commit c809666624f60b67bba5fbc082c2e5adb7598761 Author: dan_s Date: Thu Feb 26 02:31:52 2026 -0600 ObsidianDragon - DragonX ImGui Wallet Full-node GUI wallet for DragonX cryptocurrency. Built with Dear ImGui, SDL3, and OpenGL3/DX11. Features: - Send/receive shielded and transparent transactions - Autoshield with merged transaction display - Built-in CPU mining (xmrig) - Peer management and network monitoring - Wallet encryption with PIN lock - QR code generation for receive addresses - Transaction history with pagination - Console for direct RPC commands - Cross-platform (Linux, Windows) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..112eb73 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,173 @@ +# Copilot Instructions — DragonX ImGui Wallet + +## UI Layout: All values in `ui.toml` + +**Every UI layout constant must be defined in `res/themes/ui.toml` and read at runtime via the schema API.** Never hardcode pixel sizes, ratios, rounding values, thicknesses, or spacing constants directly in C++ source files. This is critical for maintainability, theming support, and hot-reload. + +### Schema API reference + +The singleton is accessed via `schema::UI()` (header: `#include "../schema/ui_schema.h"`). + +| Method | Returns | Use for | +|---|---|---| +| `drawElement(section, name)` | `DrawElementStyle` | Custom DrawList layout values (`.size`, `.height`, `.thickness`, `.radius`, `.opacity`) | +| `button(section, name)` | `ButtonStyle` | Button width/height/font | +| `input(section, name)` | `InputStyle` | Input field dimensions | +| `label(section, name)` | `LabelStyle` | Label styling | +| `table(section, name)` | `TableStyle` | Table layout | +| `window(section, name)` | `WindowStyle` | Window/dialog dimensions | +| `combo(section, name)` | `ComboStyle` | Combo box styling | +| `slider(section, name)` | `SliderStyle` | Slider styling | +| `checkbox(section, name)` | `CheckboxStyle` | Checkbox styling | +| `separator(section, name)` | `SeparatorStyle` | Separator/divider styling | + +### Section naming convention + +Sections use dot-separated paths matching the file/feature: + +- `tabs.send`, `tabs.receive`, `tabs.transactions`, `tabs.mining`, `tabs.peers`, `tabs.market` — tab-specific values +- `tabs.balance` — balance/home tab +- `components.main-layout`, `components.settings-page` — shared components +- `dialogs.about`, `dialogs.backup`, etc. — dialog-specific values +- `sidebar` — navigation sidebar + +### How to add a new layout value + +1. **Add the entry to `res/themes/ui.toml`** under the appropriate section: + ```toml + [tabs.example] + my-element = {size = 42.0} + ``` + +2. **Read it in C++** instead of using a literal: + ```cpp + // WRONG — hardcoded + float myValue = 42.0f; + + // CORRECT — schema-driven + float myValue = schema::UI().drawElement("tabs.example", "my-element").size; + ``` + +3. For values used as min/max pairs with scaling: + ```cpp + // WRONG + float h = std::max(18.0f, 24.0f * vScale); + + // CORRECT + float h = std::max( + schema::UI().drawElement("tabs.example", "row-min-height").size, + schema::UI().drawElement("tabs.example", "row-height").size * vScale + ); + ``` + +### What belongs in `ui.toml` + +- Pixel sizes (card heights, icon sizes, bar widths/heights) +- Ratios (column width ratios, max-width ratios) +- Rounding values (`FrameRounding`, corner radius) +- Thickness values (accent bars, chart lines, borders) +- Dot/circle radii +- Fade zones, padding constants +- Min/max dimension bounds +- Font selection (via schema font name strings, resolved with `S.resolveFont()`) +- Colors (via `schema::UI().resolveColor()` or color variable references like `"var(--primary)"`) +- Animation durations (transition times, fade durations, pulse speeds) +- Business logic values (fee amounts, ticker strings, buffer sizes, reward amounts) + +### What does NOT belong in `ui.toml` + +- Spacing that already goes through `Layout::spacing*()` or `spacing::dp()` + +### Legacy system: `UILayout` + +`UILayout::instance()` is the older layout system still used for fonts, typography, panels, and global spacing. New layout values should use `schema::UI().drawElement()` instead. Do not add new keys to `UILayout`. + +### Validation + +After editing `ui.toml`, always validate: +```bash +python3 -c "import toml; toml.load('res/themes/ui.toml'); print('Valid TOML')" +``` + +Or with the C++ toml++ parser (which is what the app uses): +```bash +cd build && make -j$(nproc) +``` + +### Build + +```bash +# Linux +cd build && make -j$(nproc) + +# Windows cross-compile +./build.sh --win-release +``` + +## Plans + +When asked to "create a plan", always create a new markdown document in the `docs/` directory with the plan contents. + +## Icons: Use Material Design icon font, never Unicode symbols + +**Never use raw Unicode symbols or emoji characters** (e.g. `↓`, `↗`, `⛏`, `🔍`, `📬`, `⚠️`, `ℹ`) for icons in C++ code. Always use the **Material Design Icons font** via the `ICON_MD_*` defines from `#include "../../embedded/IconsMaterialDesign.h"`. + +### Icon font API + +| Method | Size | Fallback | +|---|---|---| +| `Type().iconSmall()` | 14px | Body2 | +| `Type().iconMed()` | 18px | Body1 | +| `Type().iconLarge()` | 24px | H5 | +| `Type().iconXL()` | 40px | H3 | + +### Correct usage + +```cpp +#include "../../embedded/IconsMaterialDesign.h" + +// WRONG — raw Unicode symbol +itemSpec.leadingIcon = "↙"; + +// CORRECT — Material Design icon codepoint +itemSpec.leadingIcon = ICON_MD_CALL_RECEIVED; + +// WRONG — emoji for search +searchSpec.leadingIcon = "🔍"; + +// CORRECT — Material Design icon +searchSpec.leadingIcon = ICON_MD_SEARCH; + +// For rendering with icon font directly: +ImGui::PushFont(Type().iconSmall()); +ImGui::TextUnformatted(ICON_MD_ARROW_DOWNWARD); +ImGui::PopFont(); +``` + +### Why + +Raw Unicode symbols and emoji render inconsistently across platforms and may not be present in the loaded text fonts. The Material Design icon font is always loaded and provides consistent, scalable glyphs on both Linux and Windows. + +### Audit for Unicode symbols + +Before completing any task that touches UI code, search for and replace any raw Unicode symbols that may have been introduced. Common symbols to look for: + +| Unicode | Replacement | +|---------|-------------| +| `▶` `▷` | `ICON_MD_PLAY_ARROW` | +| `■` `□` `◼` `◻` | `ICON_MD_STOP` or `ICON_MD_SQUARE` | +| `●` `○` `◉` `◎` | `ICON_MD_FIBER_MANUAL_RECORD` or `ICON_MD_CIRCLE` | +| `↑` `↓` `←` `→` | `ICON_MD_ARROW_UPWARD`, `_DOWNWARD`, `_BACK`, `_FORWARD` | +| `↙` `↗` `↖` `↘` | `ICON_MD_CALL_RECEIVED`, `_MADE`, etc. | +| `✓` `✔` | `ICON_MD_CHECK` | +| `✗` `✕` `✖` | `ICON_MD_CLOSE` | +| `⚠` `⚠️` | `ICON_MD_WARNING` | +| `ℹ` `ℹ️` | `ICON_MD_INFO` | +| `🔍` | `ICON_MD_SEARCH` | +| `📋` | `ICON_MD_CONTENT_COPY` or `ICON_MD_DESCRIPTION` | +| `🛡` `🛡️` | `ICON_MD_SHIELD` | +| `⏳` | `ICON_MD_HOURGLASS_EMPTY` | +| `🔄` `↻` `⟳` | `ICON_MD_SYNC` or `ICON_MD_REFRESH` | +| `⚙` `⚙️` | `ICON_MD_SETTINGS` | +| `🔒` | `ICON_MD_LOCK` | +| `★` `☆` | `ICON_MD_STAR` or `ICON_MD_STAR_BORDER` | diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..35f1ee9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# Build trees per platform (build/linux/, build/windows/, build/mac/) +build/* + +# Release distributable artifacts (release/linux/, release/windows/, release/mac/) +release/ + +# Prebuilt binaries (ignore contents, keep dirs via .gitkeep) +prebuilt-binaries/dragonxd-linux/* +!prebuilt-binaries/dragonxd-linux/.gitkeep +prebuilt-binaries/dragonxd-win/* +!prebuilt-binaries/dragonxd-win/.gitkeep +prebuilt-binaries/dragonxd-mac/* +!prebuilt-binaries/dragonxd-mac/.gitkeep +prebuilt-binaries/xmrig-hac/* +!prebuilt-binaries/xmrig-hac/.gitkeep + + +# External sources / toolchains (created by scripts/setup.sh) +external/ + +# Internal docs +doc/ + +# Downloaded libsodium (built by scripts/fetch-libsodium.sh) +libs/libsodium-mac/ +libs/libsodium-win/ +libs/libsodium/ +libs/libsodium-*.tar.gz + +# dev artifacts +imgui.ini +*.bak +*.bak* +*.params +asmap.dat \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..073bb16 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,578 @@ +# DragonX Wallet - ImGui Edition +# Copyright 2024-2026 The Hush Developers +# Released under the GPLv3 + +cmake_minimum_required(VERSION 3.20) +project(ObsidianDragon + VERSION 1.0.0 + LANGUAGES C CXX + DESCRIPTION "DragonX Cryptocurrency Wallet" +) + +# C++17 standard +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Build type +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) +endif() + +# Options +option(DRAGONX_USE_SYSTEM_SDL3 "Use system SDL3 instead of fetching" ON) +option(DRAGONX_ENABLE_EMBEDDED_DAEMON "Enable embedded dragonxd support" ON) + +# Output directories +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) + +# ----------------------------------------------------------------------------- +# Dependencies +# ----------------------------------------------------------------------------- + +# OpenGL (Linux only - Windows uses DirectX 11, macOS uses frameworks) +if(NOT WIN32 AND NOT APPLE) + find_package(OpenGL REQUIRED) +endif() + +# miniz - bundled zip library (MIT / public domain) +set(MINIZ_DIR ${CMAKE_SOURCE_DIR}/libs/miniz) +set(MINIZ_SOURCES + ${MINIZ_DIR}/miniz.c + ${MINIZ_DIR}/miniz_tdef.c + ${MINIZ_DIR}/miniz_tinfl.c + ${MINIZ_DIR}/miniz_zip.c +) + +# GLAD - bundled OpenGL loader (Linux/macOS — Windows uses DX11) +set(GLAD_DIR ${CMAKE_SOURCE_DIR}/libs/glad) +if(NOT WIN32) + set(GLAD_SOURCES ${GLAD_DIR}/src/gl.c) +else() + set(GLAD_SOURCES "") +endif() +set(GLAD_INCLUDE ${GLAD_DIR}/include) +message(STATUS "Using bundled GLAD for OpenGL loading") + +# SDL3 - try system first, then fetch +if(DRAGONX_USE_SYSTEM_SDL3) + find_package(SDL3 QUIET) +endif() + +if(NOT SDL3_FOUND) + message(STATUS "SDL3 not found, will fetch from source...") + include(FetchContent) + FetchContent_Declare( + SDL3 + GIT_REPOSITORY https://github.com/libsdl-org/SDL.git + GIT_TAG 267e681a + GIT_SHALLOW FALSE + ) + set(SDL_SHARED OFF CACHE BOOL "" FORCE) + set(SDL_STATIC ON CACHE BOOL "" FORCE) + FetchContent_MakeAvailable(SDL3) +endif() + +# nlohmann/json (header-only) — used for RPC, language files, and legacy theme formats +include(FetchContent) +FetchContent_Declare( + json + GIT_REPOSITORY https://github.com/nlohmann/json.git + GIT_TAG v3.11.3 + GIT_SHALLOW TRUE +) +FetchContent_MakeAvailable(json) + +# toml++ (header-only) — used for UI schema / theme configuration files +FetchContent_Declare( + tomlplusplus + GIT_REPOSITORY https://github.com/marzer/tomlplusplus.git + GIT_TAG v3.4.0 + GIT_SHALLOW TRUE +) +FetchContent_MakeAvailable(tomlplusplus) + +# libcurl for HTTPS RPC connections (more reliable than cpp-httplib with OpenSSL 3.x) +if(WIN32) + # For Windows cross-compilation, fetch and build libcurl statically + message(STATUS "Fetching libcurl for Windows build...") + FetchContent_Declare( + curl + URL https://github.com/curl/curl/releases/download/curl-8_5_0/curl-8.5.0.tar.gz + URL_HASH SHA256=05fc17ff25b793a437a0906e0484b82172a9f4de02be5ed447e0cab8c3475add + ) + set(BUILD_CURL_EXE OFF CACHE BOOL "" FORCE) + set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) + set(CURL_STATICLIB ON CACHE BOOL "" FORCE) + set(BUILD_TESTING OFF CACHE BOOL "" FORCE) + set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) + set(CURL_DISABLE_LDAPS ON CACHE BOOL "" FORCE) + set(CURL_USE_SCHANNEL ON CACHE BOOL "" FORCE) # Use Windows native SSL + set(CURL_USE_OPENSSL OFF CACHE BOOL "" FORCE) + set(CURL_USE_LIBSSH2 OFF CACHE BOOL "" FORCE) + set(CURL_ZLIB OFF CACHE BOOL "" FORCE) + set(HTTP_ONLY ON CACHE BOOL "" FORCE) + FetchContent_MakeAvailable(curl) + set(CURL_LIBRARIES libcurl_static) + set(CURL_INCLUDE_DIRS ${curl_SOURCE_DIR}/include ${curl_BINARY_DIR}/lib/curl) +else() + find_package(CURL REQUIRED) + set(CURL_LIBRARIES CURL::libcurl) + set(CURL_INCLUDE_DIRS ${CURL_INCLUDE_DIR}) +endif() + +# libsodium - platform-specific +# Search order per platform: +# 1. Local pre-built in libs/libsodium{-mac,-win}/ (downloaded by scripts/fetch-libsodium.sh) +# 2. System libsodium via pkg-config +# 3. Auto-download from source (requires curl + C compiler for target) +set(SODIUM_LIBRARY "") +set(SODIUM_INCLUDE_DIR "") + +if(WIN32) + # Windows (MinGW cross-compile) — no pkg-config fallback; host pkg-config + # returns Linux paths that can't be used by MinGW. + if(EXISTS ${CMAKE_SOURCE_DIR}/libs/libsodium-win/lib/libsodium.a) + set(SODIUM_LIBRARY ${CMAKE_SOURCE_DIR}/libs/libsodium-win/lib/libsodium.a) + set(SODIUM_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/libs/libsodium-win/include) + elseif(EXISTS ${CMAKE_SOURCE_DIR}/libs/libsodium/lib/libsodium.a) + set(SODIUM_LIBRARY ${CMAKE_SOURCE_DIR}/libs/libsodium/lib/libsodium.a) + set(SODIUM_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/libs/libsodium/include) + endif() +elseif(APPLE) + # macOS (native or osxcross cross-compile) — use local pre-built only; + # when cross-compiling, host pkg-config returns wrong paths. + if(EXISTS ${CMAKE_SOURCE_DIR}/libs/libsodium-mac/lib/libsodium.a) + set(SODIUM_LIBRARY ${CMAKE_SOURCE_DIR}/libs/libsodium-mac/lib/libsodium.a) + set(SODIUM_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/libs/libsodium-mac/include) + endif() +else() + # Linux: prefer system libsodium, fall back to local build + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + pkg_check_modules(SODIUM QUIET libsodium) + endif() + if(NOT SODIUM_FOUND AND EXISTS ${CMAKE_SOURCE_DIR}/libs/libsodium/lib/libsodium.a) + set(SODIUM_LIBRARY ${CMAKE_SOURCE_DIR}/libs/libsodium/lib/libsodium.a) + set(SODIUM_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/libs/libsodium/include) + endif() +endif() + +# Bridge pkg-config variables to the ones used in target_link/include +if(SODIUM_FOUND AND NOT SODIUM_LIBRARY) + set(SODIUM_LIBRARY ${SODIUM_LIBRARIES}) + set(SODIUM_INCLUDE_DIR ${SODIUM_INCLUDE_DIRS}) +endif() + +# Final check: if still not found, tell the user how to get it +if(NOT SODIUM_LIBRARY AND NOT SODIUM_FOUND) + message(WARNING + "libsodium not found. Encryption features require libsodium.\n" + " Linux: sudo apt install libsodium-dev (or equivalent)\n" + " macOS: ./scripts/fetch-libsodium.sh --mac\n" + " Windows: ./scripts/fetch-libsodium.sh --win") +endif() + +message(STATUS "Sodium lib: ${SODIUM_LIBRARY}") + +# ----------------------------------------------------------------------------- +# ImGui +# ----------------------------------------------------------------------------- + +set(IMGUI_DIR ${CMAKE_SOURCE_DIR}/libs/imgui) + +set(IMGUI_SOURCES + ${IMGUI_DIR}/imgui.cpp + ${IMGUI_DIR}/imgui_draw.cpp + ${IMGUI_DIR}/imgui_tables.cpp + ${IMGUI_DIR}/imgui_widgets.cpp + ${IMGUI_DIR}/imgui_demo.cpp + ${IMGUI_DIR}/backends/imgui_impl_sdl3.cpp +) + +set(IMGUI_HEADERS + ${IMGUI_DIR}/imgui.h + ${IMGUI_DIR}/imconfig.h + ${IMGUI_DIR}/imgui_internal.h + ${IMGUI_DIR}/backends/imgui_impl_sdl3.h +) + +# Platform-specific ImGui backend +if(WIN32) + list(APPEND IMGUI_SOURCES ${IMGUI_DIR}/backends/imgui_impl_dx11.cpp) + list(APPEND IMGUI_HEADERS ${IMGUI_DIR}/backends/imgui_impl_dx11.h) +else() + list(APPEND IMGUI_SOURCES ${IMGUI_DIR}/backends/imgui_impl_opengl3.cpp) + list(APPEND IMGUI_HEADERS ${IMGUI_DIR}/backends/imgui_impl_opengl3.h) +endif() + +# ----------------------------------------------------------------------------- +# QR Code library (bundled) +# ----------------------------------------------------------------------------- + +set(QRCODE_DIR ${CMAKE_SOURCE_DIR}/libs/qrcode) + +set(QRCODE_SOURCES + ${QRCODE_DIR}/BitBuffer.cpp + ${QRCODE_DIR}/QrCode.cpp + ${QRCODE_DIR}/QrSegment.cpp +) + +# ----------------------------------------------------------------------------- +# Application Sources +# ----------------------------------------------------------------------------- + +set(APP_SOURCES + src/main.cpp + src/app.cpp + src/app_network.cpp + src/app_security.cpp + src/app_wizard.cpp + src/data/wallet_state.cpp + src/ui/theme.cpp + src/ui/theme_loader.cpp + src/ui/material/color_theme.cpp + src/ui/material/typography.cpp + src/ui/notifications.cpp + src/ui/windows/main_window.cpp + src/ui/windows/balance_tab.cpp + src/ui/windows/send_tab.cpp + src/ui/windows/receive_tab.cpp + src/ui/windows/transactions_tab.cpp + src/ui/windows/mining_tab.cpp + src/ui/windows/peers_tab.cpp + src/ui/windows/market_tab.cpp + src/ui/windows/console_tab.cpp + src/ui/windows/settings_window.cpp + src/ui/pages/settings_page.cpp + src/ui/windows/about_dialog.cpp + src/ui/windows/key_export_dialog.cpp + src/ui/windows/transaction_details_dialog.cpp + src/ui/windows/qr_popup_dialog.cpp + src/ui/windows/validate_address_dialog.cpp + src/ui/windows/address_book_dialog.cpp + src/ui/windows/shield_dialog.cpp + src/ui/windows/request_payment_dialog.cpp + src/ui/windows/block_info_dialog.cpp + src/ui/windows/import_key_dialog.cpp + src/ui/windows/export_all_keys_dialog.cpp + src/ui/windows/export_transactions_dialog.cpp + src/ui/windows/backup_wallet_dialog.cpp + src/ui/widgets/qr_code.cpp + src/rpc/rpc_client.cpp + src/rpc/rpc_worker.cpp + src/rpc/connection.cpp + src/config/settings.cpp + src/data/address_book.cpp + src/data/exchange_info.cpp + src/util/logger.cpp + src/util/base64.cpp + src/util/single_instance.cpp + src/util/i18n.cpp + src/util/platform.cpp + src/util/payment_uri.cpp + src/util/texture_loader.cpp + src/util/noise_texture.cpp + src/daemon/embedded_daemon.cpp + src/daemon/xmrig_manager.cpp + src/util/bootstrap.cpp + src/util/secure_vault.cpp + src/ui/effects/framebuffer.cpp + src/ui/effects/blur_shader.cpp + src/ui/effects/noise_texture.cpp + src/ui/effects/acrylic.cpp + src/ui/effects/imgui_acrylic.cpp + src/ui/effects/theme_effects.cpp + src/ui/effects/low_spec.cpp + src/ui/schema/color_var_resolver.cpp + src/ui/schema/element_styles.cpp + src/ui/schema/ui_schema.cpp + src/ui/schema/skin_manager.cpp + src/resources/embedded_resources.cpp +) + +# Note: The old -O0 workaround for embedded_resources.cpp is no longer needed. +# With INCBIN (.incbin assembler directive), the compiler never parses the +# binary data — the assembler streams it directly into the object file, +# using near-zero compile-time RAM instead of 12 GB+. + +# Platform-specific sources +if(WIN32) + list(APPEND APP_SOURCES + src/platform/windows_backdrop.cpp + src/platform/dx11_context.cpp + ) +endif() + +set(APP_HEADERS + src/app.h + src/config/version.h + src/data/wallet_state.h + src/ui/theme.h + src/ui/theme_loader.h + src/ui/notifications.h + src/ui/windows/main_window.h + src/ui/windows/balance_tab.h + src/ui/windows/send_tab.h + src/ui/windows/receive_tab.h + src/ui/windows/transactions_tab.h + src/ui/windows/mining_tab.h + src/ui/windows/peers_tab.h + src/ui/windows/market_tab.h + src/ui/windows/settings_window.h + src/ui/windows/about_dialog.h + src/ui/windows/key_export_dialog.h + src/ui/windows/transaction_details_dialog.h + src/ui/windows/qr_popup_dialog.h + src/ui/windows/validate_address_dialog.h + src/ui/windows/address_book_dialog.h + src/ui/windows/shield_dialog.h + src/ui/windows/request_payment_dialog.h + src/ui/windows/block_info_dialog.h + src/ui/windows/import_key_dialog.h + src/ui/windows/export_all_keys_dialog.h + src/ui/windows/export_transactions_dialog.h + src/ui/windows/backup_wallet_dialog.h + src/ui/widgets/qr_code.h + src/rpc/rpc_client.h + src/rpc/rpc_worker.h + src/rpc/connection.h + src/rpc/types.h + src/config/settings.h + src/data/address_book.h + src/data/exchange_info.h + src/util/logger.h + src/util/base64.h + src/util/single_instance.h + src/util/i18n.h + src/util/platform.h + src/util/payment_uri.h + src/util/secure_vault.h + src/daemon/embedded_daemon.h + src/daemon/xmrig_manager.h + src/ui/effects/framebuffer.h + src/ui/effects/blur_shader.h + src/ui/effects/noise_texture.h + src/ui/effects/acrylic.h +) + +# Platform-specific headers +if(WIN32) + list(APPEND APP_HEADERS + src/platform/windows_backdrop.h + src/platform/dx11_context.h + ) +endif() + +# ----------------------------------------------------------------------------- +# Executable +# ----------------------------------------------------------------------------- + +# Windows application icon + VERSIONINFO (.rc -> .res -> linked into .exe) +if(WIN32) + set(OBSIDIAN_ICO_PATH "${CMAKE_SOURCE_DIR}/res/img/ObsidianDragon.ico") + # Version numbers for the VERSIONINFO resource block + set(DRAGONX_VER_MAJOR 1) + set(DRAGONX_VER_MINOR 0) + set(DRAGONX_VER_PATCH 0) + set(DRAGONX_VERSION "1.0.0") + configure_file( + ${CMAKE_SOURCE_DIR}/res/ObsidianDragon.rc + ${CMAKE_BINARY_DIR}/generated/ObsidianDragon.rc + @ONLY + ) + set(WIN_RC_FILE ${CMAKE_BINARY_DIR}/generated/ObsidianDragon.rc) +endif() + +# Generate INCBIN font embedding source with absolute paths to .ttf files +configure_file( + ${CMAKE_SOURCE_DIR}/src/embedded/embedded_fonts.cpp.in + ${CMAKE_BINARY_DIR}/generated/embedded_fonts.cpp + @ONLY +) + +add_executable(ObsidianDragon + ${APP_SOURCES} + ${CMAKE_BINARY_DIR}/generated/embedded_fonts.cpp + ${IMGUI_SOURCES} + ${QRCODE_SOURCES} + ${GLAD_SOURCES} + ${MINIZ_SOURCES} + ${WIN_RC_FILE} +) + +target_include_directories(ObsidianDragon PRIVATE + ${CMAKE_SOURCE_DIR}/src + ${CMAKE_SOURCE_DIR}/src/embedded + ${CMAKE_SOURCE_DIR}/src/resources + ${CMAKE_SOURCE_DIR}/libs + ${CMAKE_BINARY_DIR}/generated + ${IMGUI_DIR} + ${IMGUI_DIR}/backends + ${QRCODE_DIR} + ${SODIUM_INCLUDE_DIR} + ${GLAD_INCLUDE} + ${CURL_INCLUDE_DIRS} + ${MINIZ_DIR} +) + +target_link_libraries(ObsidianDragon PRIVATE + SDL3::SDL3 + nlohmann_json::nlohmann_json + tomlplusplus::tomlplusplus + ${CURL_LIBRARIES} + ${SODIUM_LIBRARY} +) + +# Platform-specific settings +if(WIN32) + target_link_libraries(ObsidianDragon PRIVATE ws2_32 winmm imm32 version setupapi dwmapi crypt32 wldap32 psapi d3d11 dxgi d3dcompiler dcomp) + # Hide console window in release builds + if(CMAKE_BUILD_TYPE STREQUAL "Release") + set_target_properties(ObsidianDragon PROPERTIES WIN32_EXECUTABLE TRUE) + endif() +elseif(APPLE) + target_link_libraries(ObsidianDragon PRIVATE "-framework Cocoa" "-framework IOKit" "-framework CoreVideo" "-framework OpenGL") + # When cross-compiling with osxcross, link the compiler-rt builtins (provides ___isPlatformVersionAtLeast etc.) + if(CMAKE_CROSSCOMPILING AND DEFINED OSXCROSS_COMPILER_RT) + target_link_libraries(ObsidianDragon PRIVATE "${OSXCROSS_COMPILER_RT}") + endif() +elseif(UNIX) + find_package(Threads REQUIRED) + target_link_libraries(ObsidianDragon PRIVATE OpenGL::GL Threads::Threads ${CMAKE_DL_LIBS}) +endif() + +# Compiler warnings +if(MSVC) + target_compile_options(ObsidianDragon PRIVATE /W4) +else() + target_compile_options(ObsidianDragon PRIVATE -Wall -Wextra -Wpedantic) +endif() + +# Compile definitions +target_compile_definitions(ObsidianDragon PRIVATE + $<$:DRAGONX_DEBUG> +) +if(WIN32) + target_compile_definitions(ObsidianDragon PRIVATE DRAGONX_USE_DX11) +else() + target_compile_definitions(ObsidianDragon PRIVATE DRAGONX_HAS_GLAD) +endif() + +# ----------------------------------------------------------------------------- +# Copy resources +# ----------------------------------------------------------------------------- + +# Copy font file - try local first, then SilentDragonX +if(EXISTS ${CMAKE_SOURCE_DIR}/res/fonts/Ubuntu-R.ttf) + configure_file( + ${CMAKE_SOURCE_DIR}/res/fonts/Ubuntu-R.ttf + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/fonts/Ubuntu-R.ttf + COPYONLY + ) +elseif(EXISTS ${CMAKE_SOURCE_DIR}/../SilentDragonX/res/Ubuntu-R.ttf) + configure_file( + ${CMAKE_SOURCE_DIR}/../SilentDragonX/res/Ubuntu-R.ttf + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/fonts/Ubuntu-R.ttf + COPYONLY + ) +endif() + +# Copy language files +file(GLOB LANG_FILES ${CMAKE_SOURCE_DIR}/res/lang/*.json) +if(LANG_FILES) + foreach(LANG_FILE ${LANG_FILES}) + get_filename_component(LANG_FILENAME ${LANG_FILE} NAME) + configure_file( + ${LANG_FILE} + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/lang/${LANG_FILENAME} + COPYONLY + ) + endforeach() + message(STATUS " Language files: ${LANG_FILES}") +endif() + +# Embed ui.toml into the binary so it's always available at runtime +include(${CMAKE_SOURCE_DIR}/cmake/EmbedResources.cmake) +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/generated) +embed_resource( + ${CMAKE_SOURCE_DIR}/res/themes/ui.toml + ${CMAKE_BINARY_DIR}/generated/ui_toml_embedded.h + ui_toml +) + +# Note: xmrig is embedded via build.sh (embedded_data.h) for Windows builds, +# following the same pattern as daemon embedding. + +# Copy theme files at BUILD time (not just cmake configure time) +# so edits to res/themes/*.toml are picked up by 'make' without re-running cmake. +file(GLOB THEME_FILES ${CMAKE_SOURCE_DIR}/res/themes/*.toml) +if(THEME_FILES) + foreach(THEME_FILE ${THEME_FILES}) + get_filename_component(THEME_FILENAME ${THEME_FILE} NAME) + add_custom_command( + OUTPUT ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/themes/${THEME_FILENAME} + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${THEME_FILE} + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/themes/${THEME_FILENAME} + DEPENDS ${THEME_FILE} + COMMENT "Copying ${THEME_FILENAME}" + ) + list(APPEND THEME_OUTPUTS ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/themes/${THEME_FILENAME}) + endforeach() + add_custom_target(copy_themes ALL DEPENDS ${THEME_OUTPUTS}) + add_dependencies(ObsidianDragon copy_themes) + message(STATUS " Theme files: ${THEME_FILES}") +endif() + +# Copy image files (including backgrounds/ subdirectories and logos/) +file(GLOB IMG_ROOT_FILES ${CMAKE_SOURCE_DIR}/res/img/*.png ${CMAKE_SOURCE_DIR}/res/img/*.jpg ${CMAKE_SOURCE_DIR}/res/img/*.ico) +file(GLOB IMG_BG_TEXTURE_FILES ${CMAKE_SOURCE_DIR}/res/img/backgrounds/texture/*.png ${CMAKE_SOURCE_DIR}/res/img/backgrounds/texture/*.jpg) +file(GLOB IMG_BG_GRADIENT_FILES ${CMAKE_SOURCE_DIR}/res/img/backgrounds/gradient/*.png ${CMAKE_SOURCE_DIR}/res/img/backgrounds/gradient/*.jpg) +file(GLOB IMG_LOGO_FILES ${CMAKE_SOURCE_DIR}/res/img/logos/*.png ${CMAKE_SOURCE_DIR}/res/img/logos/*.jpg) +foreach(IMG_FILE ${IMG_ROOT_FILES}) + get_filename_component(IMG_FILENAME ${IMG_FILE} NAME) + configure_file(${IMG_FILE} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/img/${IMG_FILENAME} COPYONLY) +endforeach() +foreach(IMG_FILE ${IMG_BG_TEXTURE_FILES}) + get_filename_component(IMG_FILENAME ${IMG_FILE} NAME) + configure_file(${IMG_FILE} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/img/backgrounds/texture/${IMG_FILENAME} COPYONLY) +endforeach() +foreach(IMG_FILE ${IMG_BG_GRADIENT_FILES}) + get_filename_component(IMG_FILENAME ${IMG_FILE} NAME) + configure_file(${IMG_FILE} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/img/backgrounds/gradient/${IMG_FILENAME} COPYONLY) +endforeach() +foreach(IMG_FILE ${IMG_LOGO_FILES}) + get_filename_component(IMG_FILENAME ${IMG_FILE} NAME) + configure_file(${IMG_FILE} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res/img/logos/${IMG_FILENAME} COPYONLY) +endforeach() +message(STATUS " Image files: ${IMG_ROOT_FILES} ${IMG_BG_TEXTURE_FILES} ${IMG_BG_GRADIENT_FILES} ${IMG_LOGO_FILES}") + +# ----------------------------------------------------------------------------- +# Install +# ----------------------------------------------------------------------------- + +install(TARGETS ObsidianDragon + RUNTIME DESTINATION bin +) + +install(DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/res + DESTINATION share/ObsidianDragon + OPTIONAL +) + +# ----------------------------------------------------------------------------- +# Summary +# ----------------------------------------------------------------------------- + +message(STATUS "") +message(STATUS "DragonX ImGui Wallet Configuration:") +message(STATUS " Version: ${PROJECT_VERSION}") +message(STATUS " Build type: ${CMAKE_BUILD_TYPE}") +message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") +message(STATUS " ImGui dir: ${IMGUI_DIR}") +message(STATUS " SDL3 found: ${SDL3_FOUND}") +message(STATUS " Sodium lib: ${SODIUM_LIBRARY}") +message(STATUS "") diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6fddadc --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,39 @@ +# Code of Conduct + +## Our Pledge + +We are committed to making participation in this project a welcoming experience for everyone, regardless of background or identity. + +## Our Standards + +**Positive behaviour includes:** + +- Being respectful and constructive in discussions +- Accepting feedback gracefully +- Focusing on what is best for the project and community +- Showing empathy towards other community members + +**Unacceptable behaviour includes:** + +- Harassment, insults, or derogatory comments +- Personal or political attacks +- Publishing others' private information without consent +- Other conduct which could reasonably be considered inappropriate + +## Enforcement + +Project maintainers are responsible for clarifying standards and will take appropriate corrective action in response to unacceptable behaviour. + +Maintainers have the right to remove, edit, or reject comments, commits, issues, and other contributions that violate this Code of Conduct. + +## Scope + +This Code of Conduct applies within all project spaces — issues, pull requests, discussions, and community channels. + +## Reporting + +Instances of unacceptable behaviour may be reported to the project maintainers. All complaints will be reviewed and responded to appropriately. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..376ee00 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# Contributing to ObsidianDragon + +Thank you for your interest in contributing! This guide will help you get started. + +## Getting Started + +1. Fork the repository +2. Clone your fork and create a branch: + ```bash + git clone https://git.hush.is//ObsidianDragon.git + cd ObsidianDragon + git checkout -b my-feature + ``` +3. Install dependencies: + ```bash + ./scripts/setup.sh + ``` +4. Build: + ```bash + ./build.sh --linux-release # or --win-release, --mac-release + ``` + +## Development Workflow + +### Code Style + +- C++17 standard +- Use the Material Design icon font (`ICON_MD_*` defines) — never raw Unicode symbols +- UI layout values go in `res/themes/ui.toml`, read via `schema::UI()` — never hardcode pixel sizes +- Use the `RPCWorker` for all RPC calls — never block the main thread with synchronous curl + +See `.github/copilot-instructions.md` for detailed coding standards. + +### Building + +```bash +# Linux debug build (fastest iteration) +cd build && make -j$(nproc) + +# Full release builds +./build.sh --linux-release +./build.sh --win-release +./build.sh --mac-release +``` + +### Testing + +Run the wallet and verify: +- Daemon connection and sync +- Lock screen / PIN unlock +- Send and receive transactions +- All tabs render correctly + +## Submitting Changes + +1. Commit with clear, descriptive messages +2. Push to your fork +3. Open a Pull Request against `main` +4. Describe what changed and why + +### Pull Request Guidelines + +- Keep PRs focused — one feature or fix per PR +- Ensure the project builds on Linux (`make -j$(nproc)`) +- Test cross-compilation if touching platform-specific code (`./build.sh --win-release`) +- Update `res/themes/ui.toml` if adding new UI layout values + +## Reporting Issues + +- Use the [issue tracker](https://git.hush.is/dragonx/ObsidianDragon/issues) +- Include: OS, wallet version, steps to reproduce, expected vs actual behaviour +- For crashes: include any terminal output + +## License + +By contributing, you agree that your contributions will be licensed under the GPLv3. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5621e2b --- /dev/null +++ b/README.md @@ -0,0 +1,226 @@ +# DragonX Wallet - ImGui Edition + +A lightweight, portable cryptocurrency wallet for DragonX (DRGX), built with Dear ImGui. + +![License](https://img.shields.io/badge/License-GPLv3-blue.svg) +![Platform](https://img.shields.io/badge/Platform-Linux%20%7C%20Windows%20%7C%20macOS-green.svg) + +## Features + +- **Full Node Support**: Connects to dragonxd for complete blockchain verification +- **Shielded Transactions**: Full z-address support with encrypted memos +- **Integrated Mining**: CPU mining controls with hashrate monitoring +- **Market Data**: Real-time price charts from CoinGecko +- **QR Codes**: Generate and display QR codes for receiving addresses +- **Multi-language**: i18n support (English, Spanish, more coming) +- **Lightweight**: ~5-10MB binary vs ~50MB+ for Qt version +- **Fast Builds**: Compiles in seconds, not minutes + +## Screenshots + +

+ +
+ +
+ +

+ +## Building + +### Quick Setup + +The setup script detects your OS, installs all build dependencies, and validates your environment: + +```bash +./scripts/setup.sh # Install core build deps (interactive) +./scripts/setup.sh --check # Just report what's missing +./scripts/setup.sh --all # Core + Windows/macOS cross-compile + Sapling params +./scripts/setup.sh --win # Also install mingw-w64 + libsodium-win +``` + +### Manual Prerequisites + +
+Click to expand manual install commands + +**Linux (Ubuntu/Debian):** +``` +sudo apt install build-essential cmake git pkg-config +sudo apt install libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev libxinerama-dev libxi-dev +sudo apt install libsodium-dev libcurl4-openssl-dev +``` + +**Linux (Arch):** +``` +sudo pacman -S base-devel cmake git pkg-config mesa libx11 libxcursor libxrandr libxinerama libxi libsodium curl +``` + +**macOS:** +``` +xcode-select --install +brew install cmake +``` + +**Windows:** +- Visual Studio 2019+ with C++ workload +- CMake 3.20+ + +
+ +### Binaries +Download linux and windows binaries of latest releases and place in binary directories: + +**DragonX daemon** (https://git.hush.is/hush/hush3): +- prebuilt-binaries/dragonxd-linux/ +- prebuilt-binaries/dragonxd-win/ +- prebuilt-binaries/dragonxd-mac/ + +**xmrig HAC fork** (https://git.hush.is/dragonx/xmrig-hac): +- prebuilt-binaries/xmrig-hac/ + + +## Build Steps + +``` +### Clone repository (if not already) +git clone https://git.hush.is/dragonx/ObsidianDragon.git +cd ObsidianDragon/ +``` + +### Windows Build + +``` +./build.sh --win-release +``` + +### Release Build + +``` +./build.sh --linux-release # Linux release + AppImage +./build.sh --win-release # Windows cross-compile +./build.sh --mac-release # macOS .app bundle + DMG +./build.sh --clean --linux-release # Clean + Release +``` + +## Running + +1. **Start dragonxd** (if not using embedded daemon): + ``` + dragonxd -daemon + ``` + +2. **Run the wallet**: + ``` + cd build/bin + ./ObsidianDragon + ``` + +The wallet will automatically connect to the daemon using credentials from \`~/.hush/DRAGONX/DRAGONX.conf\`. +### Using Custom Node Binaries + +The wallet checks its **own directory first** when looking for DragonX node binaries. This means you can test new or different branch builds of `hush-arrakis-chain`/`hushd` without waiting for a new wallet release: + +1. Build or download the node binaries you want to test +2. Place them in the same directory as the wallet executable (e.g. `build/bin/`) +3. Launch the wallet — it will use the local binaries instead of the bundled ones + +**Search order:** +1. Wallet executable directory (highest priority) +2. Embedded/extracted daemon (app data directory) +3. System-wide locations (`/usr/local/bin`, `~/hush3/src`, etc.) + +This is useful for testing new branches or hotfixes to the node software before they are bundled into a wallet release. +## Configuration + +Configuration is stored in \`~/.hush/DRAGONX/DRAGONX.conf\`: + +``` +rpcuser=your_rpc_user +rpcpassword=your_rpc_password +rpcport=21769 +``` + +## Project Structure + +\`\`\` +ObsidianDragon/ +├── src/ +│ ├── main.cpp # Entry point, SDL/ImGui setup +│ ├── app.cpp/h # Main application class +│ ├── wallet_state.h # Wallet data structures +│ ├── version.h # Version definitions +│ ├── ui/ +│ │ ├── theme.cpp/h # DragonX theme +│ │ └── windows/ # UI tabs and dialogs +│ ├── rpc/ +│ │ ├── rpc_client.cpp # JSON-RPC client +│ │ └── connection.cpp # Daemon connection +│ ├── config/ +│ │ └── settings.cpp # Settings persistence +│ ├── util/ +│ │ ├── i18n.cpp # Internationalization +│ │ └── ... +│ └── daemon/ +│ └── embedded_daemon.cpp +├── res/ +│ ├── fonts/ # Ubuntu font +│ └── lang/ # Translation files +├── libs/ +│ └── qrcode/ # QR code generation +├── CMakeLists.txt +├── build-release.sh # Build script +└── create-appimage.sh # AppImage packaging +\`\`\` + +## Dependencies + +Fetched automatically by CMake (no manual install needed): + +- **[SDL3](https://github.com/libsdl-org/SDL)** — Cross-platform windowing/input +- **[nlohmann/json](https://github.com/nlohmann/json)** — JSON parsing +- **[toml++](https://github.com/marzer/tomlplusplus)** — TOML parsing (UI schema/themes) +- **[libcurl](https://curl.se/libcurl/)** — HTTPS RPC transport (system on Linux, fetched on Windows) + +Bundled in `libs/`: + +- **[Dear ImGui](https://github.com/ocornut/imgui)** — Immediate mode GUI +- **[libsodium](https://libsodium.org)** — Cryptographic operations (fetched by `scripts/fetch-libsodium.sh`) +- **[QR-Code-generator](https://github.com/nayuki/QR-Code-generator)** — QR code rendering +- **[miniz](https://github.com/richgel999/miniz)** — ZIP compression +- **[GLAD](https://glad.dav1d.de/)** — OpenGL loader (Linux/macOS) +- **[stb_image](https://github.com/nothings/stb)** — Image loading +- **[incbin](https://github.com/graphitemaster/incbin)** — Binary resource embedding (Windows builds) + +## Keyboard Shortcuts + +| Shortcut | Action | +|----------|--------| +| Ctrl+, | Settings | +| F5 | Refresh | +| Alt+F4 | Exit | + +## Translation + +To add a new language: + +1. Copy \`res/lang/es.json\` to \`res/lang/.json\` +2. Translate all strings +3. The language will appear in Settings automatically + +## License + +This project is licensed under the GNU General Public License v3 (GPLv3). + +## Credits + +- The Hush Developers +- DragonX Community +- [Dear ImGui](https://github.com/ocornut/imgui) by Omar Cornut +- [SDL](https://libsdl.org/) by Sam Lantinga + +## Links + +- Website: https://dragonx.is +- Explorer: https://explorer.dragonx.is +- Source: https://git.hush.is/dragonx/ObsidianDragon diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..0bed359 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,53 @@ +# Security Policy + +## Reporting a Vulnerability + +ObsidianDragon is a cryptocurrency wallet that handles private keys and funds. We take security seriously. + +**Do NOT report security vulnerabilities through public issues.** + +Instead, please report them privately: + +- Email: security@dragonx.is +- Or contact the maintainers directly through the DragonX community channels + +### What to Include + +- Description of the vulnerability +- Steps to reproduce +- Potential impact +- Suggested fix (if any) + +### Response Timeline + +- **Acknowledgement**: Within 48 hours +- **Assessment**: Within 1 week +- **Fix**: As soon as possible, depending on severity + +### Scope + +The following are in scope: +- Private key exposure or theft +- Wallet passphrase/PIN bypass +- RPC credential leakage +- Remote code execution +- Fund loss or misdirection +- Daemon communication interception + +### Recognition + +We appreciate responsible disclosure and will credit reporters in release notes (unless anonymity is preferred). + +## Supported Versions + +| Version | Supported | +|---------|-----------| +| Latest release | Yes | +| Older releases | Best effort | + +## Security Best Practices for Users + +- Always verify downloads against published checksums +- Use a strong passphrase or PIN to encrypt your wallet +- Keep your system and wallet software up to date +- Back up your wallet regularly diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES new file mode 100644 index 0000000..013221f --- /dev/null +++ b/THIRD_PARTY_LICENSES @@ -0,0 +1,401 @@ +# Third-Party Licenses + +This file documents all third-party libraries used in ObsidianDragon, +their versions, authors, and license texts. + +--- + +## 1. Dear ImGui — v1.92.6 WIP + +- **Source:** https://github.com/ocornut/imgui +- **Copyright:** (c) 2014-2026 Omar Cornut +- **License:** MIT + +``` +The MIT License (MIT) + +Copyright (c) 2014-2026 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +--- + +## 2. SDL3 — v3.5.0 (267e681a) + +- **Source:** https://github.com/libsdl-org/SDL +- **Copyright:** (c) 1997-2026 Sam Lantinga +- **License:** zlib + +``` +Copyright (C) 1997-2026 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + +--- + +## 3. nlohmann/json — v3.11.3 + +- **Source:** https://github.com/nlohmann/json +- **Copyright:** (c) 2013-2022 Niels Lohmann +- **License:** MIT + +``` +MIT License + +Copyright (c) 2013-2022 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +--- + +## 4. toml++ — v3.4.0 + +- **Source:** https://github.com/marzer/tomlplusplus +- **Copyright:** (c) Mark Gillard +- **License:** MIT + +``` +MIT License + +Copyright (c) Mark Gillard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +--- + +## 5. stb_image — v2.30 + +- **Location:** `libs/stb_image.h` +- **Source:** https://github.com/nothings/stb +- **Copyright:** (c) 2017 Sean Barrett +- **License:** MIT or Public Domain (dual-licensed, choose either) + +``` +ALTERNATIVE A - MIT License + +Copyright (c) 2017 Sean Barrett + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +--- + +## 6. miniz — v3.1.0 + +- **Location:** `libs/miniz/` +- **Source:** https://github.com/richgel999/miniz +- **Copyright:** Rich Geldreich +- **License:** Unlicense (Public Domain) + +``` +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to +``` + +--- + +## 7. QR Code generator library (C++) + +- **Location:** `libs/qrcode/` +- **Source:** https://www.nayuki.io/page/qr-code-generator-library +- **Copyright:** (c) Project Nayuki +- **License:** MIT + +``` +Copyright (c) Project Nayuki. (MIT License) +https://www.nayuki.io/page/qr-code-generator-library + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: +- The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +- The Software is provided "as is", without warranty of any kind, express or + implied, including but not limited to the warranties of merchantability, + fitness for a particular purpose and noninfringement. In no event shall the + authors or copyright holders be liable for any claim, damages or other + liability, whether in an action of contract, tort or otherwise, arising from, + out of or in connection with the Software or the use or other dealings in the + Software. +``` + +--- + +## 8. GLAD (OpenGL Loader) + +- **Location:** `libs/glad/` +- **Source:** https://glad.dav1d.de (generator) / https://github.com/Dav1dde/glad +- **License:** Public Domain / MIT + +Generated code from the GLAD loader generator is in the public domain. +The GLAD generator itself is MIT-licensed. The OpenGL specifications +used to generate the loader are copyright The Khronos Group Inc. under +the Apache License 2.0: + +``` +Copyright (c) 2013-2020 The Khronos Group Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +--- + +## 9. incbin + +- **Location:** `libs/incbin.h` +- **License:** Public Domain + +Based on the public-domain incbin technique. Adapted for DragonX Wallet +by The Hush Developers, 2024-2026. + +--- + +## 10. libsodium — v1.0.18 (macOS pre-built) + +- **Location:** `libs/libsodium-mac/` +- **Source:** https://github.com/jedisct1/libsodium +- **Copyright:** (c) 2013-2020 Frank Denis +- **License:** ISC + +``` +ISC License + +Copyright (c) 2013-2020 +Frank Denis + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +``` + +--- + +## 11. libcurl — v8.5.0 (Windows cross-compile only) + +- **Source:** https://github.com/curl/curl +- **Copyright:** (c) 1996-2024 Daniel Stenberg +- **License:** curl (MIT-style) + +``` +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2024, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. +``` + +--- + +## 12. Material Design Icons Font + +- **Location:** `res/fonts/MaterialIcons-Regular.ttf` +- **Source:** https://github.com/google/material-design-icons +- **Copyright:** (c) Google Inc. +- **License:** Apache License 2.0 + +The full text of the Apache License 2.0 is available at: +https://www.apache.org/licenses/LICENSE-2.0 + +--- + +## 13. IconFontCppHeaders + +- **Location:** `src/embedded/IconsMaterialDesign.h` +- **Source:** https://github.com/juliettef/IconFontCppHeaders +- **Copyright:** (c) 2017 Juliette Foucaut and Doug Binks +- **License:** zlib + +``` +Copyright (c) 2017 Juliette Foucaut and Doug Binks + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + +--- + +## 14. Ubuntu Font Family + +- **Location:** `res/fonts/Ubuntu-Light.ttf`, `Ubuntu-Medium.ttf`, `Ubuntu-R.ttf` +- **Source:** https://design.ubuntu.com/font +- **Copyright:** (c) 2010-2011 Canonical Ltd. +- **License:** Ubuntu Font Licence v1.0 + +The full text of the Ubuntu Font Licence v1.0 is available at: +https://ubuntu.com/legal/font-licence diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..ffd71be --- /dev/null +++ b/build.sh @@ -0,0 +1,1049 @@ +#!/bin/bash +# DragonX ImGui Wallet - Unified Build Script +# Copyright 2024-2026 The Hush Developers +# Released under the GPLv3 +# +# Usage: +# ./build.sh # Dev build (Linux, debug-friendly) +# ./build.sh --linux-release # Linux release + AppImage +# ./build.sh --win-release # Windows cross-compile (mingw-w64) +# ./build.sh --mac-release # macOS .app bundle + DMG +# ./build.sh --linux-release --win-release # Multiple targets +# ./build.sh --clean --win-release # Clean first, then build +# +# Prerequisites: +# Linux: cmake, g++, libsdl3-dev (or fetched), libsodium-dev +# Windows: mingw-w64 (posix threads), cmake +# macOS (native): Xcode CLT, cmake, create-dmg (brew install create-dmg) +# macOS (cross from Linux): osxcross + macOS SDK, genisoimage, icnsutils + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +VERSION="1.0.0" + +# ── Colours ────────────────────────────────────────────────────────────────── +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +CYAN='\033[0;36m' +NC='\033[0m' + +info() { echo -e "${GREEN}[*]${NC} $1"; } +warn() { echo -e "${YELLOW}[!]${NC} $1"; } +err() { echo -e "${RED}[ERROR]${NC} $1"; } +header(){ echo -e "\n${CYAN}══════════════════════════════════════════════════════════${NC}"; echo -e "${CYAN} $1${NC}"; echo -e "${CYAN}══════════════════════════════════════════════════════════${NC}"; } + +JOBS=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4) + +# ── Defaults ───────────────────────────────────────────────────────────────── +DO_DEV=false +DO_LINUX=false +DO_WIN=false +DO_MAC=false +CLEAN=false +BUILD_TYPE="Release" + +usage() { + cat < release/linux/ + --win-release Windows cross-compile (mingw-w64) -> release/windows/ + --mac-release macOS .app bundle + DMG -> release/mac/ + + Build trees are stored under build/{linux,windows,mac}/ + +Options: + -c, --clean Remove build artifacts before building + -d, --debug Use Debug build type instead of Release + -j N Parallel jobs (default: $JOBS) + -h, --help Show this help + +Cross-compiling from Linux: + Windows: sudo apt install mingw-w64 + macOS: Requires osxcross (https://github.com/tpoechtrager/osxcross) + export OSXCROSS=/path/to/osxcross + sudo apt install genisoimage icnsutils # DMG + icon tools + +Examples: + $0 # Quick dev build (Linux) + $0 --linux-release # Linux release + AppImage + $0 --win-release # Windows cross-compile + $0 --mac-release # macOS bundle + DMG (native or osxcross) + $0 --clean --linux-release --win-release # Clean + both +EOF + exit 0 +} + +# ── Parse args ─────────────────────────────────────────────────────────────── +while [[ $# -gt 0 ]]; do + case $1 in + --linux-release) DO_LINUX=true; shift ;; + --win-release) DO_WIN=true; shift ;; + --mac-release) DO_MAC=true; shift ;; + -c|--clean) CLEAN=true; shift ;; + -d|--debug) BUILD_TYPE="Debug"; shift ;; + -j) JOBS="$2"; shift 2 ;; + -h|--help) usage ;; + *) err "Unknown option: $1"; usage ;; + esac +done + +# No release target → dev build (native, no packaging) +if ! $DO_LINUX && ! $DO_WIN && ! $DO_MAC; then + DO_DEV=true +fi + +# ── Helper: find resource files ────────────────────────────────────────────── +find_sapling_params() { + local dirs=( + "$HOME/.zcash-params" + "$HOME/.hush-params" + "$SCRIPT_DIR/../SilentDragonX" + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-linux" + "$SCRIPT_DIR" + ) + for d in "${dirs[@]}"; do + if [[ -f "$d/sapling-spend.params" && -f "$d/sapling-output.params" ]]; then + SAPLING_SPEND="$d/sapling-spend.params" + SAPLING_OUTPUT="$d/sapling-output.params" + info "Found Sapling params in $d" + return 0 + fi + done + warn "Sapling params not found — embedded resources will be unavailable" + return 1 +} + +find_asmap() { + local paths=( + "$SCRIPT_DIR/external/hush3/asmap.dat" + "$SCRIPT_DIR/external/hush3/contrib/asmap/asmap.dat" + "$HOME/hush3/asmap.dat" + "$HOME/hush3/contrib/asmap/asmap.dat" + "$SCRIPT_DIR/../asmap.dat" + "$SCRIPT_DIR/asmap.dat" + "$SCRIPT_DIR/../SilentDragonX/asmap.dat" + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-linux/asmap.dat" + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-win/asmap.dat" + ) + for p in "${paths[@]}"; do + if [[ -f "$p" ]]; then + ASMAP_DAT="$p" + info "Found asmap.dat at $p" + return 0 + fi + done + return 1 +} + +# ── Helper: bundle daemon binaries into a target dir ───────────────────────── +bundle_linux_daemon() { + local dest="$1" + local found=0 + + local launcher_paths=( + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-linux/hush-arrakis-chain" + "$SCRIPT_DIR/../hush-arrakis-chain" + "$SCRIPT_DIR/external/hush3/src/hush-arrakis-chain" + "$HOME/hush3/src/hush-arrakis-chain" + ) + for p in "${launcher_paths[@]}"; do + if [[ -f "$p" ]]; then + cp "$p" "$dest/hush-arrakis-chain"; chmod +x "$dest/hush-arrakis-chain" + info " Bundled hush-arrakis-chain"; found=1; break + fi + done + + local hushd_paths=( + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-linux/hushd" + "$SCRIPT_DIR/../hushd" + "$SCRIPT_DIR/external/hush3/src/hushd" + "$HOME/hush3/src/hushd" + ) + for p in "${hushd_paths[@]}"; do + if [[ -f "$p" ]]; then + cp "$p" "$dest/hushd"; chmod +x "$dest/hushd" + info " Bundled hushd"; break + fi + done + + local dragonxd_paths=( + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-linux/dragonxd" + "$SCRIPT_DIR/../dragonxd" + "$SCRIPT_DIR/external/hush3/src/dragonxd" + "$HOME/hush3/src/dragonxd" + ) + for p in "${dragonxd_paths[@]}"; do + if [[ -f "$p" ]]; then + cp "$p" "$dest/dragonxd"; chmod +x "$dest/dragonxd" + info " Bundled dragonxd"; break + fi + done + + # asmap.dat + find_asmap && cp "$ASMAP_DAT" "$dest/asmap.dat" && info " Bundled asmap.dat" + + return $found +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# DEV BUILD (native, no packaging) +# ═══════════════════════════════════════════════════════════════════════════════ +build_dev() { + header "Dev Build ($(uname -s) / $BUILD_TYPE)" + local bd="$SCRIPT_DIR/build/linux" + + if $CLEAN; then + info "Cleaning $bd ..."; rm -rf "$bd" + fi + mkdir -p "$bd" && cd "$bd" + + info "Configuring ..." + cmake "$SCRIPT_DIR" \ + -DCMAKE_BUILD_TYPE="$BUILD_TYPE" \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DDRAGONX_USE_SYSTEM_SDL3=ON + + info "Building with $JOBS jobs ..." + cmake --build . -j "$JOBS" + + [[ -f "bin/ObsidianDragon" ]] || { err "Build failed"; exit 1; } + info "Dev binary: $bd/bin/ObsidianDragon ($(du -h bin/ObsidianDragon | cut -f1))" +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# RELEASE: LINUX — build + strip + bundle daemon + AppImage +# ═══════════════════════════════════════════════════════════════════════════════ +build_release_linux() { + header "Release: Linux x86_64" + local bd="$SCRIPT_DIR/build/linux" + local out="$SCRIPT_DIR/release/linux" + + if $CLEAN; then + info "Cleaning $bd ..."; rm -rf "$bd" + fi + mkdir -p "$bd" && cd "$bd" + + # ── Compile ────────────────────────────────────────────────────────────── + info "Configuring ..." + cmake "$SCRIPT_DIR" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DDRAGONX_USE_SYSTEM_SDL3=ON + + info "Building with $JOBS jobs ..." + cmake --build . -j "$JOBS" + + [[ -f "bin/ObsidianDragon" ]] || { err "Linux build failed"; exit 1; } + + info "Stripping ..." + strip bin/ObsidianDragon + info "Binary: $(du -h bin/ObsidianDragon | cut -f1)" + + # ── Bundle daemon ──────────────────────────────────────────────────────── + bundle_linux_daemon "bin" || warn "Daemon not bundled — wallet-only build" + + # ── Package: release/linux/ ────────────────────────────────────────────── + rm -rf "$out" + mkdir -p "$out" + + cp bin/ObsidianDragon "$out/" + [[ -f bin/hush-arrakis-chain ]] && cp bin/hush-arrakis-chain "$out/" + [[ -f bin/hushd ]] && cp bin/hushd "$out/" + [[ -f bin/dragonxd ]] && cp bin/dragonxd "$out/" + [[ -f bin/asmap.dat ]] && cp bin/asmap.dat "$out/" + cp -r bin/res "$out/" 2>/dev/null || true + + # ── AppImage ───────────────────────────────────────────────────────────── + info "Creating AppImage ..." + local APPDIR="$bd/AppDir" + rm -rf "$APPDIR" + mkdir -p "$APPDIR/usr/bin" "$APPDIR/usr/lib" \ + "$APPDIR/usr/share/applications" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps" \ + "$APPDIR/usr/share/ObsidianDragon/res" + + cp bin/ObsidianDragon "$APPDIR/usr/bin/" + cp -r bin/res/* "$APPDIR/usr/share/ObsidianDragon/res/" 2>/dev/null || true + + # Daemon inside AppImage + [[ -f bin/hush-arrakis-chain ]] && cp bin/hush-arrakis-chain "$APPDIR/usr/bin/" + [[ -f bin/hushd ]] && cp bin/hushd "$APPDIR/usr/bin/" + [[ -f bin/dragonxd ]] && cp bin/dragonxd "$APPDIR/usr/bin/" + [[ -f bin/asmap.dat ]] && cp bin/asmap.dat "$APPDIR/usr/share/ObsidianDragon/" + + # Desktop entry + cat > "$APPDIR/usr/share/applications/ObsidianDragon.desktop" <<'DESK' +[Desktop Entry] +Type=Application +Name=DragonX Wallet +Comment=DragonX Cryptocurrency Wallet +Exec=ObsidianDragon +Icon=ObsidianDragon +Categories=Finance;Network; +Terminal=false +StartupNotify=true +DESK + cp "$APPDIR/usr/share/applications/ObsidianDragon.desktop" "$APPDIR/" + + # Icon + if [[ -f "$SCRIPT_DIR/res/icons/dragonx-256.png" ]]; then + cp "$SCRIPT_DIR/res/icons/dragonx-256.png" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" + else + cat > "$APPDIR/ObsidianDragon.svg" <<'SVG' + + + + + DX + +SVG + if command -v rsvg-convert &>/dev/null; then + rsvg-convert -w 256 -h 256 "$APPDIR/ObsidianDragon.svg" > \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" + fi + fi + cp "$APPDIR/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" "$APPDIR/" 2>/dev/null || \ + cp "$APPDIR/ObsidianDragon.svg" "$APPDIR/ObsidianDragon.png" 2>/dev/null || true + + # AppRun + cat > "$APPDIR/AppRun" <<'APPRUN' +#!/bin/bash +SELF=$(readlink -f "$0") +HERE=${SELF%/*} +export DRAGONX_RES_PATH="${HERE}/usr/share/ObsidianDragon/res" +export LD_LIBRARY_PATH="${HERE}/usr/lib:${LD_LIBRARY_PATH}" +cd "${HERE}/usr/share/ObsidianDragon" +exec "${HERE}/usr/bin/ObsidianDragon" "$@" +APPRUN + chmod +x "$APPDIR/AppRun" + + # Bundle SDL3 + for lib in libSDL3.so; do + local lp + lp=$(ldconfig -p 2>/dev/null | grep "$lib" | head -1 | awk '{print $NF}') + [[ -n "$lp" && -f "$lp" ]] && cp "$lp" "$APPDIR/usr/lib/" 2>/dev/null || true + done + [[ -f "$bd/_deps/sdl3-build/libSDL3.so" ]] && cp "$bd/_deps/sdl3-build/libSDL3.so"* "$APPDIR/usr/lib/" 2>/dev/null || true + + # appimagetool + local APPIMAGETOOL="" + if command -v appimagetool &>/dev/null; then + APPIMAGETOOL="appimagetool" + elif [[ -f "$bd/appimagetool-x86_64.AppImage" ]]; then + APPIMAGETOOL="$bd/appimagetool-x86_64.AppImage" + else + info "Downloading appimagetool ..." + wget -q -O "$bd/appimagetool-x86_64.AppImage" \ + "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage" + chmod +x "$bd/appimagetool-x86_64.AppImage" + APPIMAGETOOL="$bd/appimagetool-x86_64.AppImage" + fi + + local ARCH + ARCH=$(uname -m) + local IMG_NAME="DragonX_Wallet-${VERSION}-${ARCH}.AppImage" + cd "$bd" + ARCH="$ARCH" "$APPIMAGETOOL" "$APPDIR" "$IMG_NAME" 2>/dev/null && { + cp "$IMG_NAME" "$out/" + info "AppImage: $out/$IMG_NAME ($(du -h "$IMG_NAME" | cut -f1))" + } || warn "AppImage creation failed (appimagetool issue) — raw binary still in release/linux/" + + # Clean up: keep only AppImage + raw binary in release/linux/ + if ls "$out"/*.AppImage 1>/dev/null 2>&1; then + # AppImage succeeded — remove everything except AppImage and the binary + find "$out" -maxdepth 1 -type f ! -name '*.AppImage' ! -name 'ObsidianDragon' -delete + rm -rf "$out/res" 2>/dev/null + fi + + info "Linux release artifacts: $out/" + ls -lh "$out/" +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# RELEASE: WINDOWS — mingw-w64 cross-compile + INCBIN embedding +# ═══════════════════════════════════════════════════════════════════════════════ +build_release_win() { + header "Release: Windows x86_64 (cross-compile)" + local bd="$SCRIPT_DIR/build/windows" + local out="$SCRIPT_DIR/release/windows" + + if $CLEAN; then + info "Cleaning $bd ..."; rm -rf "$bd" + fi + mkdir -p "$bd" && cd "$bd" + + # ── Find MinGW ─────────────────────────────────────────────────────────── + local MINGW_GCC="" MINGW_GXX="" + if command -v x86_64-w64-mingw32-gcc-posix &>/dev/null; then + MINGW_GCC="x86_64-w64-mingw32-gcc-posix" + MINGW_GXX="x86_64-w64-mingw32-g++-posix" + info "Using POSIX thread model" + elif command -v x86_64-w64-mingw32-gcc &>/dev/null; then + MINGW_GCC="x86_64-w64-mingw32-gcc" + MINGW_GXX="x86_64-w64-mingw32-g++" + if x86_64-w64-mingw32-gcc -v 2>&1 | grep -q "posix"; then + info "Using POSIX thread model" + else + warn "Using win32 thread model — may have threading issues" + warn "Switch: sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix" + fi + else + err "mingw-w64 not found! Install: sudo apt install mingw-w64" + exit 1 + fi + + # ── Toolchain file ─────────────────────────────────────────────────────── + cat > "$bd/mingw-toolchain.cmake" < "$GEN/embedded_data.h" < +#include +#include "incbin.h" + +INCBIN(sapling_spend_params, "$RES/sapling-spend.params"); +INCBIN(sapling_output_params, "$RES/sapling-output.params"); +HDR + + if [[ -n "$ASMAP_DAT" ]]; then + cp -f "$ASMAP_DAT" "$RES/asmap.dat" + echo "INCBIN(asmap_dat, \"$RES/asmap.dat\");" >> "$GEN/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_asmap_dat_data = nullptr; }' >> "$GEN/embedded_data.h" + echo 'static const unsigned int g_asmap_dat_size = 0;' >> "$GEN/embedded_data.h" + fi + + # ── Daemon binaries ────────────────────────────────────────────── + local DD="$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + if [[ -d "$DD" && -f "$DD/hushd.exe" ]]; then + info "Embedding daemon binaries ..." + echo -e "\n#define HAS_EMBEDDED_DAEMON 1\n" >> "$GEN/embedded_data.h" + for f in hushd.exe hush-cli.exe hush-tx.exe dragonxd.bat dragonx-cli.bat; do + local sym=$(echo "$f" | sed 's/[^a-zA-Z0-9]/_/g') + if [[ -f "$DD/$f" ]]; then + cp -f "$DD/$f" "$RES/$f" + info " Staged $f ($(du -h "$DD/$f" | cut -f1))" + echo "INCBIN(${sym}, \"$RES/$f\");" >> "$GEN/embedded_data.h" + else + echo "extern \"C\" { static const uint8_t* g_${sym}_data = nullptr; }" >> "$GEN/embedded_data.h" + echo "static const unsigned int g_${sym}_size = 0;" >> "$GEN/embedded_data.h" + fi + done + else + warn "prebuilt-binaries/dragonxd-win/ not found — wallet-only build" + fi + + # ── xmrig binary (from prebuilt-binaries/xmrig-hac/) ──────────────── + local XMRIG_DIR="$SCRIPT_DIR/prebuilt-binaries/xmrig-hac" + if [[ -f "$XMRIG_DIR/xmrig.exe" ]]; then + cp -f "$XMRIG_DIR/xmrig.exe" "$RES/xmrig.exe" + info " Staged xmrig.exe ($(du -h "$XMRIG_DIR/xmrig.exe" | cut -f1))" + echo -e "\n#define HAS_EMBEDDED_XMRIG 1" >> "$GEN/embedded_data.h" + echo "INCBIN(xmrig_exe, \"$RES/xmrig.exe\");" >> "$GEN/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_xmrig_exe_data = nullptr; }' >> "$GEN/embedded_data.h" + echo 'static const unsigned int g_xmrig_exe_size = 0;' >> "$GEN/embedded_data.h" + fi + + # ── Theme images ───────────────────────────────────────────────── + echo -e "\n// ---- Embedded theme images ----" >> "$GEN/embedded_data.h" + local IMAGE_TABLE="" IMAGE_COUNT=0 + for dir in "$SCRIPT_DIR/res/img/backgrounds/texture" "$SCRIPT_DIR/res/img/backgrounds/gradient" "$SCRIPT_DIR/res/img/logos"; do + [[ -d "$dir" ]] || continue + for img in "$dir"/*.png; do + [[ -f "$img" ]] || continue + local bn=$(basename "$img") + local sym=$(echo "$bn" | sed 's/[^a-zA-Z0-9]/_/g') + cp -f "$img" "$RES/$bn" + echo "INCBIN(img_${sym}, \"$RES/$bn\");" >> "$GEN/embedded_data.h" + IMAGE_TABLE+=" { g_img_${sym}_data, g_img_${sym}_size, \"${bn}\" },\n" + IMAGE_COUNT=$((IMAGE_COUNT + 1)) + done + done + echo "" >> "$GEN/embedded_data.h" + echo "#define HAS_EMBEDDED_IMAGES 1" >> "$GEN/embedded_data.h" + echo "#define EMBEDDED_IMAGE_COUNT $IMAGE_COUNT" >> "$GEN/embedded_data.h" + echo "#define HAS_EMBEDDED_GRADIENT 1" >> "$GEN/embedded_data.h" + echo "#define HAS_EMBEDDED_LOGO 1" >> "$GEN/embedded_data.h" + # Backward compat aliases + echo "static const uint8_t* g_dark_gradient_png_data = g_img_dark_gradient_png_data;" >> "$GEN/embedded_data.h" + echo "static const unsigned int g_dark_gradient_png_size = g_img_dark_gradient_png_size;" >> "$GEN/embedded_data.h" + echo "static const uint8_t* g_logo_ObsidianDragon_dark_png_data = g_img_logo_ObsidianDragon_dark_png_data;" >> "$GEN/embedded_data.h" + echo "static const unsigned int g_logo_ObsidianDragon_dark_png_size = g_img_logo_ObsidianDragon_dark_png_size;" >> "$GEN/embedded_data.h" + echo "" >> "$GEN/embedded_data.h" + echo "struct EmbeddedImageEntry { const uint8_t* data; unsigned int size; const char* filename; };" >> "$GEN/embedded_data.h" + echo "static const EmbeddedImageEntry s_embedded_images[] = {" >> "$GEN/embedded_data.h" + echo -e "$IMAGE_TABLE" >> "$GEN/embedded_data.h" + echo " { nullptr, 0, nullptr }" >> "$GEN/embedded_data.h" + echo "};" >> "$GEN/embedded_data.h" + + # ── Overlay themes ─────────────────────────────────────────────── + echo -e "\n// ---- Bundled overlay themes ----" >> "$GEN/embedded_data.h" + local THEME_TABLE="" THEME_COUNT=0 + for tf in "$SCRIPT_DIR/res/themes"/*.toml; do + local tbn=$(basename "$tf") + [[ "$tbn" == "ui.toml" ]] && continue + local tsym=$(echo "$tbn" | sed 's/[^a-zA-Z0-9]/_/g') + cp -f "$tf" "$RES/$tbn" + echo "INCBIN(theme_${tsym}, \"$RES/$tbn\");" >> "$GEN/embedded_data.h" + THEME_TABLE+=" { g_theme_${tsym}_data, g_theme_${tsym}_size, \"${tbn}\" },\n" + THEME_COUNT=$((THEME_COUNT + 1)) + done + echo "" >> "$GEN/embedded_data.h" + echo "#define EMBEDDED_THEME_COUNT $THEME_COUNT" >> "$GEN/embedded_data.h" + echo "struct EmbeddedThemeEntry { const uint8_t* data; unsigned int size; const char* filename; };" >> "$GEN/embedded_data.h" + echo "static const EmbeddedThemeEntry s_embedded_themes[] = {" >> "$GEN/embedded_data.h" + echo -e "$THEME_TABLE" >> "$GEN/embedded_data.h" + echo " { nullptr, 0, nullptr }" >> "$GEN/embedded_data.h" + echo "};" >> "$GEN/embedded_data.h" + + info "Embedded resources header generated" + else + warn "Building WITHOUT embedded resources (Sapling params not found)" + fi + + # ── Fetch libsodium for Windows if needed ────────────────────────────── + if [[ ! -f "$SCRIPT_DIR/libs/libsodium-win/lib/libsodium.a" ]]; then + info "Fetching libsodium for Windows ..." + "$SCRIPT_DIR/scripts/fetch-libsodium.sh" --win + fi + + # ── CMake + build ──────────────────────────────────────────────────────── + info "Configuring (cross-compile) ..." + cmake "$SCRIPT_DIR" \ + -DCMAKE_TOOLCHAIN_FILE="$bd/mingw-toolchain.cmake" \ + -DCMAKE_BUILD_TYPE=Release \ + -DDRAGONX_USE_SYSTEM_SDL3=OFF + + info "Building with $JOBS jobs ..." + cmake --build . -j "$JOBS" + + [[ -f "bin/ObsidianDragon.exe" ]] || { err "Windows build failed"; exit 1; } + info "Binary: $(du -h bin/ObsidianDragon.exe | cut -f1)" + + # ── Package: release/windows/ ──────────────────────────────────────────── + rm -rf "$out" + mkdir -p "$out" + + local DIST="DragonX-Wallet-Windows-x64" + local dist_dir="$out/$DIST" + mkdir -p "$dist_dir" + cp bin/ObsidianDragon.exe "$dist_dir/" + + local DD="$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + for f in dragonxd.bat dragonx-cli.bat hushd.exe hush-cli.exe hush-tx.exe; do + [[ -f "$DD/$f" ]] && cp "$DD/$f" "$dist_dir/" + done + + cat > "$dist_dir/README.txt" <<'README' +DragonX Wallet - Windows Edition +================================ + +SINGLE-FILE DISTRIBUTION +======================== +This wallet is a true single-file executable with all resources embedded. +Just run ObsidianDragon.exe — no additional files needed! + +On first run, the wallet will automatically extract: +- Sapling parameters to %APPDATA%\ZcashParams\ +- asmap.dat to %APPDATA%\Hush\DRAGONX\ + +For support: https://git.hush.is/hush/ObsidianDragon +README + + # Copy single-file exe to release dir + cp bin/ObsidianDragon.exe "$out/" + + if command -v zip &>/dev/null; then + (cd "$out" && zip -r "$DIST.zip" "$DIST") + info "Zip: $out/$DIST.zip ($(du -h "$out/$DIST.zip" | cut -f1))" + # Clean up: keep .zip + single-file exe, remove loose directory + rm -rf "$dist_dir" + fi + + info "Windows release artifacts: $out/" + ls -lh "$out/" +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# RELEASE: macOS — .app bundle + DMG +# +# Cross-compile from Linux: +# 1. Install osxcross: https://github.com/tpoechtrager/osxcross +# export OSXCROSS="$HOME/osxcross" (or wherever you installed it) +# 2. For DMG: sudo apt install genisoimage +# 3. For .icns icons: sudo apt install icnsutils +# 4. Place macOS daemon binaries in prebuilt-binaries/dragonxd-mac/ (optional) +# +# Native on macOS: +# Works out of the box. brew install create-dmg for prettier DMGs. +# ═══════════════════════════════════════════════════════════════════════════════ +build_release_mac() { + local IS_CROSS=false + local MAC_ARCH="x86_64" + + # Detect cross-compilation from Linux + if [[ "$(uname -s)" == "Linux" ]]; then + IS_CROSS=true + info "Cross-compiling for macOS from Linux" + + # Find osxcross + if [[ -z "${OSXCROSS:-}" ]]; then + # Try common locations + for try_path in "$SCRIPT_DIR/external/osxcross" "$HOME/osxcross" "/opt/osxcross" "/usr/local/osxcross"; do + if [[ -d "$try_path/target" ]]; then + OSXCROSS="$try_path" + break + fi + done + fi + + if [[ -z "${OSXCROSS:-}" || ! -d "${OSXCROSS}/target" ]]; then + err "osxcross not found! Set OSXCROSS=/path/to/osxcross or install it:" + echo "" + echo " git clone https://github.com/tpoechtrager/osxcross" + echo " cd osxcross" + echo " # Place MacOSX SDK (e.g. MacOSX13.0.sdk.tar.xz) in tarballs/" + echo " UNATTENDED=1 ./build.sh" + echo " export OSXCROSS=\$PWD" + echo "" + exit 1 + fi + info "Using osxcross at: $OSXCROSS" + export PATH="$OSXCROSS/target/bin:$PATH" + + # Find the right compiler triple + local OSXCROSS_CC="" OSXCROSS_CXX="" OSXCROSS_TRIPLE="" + + # Look for full-triple compilers first (e.g. x86_64-apple-darwin22.4-clang++) + local found_triple + found_triple=$(ls "$OSXCROSS/target/bin/"x86_64-apple-darwin*-clang++ 2>/dev/null | head -1) + if [[ -n "$found_triple" ]]; then + OSXCROSS_TRIPLE=$(basename "$found_triple" | sed 's/-clang++$//') + OSXCROSS_CC="$OSXCROSS/target/bin/${OSXCROSS_TRIPLE}-clang" + OSXCROSS_CXX="$OSXCROSS/target/bin/${OSXCROSS_TRIPLE}-clang++" + MAC_ARCH="x86_64" + fi + # Prefer arm64 if available (Apple Silicon) + found_triple=$(ls "$OSXCROSS/target/bin/"aarch64-apple-darwin*-clang++ 2>/dev/null | head -1) + if [[ -n "$found_triple" ]]; then + OSXCROSS_TRIPLE=$(basename "$found_triple" | sed 's/-clang++$//') + OSXCROSS_CC="$OSXCROSS/target/bin/${OSXCROSS_TRIPLE}-clang" + OSXCROSS_CXX="$OSXCROSS/target/bin/${OSXCROSS_TRIPLE}-clang++" + MAC_ARCH="arm64" + fi + # Also try o64/oa64 wrapper — but resolve the underlying triple + if [[ -z "$OSXCROSS_CXX" ]]; then + if command -v o64-clang++ &>/dev/null; then + # Resolve the x86_64 triple from binutils + OSXCROSS_TRIPLE=$(ls "$OSXCROSS/target/bin/"x86_64-apple-darwin*-ar 2>/dev/null | head -1 | xargs basename | sed 's/-ar$//') + OSXCROSS_CC="o64-clang" + OSXCROSS_CXX="o64-clang++" + MAC_ARCH="x86_64" + elif command -v oa64-clang++ &>/dev/null; then + OSXCROSS_TRIPLE=$(ls "$OSXCROSS/target/bin/"aarch64-apple-darwin*-ar 2>/dev/null | head -1 | xargs basename | sed 's/-ar$//') + OSXCROSS_CC="oa64-clang" + OSXCROSS_CXX="oa64-clang++" + MAC_ARCH="arm64" + fi + fi + + if [[ -z "$OSXCROSS_CXX" ]]; then + err "Could not find osxcross compilers in PATH" + echo " Ensure \$OSXCROSS/target/bin contains *-apple-darwin*-clang++" + exit 1 + fi + info "macOS cross-compiler: $OSXCROSS_CXX (arch: $MAC_ARCH)" + else + MAC_ARCH=$(uname -m) + fi + + header "Release: macOS ($MAC_ARCH$(${IS_CROSS} && echo ' — cross-compile'))" + local bd="$SCRIPT_DIR/build/mac" + local out="$SCRIPT_DIR/release/mac" + + if $CLEAN; then + info "Cleaning $bd ..."; rm -rf "$bd" + fi + mkdir -p "$bd" && cd "$bd" + + # ── Compile ────────────────────────────────────────────────────────────── + if $IS_CROSS; then + # OSXCROSS_TRIPLE already resolved during compiler detection above + local OSXCROSS_SDK_PATH + OSXCROSS_SDK_PATH=$(ls -d "$OSXCROSS"/target/SDK/MacOSX*.sdk 2>/dev/null | head -1) + + # Generate osxcross toolchain file + cat > "$bd/osxcross-toolchain.cmake" </dev/null || echo "") + if [[ -n "$CLANG_RESOURCE_DIR" && -f "$CLANG_RESOURCE_DIR/lib/darwin/libclang_rt.osx.a" ]]; then + COMPILER_RT="$CLANG_RESOURCE_DIR/lib/darwin/libclang_rt.osx.a" + elif [[ -f "$OSXCROSS/build/compiler-rt/compiler-rt/build/lib/darwin/libclang_rt.osx.a" ]]; then + COMPILER_RT="$OSXCROSS/build/compiler-rt/compiler-rt/build/lib/darwin/libclang_rt.osx.a" + fi + + # Fetch libsodium for macOS if needed + if [[ ! -f "$SCRIPT_DIR/libs/libsodium-mac/lib/libsodium.a" ]]; then + info "Fetching libsodium for macOS ..." + "$SCRIPT_DIR/scripts/fetch-libsodium.sh" --mac + fi + + info "Configuring (cross-compile via osxcross) ..." + cmake "$SCRIPT_DIR" \ + -DCMAKE_TOOLCHAIN_FILE="$bd/osxcross-toolchain.cmake" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DDRAGONX_USE_SYSTEM_SDL3=OFF \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \ + ${COMPILER_RT:+-DOSXCROSS_COMPILER_RT="$COMPILER_RT"} + else + info "Configuring (native) ..." + cmake "$SCRIPT_DIR" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DDRAGONX_USE_SYSTEM_SDL3=OFF \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 + fi + + info "Building with $JOBS jobs ..." + cmake --build . -j "$JOBS" + + [[ -f "bin/ObsidianDragon" ]] || { err "macOS build failed"; exit 1; } + + # Strip — use osxcross strip for cross-builds + if $IS_CROSS; then + local STRIP_CMD="${OSXCROSS}/target/bin/${OSXCROSS_TRIPLE}-strip" + if [[ -x "$STRIP_CMD" ]]; then + info "Stripping (osxcross) ..." + "$STRIP_CMD" bin/ObsidianDragon + else + warn "osxcross strip not found at $STRIP_CMD — skipping" + fi + else + info "Stripping ..." + strip bin/ObsidianDragon + fi + info "Binary: $(du -h bin/ObsidianDragon | cut -f1)" + + # ── Create .app bundle ─────────────────────────────────────────────────── + rm -rf "$out" + mkdir -p "$out" + + local APP="$out/ObsidianDragon.app" + local CONTENTS="$APP/Contents" + local MACOS="$CONTENTS/MacOS" + local RESOURCES="$CONTENTS/Resources" + local FRAMEWORKS="$CONTENTS/Frameworks" + + mkdir -p "$MACOS" "$RESOURCES/res" "$FRAMEWORKS" + + # Main binary + cp bin/ObsidianDragon "$MACOS/" + chmod +x "$MACOS/ObsidianDragon" + + # Resources + cp -r bin/res/* "$RESOURCES/res/" 2>/dev/null || true + + # Daemon binaries (macOS native, from dragonxd-mac/) + local daemon_dir="$SCRIPT_DIR/prebuilt-binaries/dragonxd-mac" + if [[ -d "$daemon_dir" ]]; then + for f in hush-arrakis-chain hushd hush-cli hush-tx dragonxd; do + [[ -f "$daemon_dir/$f" ]] && { cp "$daemon_dir/$f" "$MACOS/"; chmod +x "$MACOS/$f"; info " Bundled $f"; } + done + elif ! $IS_CROSS; then + # Native macOS: try standard paths + local launcher_paths=( + "$SCRIPT_DIR/../hush-arrakis-chain" + "$HOME/hush3/src/hush-arrakis-chain" + ) + for p in "${launcher_paths[@]}"; do + [[ -f "$p" ]] && { cp "$p" "$MACOS/hush-arrakis-chain"; chmod +x "$MACOS/hush-arrakis-chain"; info " Bundled hush-arrakis-chain"; break; } + done + local hushd_paths=( + "$SCRIPT_DIR/../hushd" + "$HOME/hush3/src/hushd" + ) + for p in "${hushd_paths[@]}"; do + [[ -f "$p" ]] && { cp "$p" "$MACOS/hushd"; chmod +x "$MACOS/hushd"; info " Bundled hushd"; break; } + done + else + warn "prebuilt-binaries/dragonxd-mac/ not found — place macOS daemon binaries there for bundling" + fi + + # asmap.dat + find_asmap 2>/dev/null && cp "$ASMAP_DAT" "$RESOURCES/asmap.dat" && info " Bundled asmap.dat" + + # Bundle SDL3 dylib + local sdl_dylib="" + for candidate in \ + "$bd/_deps/sdl3-build/libSDL3.dylib" \ + "$bd/_deps/sdl3-build/libSDL3.0.dylib" \ + "/usr/local/lib/libSDL3.dylib" \ + "/opt/homebrew/lib/libSDL3.dylib"; do + if [[ -f "$candidate" ]]; then + sdl_dylib="$candidate" + break + fi + done + if [[ -n "$sdl_dylib" ]]; then + cp "$sdl_dylib" "$FRAMEWORKS/" + local sdl_name=$(basename "$sdl_dylib") + # Fix the rpath so the binary finds SDL3 in Frameworks/ + if $IS_CROSS; then + local INSTALL_NAME_TOOL="${OSXCROSS}/target/bin/${OSXCROSS_TRIPLE}-install_name_tool" + [[ -x "$INSTALL_NAME_TOOL" ]] && "$INSTALL_NAME_TOOL" -change "@rpath/$sdl_name" "@executable_path/../Frameworks/$sdl_name" "$MACOS/ObsidianDragon" 2>/dev/null || true + else + install_name_tool -change "@rpath/$sdl_name" "@executable_path/../Frameworks/$sdl_name" "$MACOS/ObsidianDragon" 2>/dev/null || true + fi + info " Bundled $sdl_name" + fi + + # Launcher script (ensures working dir + dylib path) + mv "$MACOS/ObsidianDragon" "$MACOS/ObsidianDragon.bin" + cat > "$MACOS/ObsidianDragon" <<'LAUNCH' +#!/bin/bash +DIR="$(cd "$(dirname "$0")" && pwd)" +export DYLD_LIBRARY_PATH="$DIR/../Frameworks:$DYLD_LIBRARY_PATH" +export DRAGONX_RES_PATH="$DIR/../Resources/res" +cd "$DIR/../Resources" +exec "$DIR/ObsidianDragon.bin" "$@" +LAUNCH + chmod +x "$MACOS/ObsidianDragon" + + # Info.plist + cat > "$CONTENTS/Info.plist" < + + + + CFBundleName + DragonX Wallet + CFBundleDisplayName + DragonX Wallet + CFBundleIdentifier + is.hush.dragonx + CFBundleVersion + ${VERSION} + CFBundleShortVersionString + ${VERSION} + CFBundleExecutable + ObsidianDragon + CFBundleIconFile + ObsidianDragon + CFBundlePackageType + APPL + CFBundleSignature + DRGX + LSMinimumSystemVersion + 11.0 + NSHighResolutionCapable + + NSSupportsAutomaticGraphicsSwitching + + LSApplicationCategoryType + public.app-category.finance + + +PLIST + + # ── Icon (.icns) ───────────────────────────────────────────────────────── + if [[ -f "$SCRIPT_DIR/res/img/ObsidianDragon.icns" ]]; then + cp "$SCRIPT_DIR/res/img/ObsidianDragon.icns" "$RESOURCES/ObsidianDragon.icns" + elif [[ -f "$SCRIPT_DIR/res/icons/dragonx-256.png" ]]; then + if command -v iconutil &>/dev/null && command -v sips &>/dev/null; then + # Native macOS: sips + iconutil + local iconset="$bd/ObsidianDragon.iconset" + mkdir -p "$iconset" + local src="$SCRIPT_DIR/res/icons/dragonx-256.png" + for sz in 16 32 64 128 256; do + sips -z $sz $sz "$src" --out "$iconset/icon_${sz}x${sz}.png" &>/dev/null || true + done + for sz in 16 32 128; do + local r=$((sz * 2)) + sips -z $r $r "$src" --out "$iconset/icon_${sz}x${sz}@2x.png" &>/dev/null || true + done + iconutil -c icns "$iconset" -o "$RESOURCES/ObsidianDragon.icns" 2>/dev/null || true + rm -rf "$iconset" + elif command -v png2icns &>/dev/null; then + # Linux: png2icns from icnsutils (sudo apt install icnsutils) + info "Creating .icns with png2icns ..." + local src="$SCRIPT_DIR/res/icons/dragonx-256.png" + # png2icns needs specific sizes; resize with ImageMagick if available + if command -v convert &>/dev/null; then + local icondir="$bd/icon-sizes" + mkdir -p "$icondir" + for sz in 16 32 48 128 256; do + convert "$src" -resize ${sz}x${sz} "$icondir/icon_${sz}.png" 2>/dev/null || true + done + png2icns "$RESOURCES/ObsidianDragon.icns" "$icondir"/icon_*.png 2>/dev/null || true + rm -rf "$icondir" + else + # Just use the 256px as-is + png2icns "$RESOURCES/ObsidianDragon.icns" "$src" 2>/dev/null || true + fi + else + warn "No .icns tool found (install: sudo apt install icnsutils)" + fi + fi + + info ".app bundle created: $APP" + + # ── Create DMG ─────────────────────────────────────────────────────────── + local DMG_NAME="DragonX_Wallet-${VERSION}-macOS-${MAC_ARCH}.dmg" + + if command -v create-dmg &>/dev/null; then + # create-dmg (works on macOS; also available on Linux via npm) + info "Creating DMG with create-dmg ..." + create-dmg \ + --volname "DragonX Wallet" \ + --volicon "$RESOURCES/ObsidianDragon.icns" \ + --window-pos 200 120 \ + --window-size 600 400 \ + --icon-size 100 \ + --icon "ObsidianDragon.app" 150 190 \ + --app-drop-link 450 190 \ + --no-internet-enable \ + "$out/$DMG_NAME" \ + "$APP" 2>/dev/null && { + info "DMG: $out/$DMG_NAME ($(du -h "$out/$DMG_NAME" | cut -f1))" + } || warn "create-dmg failed — .app bundle still available" + elif command -v hdiutil &>/dev/null; then + # Native macOS + info "Creating DMG with hdiutil ..." + local staging="$bd/dmg-staging" + rm -rf "$staging" + mkdir -p "$staging" + cp -a "$APP" "$staging/" + ln -s /Applications "$staging/Applications" + hdiutil create -volname "DragonX Wallet" \ + -srcfolder "$staging" \ + -ov -format UDZO \ + "$out/$DMG_NAME" 2>/dev/null && { + info "DMG: $out/$DMG_NAME ($(du -h "$out/$DMG_NAME" | cut -f1))" + } || warn "hdiutil failed — .app bundle still available" + rm -rf "$staging" + elif command -v genisoimage &>/dev/null; then + # Linux fallback: genisoimage produces a hybrid ISO/DMG that macOS can open + info "Creating DMG with genisoimage (Linux) ..." + local staging="$bd/dmg-staging" + rm -rf "$staging" + mkdir -p "$staging" + cp -a "$APP" "$staging/" + # Can't create a real symlink to /Applications in an ISO, but the .app + # is the important part — users drag it to Applications manually. + genisoimage -V "DragonX Wallet" \ + -D -R -apple -no-pad \ + -o "$out/$DMG_NAME" \ + "$staging" 2>/dev/null && { + info "DMG: $out/$DMG_NAME ($(du -h "$out/$DMG_NAME" | cut -f1))" + info " (ISO/HFS hybrid — mountable on macOS)" + } || warn "genisoimage failed — .app bundle still available" + rm -rf "$staging" + else + warn "No DMG tool found — .app bundle still available" + echo "" + echo " To create DMGs on Linux, install one of:" + echo " sudo apt install genisoimage # Basic DMG (recommended)" + echo " sudo apt install icnsutils # For .icns icon creation" + echo "" + fi + + info "macOS release artifacts: $out/" + ls -lhR "$out/" 2>/dev/null | head -30 +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# MAIN +# ═══════════════════════════════════════════════════════════════════════════════ +echo -e "${GREEN}DragonX Wallet v${VERSION} — Unified Build${NC}" +echo "─────────────────────────────────────────" + +$DO_DEV && build_dev +$DO_LINUX && build_release_linux +$DO_WIN && build_release_win +$DO_MAC && build_release_mac + +header "Done" +if $DO_LINUX || $DO_WIN || $DO_MAC; then + echo -e " Release artifacts in: ${GREEN}$SCRIPT_DIR/release/${NC}" + [[ -d "$SCRIPT_DIR/release/linux" ]] && echo -e " ${CYAN}linux/${NC} — AppImage + binary" + [[ -d "$SCRIPT_DIR/release/windows" ]] && echo -e " ${CYAN}windows/${NC} — .exe + .zip" + [[ -d "$SCRIPT_DIR/release/mac" ]] && echo -e " ${CYAN}mac/${NC} — .app + .dmg" +fi diff --git a/cmake/EmbedResources.cmake b/cmake/EmbedResources.cmake new file mode 100644 index 0000000..b86fd5c --- /dev/null +++ b/cmake/EmbedResources.cmake @@ -0,0 +1,42 @@ +# CMake script to embed binary files as C arrays + +function(embed_resource RESOURCE_FILE OUTPUT_FILE VAR_NAME) + file(READ "${RESOURCE_FILE}" HEX_CONTENT HEX) + + # Convert hex to C array format + string(LENGTH "${HEX_CONTENT}" HEX_LENGTH) + math(EXPR BYTE_COUNT "${HEX_LENGTH} / 2") + + set(ARRAY_CONTENT "") + set(INDEX 0) + while(INDEX LESS HEX_LENGTH) + string(SUBSTRING "${HEX_CONTENT}" ${INDEX} 2 BYTE) + string(APPEND ARRAY_CONTENT "0x${BYTE},") + math(EXPR INDEX "${INDEX} + 2") + math(EXPR BYTE_NUM "${INDEX} / 2") + math(EXPR MOD "${BYTE_NUM} % 16") + if(MOD EQUAL 0) + string(APPEND ARRAY_CONTENT "\n ") + endif() + endwhile() + + # Generate header file + set(HEADER_CONTENT "// Auto-generated embedded resource - DO NOT EDIT +#pragma once +#include +#include + +namespace embedded { + +inline constexpr unsigned char ${VAR_NAME}_data[] = { + ${ARRAY_CONTENT} +}; + +inline constexpr size_t ${VAR_NAME}_size = ${BYTE_COUNT}; + +} // namespace embedded +") + + file(WRITE "${OUTPUT_FILE}" "${HEADER_CONTENT}") + message(STATUS "Embedded ${RESOURCE_FILE} -> ${OUTPUT_FILE} (${BYTE_COUNT} bytes)") +endfunction() diff --git a/docs/screenshots/1.webp b/docs/screenshots/1.webp new file mode 100644 index 0000000..c16c9be Binary files /dev/null and b/docs/screenshots/1.webp differ diff --git a/docs/screenshots/2.webp b/docs/screenshots/2.webp new file mode 100644 index 0000000..a087950 Binary files /dev/null and b/docs/screenshots/2.webp differ diff --git a/docs/screenshots/3.webp b/docs/screenshots/3.webp new file mode 100644 index 0000000..6924037 Binary files /dev/null and b/docs/screenshots/3.webp differ diff --git a/docs/screenshots/4.webp b/docs/screenshots/4.webp new file mode 100644 index 0000000..e3d8195 Binary files /dev/null and b/docs/screenshots/4.webp differ diff --git a/docs/screenshots/5.webp b/docs/screenshots/5.webp new file mode 100644 index 0000000..5575d15 Binary files /dev/null and b/docs/screenshots/5.webp differ diff --git a/docs/screenshots/6.webp b/docs/screenshots/6.webp new file mode 100644 index 0000000..22a12a6 Binary files /dev/null and b/docs/screenshots/6.webp differ diff --git a/docs/screenshots/7.webp b/docs/screenshots/7.webp new file mode 100644 index 0000000..f079557 Binary files /dev/null and b/docs/screenshots/7.webp differ diff --git a/docs/screenshots/8.webp b/docs/screenshots/8.webp new file mode 100644 index 0000000..af21d28 Binary files /dev/null and b/docs/screenshots/8.webp differ diff --git a/docs/screenshots/9.webp b/docs/screenshots/9.webp new file mode 100644 index 0000000..9e18c6c Binary files /dev/null and b/docs/screenshots/9.webp differ diff --git a/libs/glad/include/KHR/khrplatform.h b/libs/glad/include/KHR/khrplatform.h new file mode 100644 index 0000000..2e8c48b --- /dev/null +++ b/libs/glad/include/KHR/khrplatform.h @@ -0,0 +1,244 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75a5cc215f570d5d8e5d8b24db93 + * + * Adopters may modify this file to suit their platform., please + * send a copy of any modifications to the Khronos Registrar + * (Khronos Registrar ). + * + */ + +#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) +# define KHRONOS_STATIC 1 +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(KHRONOS_STATIC) + /* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +# define KHRONOS_APICALL +#elif defined(_WIN32) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 +/* + * To support platform where these types are not defined. + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/libs/glad/include/glad/gl.h b/libs/glad/include/glad/gl.h new file mode 100644 index 0000000..8ac39ca --- /dev/null +++ b/libs/glad/include/glad/gl.h @@ -0,0 +1,379 @@ +/** + * GLAD - OpenGL Loader Generator + * Generated for OpenGL 3.3 Core Profile + * + * This is a minimal GLAD loader for OpenGL 3.3 Core with the extensions + * needed for framebuffer operations in the DragonX acrylic effects system. + * + * Generated from glad.dav1d.de with settings: + * - Language: C/C++ + * - Specification: OpenGL + * - API: gl 3.3 + * - Profile: Core + * - Extensions: None (core only) + * - Options: Loader enabled + */ + +#ifndef GLAD_GL_H_ +#define GLAD_GL_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* Type definitions */ +typedef void (*GLADloadproc)(void); +typedef void (*GLADapiproc)(void); + +/* GLAD API */ +#define GLAD_VERSION_MAJOR(version) (version / 10000) +#define GLAD_VERSION_MINOR(version) (version % 10000) + +/* Function pointer loader type */ +typedef GLADapiproc (*GLADloadfunc)(const char *name); + +/* Initialize GLAD loader - returns version (major * 10000 + minor) or 0 on failure */ +int gladLoadGL(GLADloadfunc load); + +/* SDL3 specific loader helper */ +#ifdef SDL_VERSION_ATLEAST +#include +static inline GLADapiproc glad_sdl_get_proc(const char* name) { + return (GLADapiproc)SDL_GL_GetProcAddress(name); +} +#define gladLoadGL_SDL() gladLoadGL(glad_sdl_get_proc) +#endif + +/* Feature flags */ +extern int GLAD_GL_VERSION_1_0; +extern int GLAD_GL_VERSION_1_1; +extern int GLAD_GL_VERSION_1_2; +extern int GLAD_GL_VERSION_1_3; +extern int GLAD_GL_VERSION_1_4; +extern int GLAD_GL_VERSION_1_5; +extern int GLAD_GL_VERSION_2_0; +extern int GLAD_GL_VERSION_2_1; +extern int GLAD_GL_VERSION_3_0; +extern int GLAD_GL_VERSION_3_1; +extern int GLAD_GL_VERSION_3_2; +extern int GLAD_GL_VERSION_3_3; + +/* OpenGL type definitions */ +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef khronos_int8_t GLbyte; +typedef khronos_uint8_t GLubyte; +typedef khronos_int16_t GLshort; +typedef khronos_uint16_t GLushort; +typedef int GLint; +typedef unsigned int GLuint; +typedef khronos_int32_t GLclampx; +typedef int GLsizei; +typedef khronos_float_t GLfloat; +typedef khronos_float_t GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void *GLeglClientBufferEXT; +typedef void *GLeglImageOES; +typedef char GLchar; +typedef char GLcharARB; +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef khronos_uint16_t GLhalf; +typedef khronos_uint16_t GLhalfARB; +typedef khronos_int32_t GLfixed; +typedef khronos_intptr_t GLintptr; +typedef khronos_intptr_t GLintptrARB; +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_ssize_t GLsizeiptrARB; +typedef khronos_int64_t GLint64; +typedef khronos_int64_t GLint64EXT; +typedef khronos_uint64_t GLuint64; +typedef khronos_uint64_t GLuint64EXT; +typedef struct __GLsync *GLsync; + +/* OpenGL constants */ +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_NONE 0 +#define GL_ZERO 0 +#define GL_ONE 1 + +/* Depth buffer */ +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_DEPTH_TEST 0x0B71 + +/* Blending */ +#define GL_BLEND 0x0BE2 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 + +/* Texture */ +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_LINEAR 0x2601 +#define GL_NEAREST 0x2600 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_REPEAT 0x2901 +#define GL_RGBA 0x1908 +#define GL_RGBA8 0x8058 +#define GL_UNSIGNED_BYTE 0x1401 + +/* Framebuffer */ +#define GL_FRAMEBUFFER 0x8D40 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 + +/* Renderbuffer */ +#define GL_RENDERBUFFER 0x8D41 + +/* Shaders */ +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_FLOAT 0x1406 + +/* Draw */ +#define GL_TRIANGLES 0x0004 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_STATIC_DRAW 0x88E4 + +/* -------------------- Function declarations -------------------- */ + +/* Core 1.0 */ +typedef void (KHRONOS_APIENTRY *PFNGLCLEARPROC)(GLbitfield mask); +typedef void (KHRONOS_APIENTRY *PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (KHRONOS_APIENTRY *PFNGLENABLEPROC)(GLenum cap); +typedef void (KHRONOS_APIENTRY *PFNGLDISABLEPROC)(GLenum cap); +typedef void (KHRONOS_APIENTRY *PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (KHRONOS_APIENTRY *PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (KHRONOS_APIENTRY *PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +typedef void (KHRONOS_APIENTRY *PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); +typedef void (KHRONOS_APIENTRY *PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); +typedef void (KHRONOS_APIENTRY *PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); +typedef void (KHRONOS_APIENTRY *PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); +typedef const GLubyte *(KHRONOS_APIENTRY *PFNGLGETSTRINGPROC)(GLenum name); +typedef void (KHRONOS_APIENTRY *PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); + +/* Core 1.3 */ +typedef void (KHRONOS_APIENTRY *PFNGLACTIVETEXTUREPROC)(GLenum texture); + +/* Core 1.5 */ +typedef void (KHRONOS_APIENTRY *PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); +typedef void (KHRONOS_APIENTRY *PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); +typedef void (KHRONOS_APIENTRY *PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); +typedef void (KHRONOS_APIENTRY *PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); + +/* Core 2.0 */ +typedef GLuint (KHRONOS_APIENTRY *PFNGLCREATESHADERPROC)(GLenum type); +typedef void (KHRONOS_APIENTRY *PFNGLDELETESHADERPROC)(GLuint shader); +typedef void (KHRONOS_APIENTRY *PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (KHRONOS_APIENTRY *PFNGLCOMPILESHADERPROC)(GLuint shader); +typedef void (KHRONOS_APIENTRY *PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); +typedef void (KHRONOS_APIENTRY *PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef GLuint (KHRONOS_APIENTRY *PFNGLCREATEPROGRAMPROC)(void); +typedef void (KHRONOS_APIENTRY *PFNGLDELETEPROGRAMPROC)(GLuint program); +typedef void (KHRONOS_APIENTRY *PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +typedef void (KHRONOS_APIENTRY *PFNGLLINKPROGRAMPROC)(GLuint program); +typedef void (KHRONOS_APIENTRY *PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); +typedef void (KHRONOS_APIENTRY *PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (KHRONOS_APIENTRY *PFNGLUSEPROGRAMPROC)(GLuint program); +typedef GLint (KHRONOS_APIENTRY *PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); +typedef void (KHRONOS_APIENTRY *PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +typedef void (KHRONOS_APIENTRY *PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +typedef void (KHRONOS_APIENTRY *PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); +typedef void (KHRONOS_APIENTRY *PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (KHRONOS_APIENTRY *PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (KHRONOS_APIENTRY *PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); +typedef void (KHRONOS_APIENTRY *PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); +typedef void (KHRONOS_APIENTRY *PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (KHRONOS_APIENTRY *PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef void (KHRONOS_APIENTRY *PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef void (KHRONOS_APIENTRY *PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); + +/* Core 3.0 - Framebuffer */ +typedef void (KHRONOS_APIENTRY *PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); +typedef void (KHRONOS_APIENTRY *PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); +typedef void (KHRONOS_APIENTRY *PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); +typedef void (KHRONOS_APIENTRY *PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef GLenum (KHRONOS_APIENTRY *PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); +typedef void (KHRONOS_APIENTRY *PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); +typedef void (KHRONOS_APIENTRY *PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); +typedef void (KHRONOS_APIENTRY *PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); +typedef void (KHRONOS_APIENTRY *PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (KHRONOS_APIENTRY *PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (KHRONOS_APIENTRY *PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); + +/* Core 3.0 - Mipmap */ +typedef void (KHRONOS_APIENTRY *PFNGLGENERATEMIPMAPPROC)(GLenum target); + +/* Core 3.0 - VAO */ +typedef void (KHRONOS_APIENTRY *PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); +typedef void (KHRONOS_APIENTRY *PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); +typedef void (KHRONOS_APIENTRY *PFNGLBINDVERTEXARRAYPROC)(GLuint array); + +/* -------------------- Function pointers -------------------- */ + +/* Core 1.0 */ +extern PFNGLCLEARPROC glad_glClear; +#define glClear glad_glClear +extern PFNGLCLEARCOLORPROC glad_glClearColor; +#define glClearColor glad_glClearColor +extern PFNGLENABLEPROC glad_glEnable; +#define glEnable glad_glEnable +extern PFNGLDISABLEPROC glad_glDisable; +#define glDisable glad_glDisable +extern PFNGLVIEWPORTPROC glad_glViewport; +#define glViewport glad_glViewport +extern PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +#define glTexImage2D glad_glTexImage2D +extern PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +#define glTexParameteri glad_glTexParameteri +extern PFNGLBINDTEXTUREPROC glad_glBindTexture; +#define glBindTexture glad_glBindTexture +extern PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +#define glDeleteTextures glad_glDeleteTextures +extern PFNGLGENTEXTURESPROC glad_glGenTextures; +#define glGenTextures glad_glGenTextures +extern PFNGLDRAWARRAYSPROC glad_glDrawArrays; +#define glDrawArrays glad_glDrawArrays +extern PFNGLGETSTRINGPROC glad_glGetString; +#define glGetString glad_glGetString +extern PFNGLGETINTEGERVPROC glad_glGetIntegerv; +#define glGetIntegerv glad_glGetIntegerv +extern PFNGLBLENDFUNCPROC glad_glBlendFunc; +#define glBlendFunc glad_glBlendFunc + +/* Core 1.3 */ +extern PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +#define glActiveTexture glad_glActiveTexture + +/* Core 1.5 */ +extern PFNGLGENBUFFERSPROC glad_glGenBuffers; +#define glGenBuffers glad_glGenBuffers +extern PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +#define glDeleteBuffers glad_glDeleteBuffers +extern PFNGLBINDBUFFERPROC glad_glBindBuffer; +#define glBindBuffer glad_glBindBuffer +extern PFNGLBUFFERDATAPROC glad_glBufferData; +#define glBufferData glad_glBufferData + +/* Core 2.0 */ +extern PFNGLCREATESHADERPROC glad_glCreateShader; +#define glCreateShader glad_glCreateShader +extern PFNGLDELETESHADERPROC glad_glDeleteShader; +#define glDeleteShader glad_glDeleteShader +extern PFNGLSHADERSOURCEPROC glad_glShaderSource; +#define glShaderSource glad_glShaderSource +extern PFNGLCOMPILESHADERPROC glad_glCompileShader; +#define glCompileShader glad_glCompileShader +extern PFNGLGETSHADERIVPROC glad_glGetShaderiv; +#define glGetShaderiv glad_glGetShaderiv +extern PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +#define glGetShaderInfoLog glad_glGetShaderInfoLog +extern PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +#define glCreateProgram glad_glCreateProgram +extern PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +#define glDeleteProgram glad_glDeleteProgram +extern PFNGLATTACHSHADERPROC glad_glAttachShader; +#define glAttachShader glad_glAttachShader +extern PFNGLLINKPROGRAMPROC glad_glLinkProgram; +#define glLinkProgram glad_glLinkProgram +extern PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +#define glGetProgramiv glad_glGetProgramiv +extern PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +#define glGetProgramInfoLog glad_glGetProgramInfoLog +extern PFNGLUSEPROGRAMPROC glad_glUseProgram; +#define glUseProgram glad_glUseProgram +extern PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +#define glGetUniformLocation glad_glGetUniformLocation +extern PFNGLUNIFORM1IPROC glad_glUniform1i; +#define glUniform1i glad_glUniform1i +extern PFNGLUNIFORM1FPROC glad_glUniform1f; +#define glUniform1f glad_glUniform1f +extern PFNGLUNIFORM2FPROC glad_glUniform2f; +#define glUniform2f glad_glUniform2f +extern PFNGLUNIFORM4FPROC glad_glUniform4f; +#define glUniform4f glad_glUniform4f +extern PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +#define glUniformMatrix4fv glad_glUniformMatrix4fv +extern PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +#define glBindAttribLocation glad_glBindAttribLocation +extern PFNGLDETACHSHADERPROC glad_glDetachShader; +#define glDetachShader glad_glDetachShader +extern PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +#define glVertexAttribPointer glad_glVertexAttribPointer +extern PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +#define glEnableVertexAttribArray glad_glEnableVertexAttribArray +extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +#define glDisableVertexAttribArray glad_glDisableVertexAttribArray + +/* Core 3.0 - Framebuffer */ +extern PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; +#define glGenFramebuffers glad_glGenFramebuffers +extern PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; +#define glDeleteFramebuffers glad_glDeleteFramebuffers +extern PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; +#define glBindFramebuffer glad_glBindFramebuffer +extern PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; +#define glFramebufferTexture2D glad_glFramebufferTexture2D +extern PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; +#define glCheckFramebufferStatus glad_glCheckFramebufferStatus +extern PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; +#define glGenRenderbuffers glad_glGenRenderbuffers +extern PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; +#define glDeleteRenderbuffers glad_glDeleteRenderbuffers +extern PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; +#define glBindRenderbuffer glad_glBindRenderbuffer +extern PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; +#define glRenderbufferStorage glad_glRenderbufferStorage +extern PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; +#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer +extern PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; +#define glBlitFramebuffer glad_glBlitFramebuffer + +/* Core 3.0 - Mipmap */ +extern PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; +#define glGenerateMipmap glad_glGenerateMipmap + +/* Core 3.0 - VAO */ +extern PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; +#define glGenVertexArrays glad_glGenVertexArrays +extern PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; +#define glDeleteVertexArrays glad_glDeleteVertexArrays +extern PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; +#define glBindVertexArray glad_glBindVertexArray + +#ifdef __cplusplus +} +#endif + +#endif /* GLAD_GL_H_ */ diff --git a/libs/glad/src/gl.c b/libs/glad/src/gl.c new file mode 100644 index 0000000..dbad03f --- /dev/null +++ b/libs/glad/src/gl.c @@ -0,0 +1,290 @@ +/** + * GLAD - OpenGL Loader Generator + * Generated for OpenGL 3.3 Core Profile + * + * This file implements the OpenGL function loader for the acrylic effects system. + * It loads function pointers at runtime, making the binary self-contained. + */ + +#include +#include + +/* Feature flags */ +int GLAD_GL_VERSION_1_0 = 0; +int GLAD_GL_VERSION_1_1 = 0; +int GLAD_GL_VERSION_1_2 = 0; +int GLAD_GL_VERSION_1_3 = 0; +int GLAD_GL_VERSION_1_4 = 0; +int GLAD_GL_VERSION_1_5 = 0; +int GLAD_GL_VERSION_2_0 = 0; +int GLAD_GL_VERSION_2_1 = 0; +int GLAD_GL_VERSION_3_0 = 0; +int GLAD_GL_VERSION_3_1 = 0; +int GLAD_GL_VERSION_3_2 = 0; +int GLAD_GL_VERSION_3_3 = 0; + +/* Function pointers - Core 1.0 */ +PFNGLCLEARPROC glad_glClear = NULL; +PFNGLCLEARCOLORPROC glad_glClearColor = NULL; +PFNGLENABLEPROC glad_glEnable = NULL; +PFNGLDISABLEPROC glad_glDisable = NULL; +PFNGLVIEWPORTPROC glad_glViewport = NULL; +PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; +PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; +PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; +PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; +PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; +PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; +PFNGLGETSTRINGPROC glad_glGetString = NULL; +PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; +PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; + +/* Function pointers - Core 1.3 */ +PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; + +/* Function pointers - Core 1.5 */ +PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; +PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; +PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; +PFNGLBUFFERDATAPROC glad_glBufferData = NULL; + +/* Function pointers - Core 2.0 */ +PFNGLCREATESHADERPROC glad_glCreateShader = NULL; +PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; +PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; +PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; +PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; +PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; +PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; +PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; +PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; +PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; +PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; +PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; +PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; +PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; +PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; +PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; +PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; +PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; +PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; +PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; +PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; + +/* Function pointers - Core 3.0 Framebuffer */ +PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; +PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; +PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; +PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; +PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; +PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; +PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; +PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; +PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; + +/* Function pointers - Core 3.0 Mipmap */ +PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; + +/* Function pointers - Core 3.0 VAO */ +PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; +PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; +PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; + +/* Parse GL version string to extract major.minor */ +static void glad_parse_version(const char* version, int* major, int* minor) { + const char* p = version; + + /* Skip "OpenGL ES " prefix if present */ + if (version[0] == 'O') { + while (*p && *p != ' ') p++; + if (*p == ' ') p++; + if (*p == 'E') { + while (*p && *p != ' ') p++; + if (*p == ' ') p++; + } + } + + *major = 0; + *minor = 0; + + /* Parse major version */ + while (*p >= '0' && *p <= '9') { + *major = *major * 10 + (*p - '0'); + p++; + } + + /* Skip dot */ + if (*p == '.') p++; + + /* Parse minor version */ + while (*p >= '0' && *p <= '9') { + *minor = *minor * 10 + (*p - '0'); + p++; + } +} + +/* Load Core 1.0 functions */ +static int glad_load_gl_1_0(GLADloadfunc load) { + glad_glClear = (PFNGLCLEARPROC)load("glClear"); + glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); + glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); + glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); + glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); + glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); + glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); + glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); + glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); + glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); + glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); + glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); + glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); + + return glad_glClear && glad_glClearColor && glad_glEnable && glad_glDisable && + glad_glViewport && glad_glTexImage2D && glad_glTexParameteri && + glad_glBindTexture && glad_glDeleteTextures && glad_glGenTextures && + glad_glDrawArrays && glad_glGetString && glad_glGetIntegerv && glad_glBlendFunc; +} + +/* Load Core 1.3 functions */ +static int glad_load_gl_1_3(GLADloadfunc load) { + glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); + return glad_glActiveTexture != NULL; +} + +/* Load Core 1.5 functions */ +static int glad_load_gl_1_5(GLADloadfunc load) { + glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); + glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); + glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); + glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); + + return glad_glGenBuffers && glad_glDeleteBuffers && + glad_glBindBuffer && glad_glBufferData; +} + +/* Load Core 2.0 functions */ +static int glad_load_gl_2_0(GLADloadfunc load) { + glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); + glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); + glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); + glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); + glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); + glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); + glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); + glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); + glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); + glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); + glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); + glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); + glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); + glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); + glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); + glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); + glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); + glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); + glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); + glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); + glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); + glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); + glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); + glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); + + return glad_glCreateShader && glad_glDeleteShader && glad_glShaderSource && + glad_glCompileShader && glad_glGetShaderiv && glad_glGetShaderInfoLog && + glad_glCreateProgram && glad_glDeleteProgram && glad_glAttachShader && + glad_glLinkProgram && glad_glGetProgramiv && glad_glGetProgramInfoLog && + glad_glUseProgram && glad_glGetUniformLocation && glad_glUniform1i && + glad_glUniform1f && glad_glUniform2f && glad_glUniform4f && + glad_glUniformMatrix4fv && glad_glBindAttribLocation && glad_glDetachShader && + glad_glVertexAttribPointer && glad_glEnableVertexAttribArray && + glad_glDisableVertexAttribArray; +} + +/* Load Core 3.0 functions (framebuffer and VAO) */ +static int glad_load_gl_3_0(GLADloadfunc load) { + /* Framebuffer functions */ + glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); + glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); + glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); + glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); + glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); + glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); + glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); + glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); + glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); + glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); + glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); + + /* Mipmap */ + glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); + + /* VAO functions */ + glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); + glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); + glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); + + return glad_glGenFramebuffers && glad_glDeleteFramebuffers && + glad_glBindFramebuffer && glad_glFramebufferTexture2D && + glad_glCheckFramebufferStatus && glad_glGenRenderbuffers && + glad_glDeleteRenderbuffers && glad_glBindRenderbuffer && + glad_glRenderbufferStorage && glad_glFramebufferRenderbuffer && + glad_glBlitFramebuffer && glad_glGenVertexArrays && + glad_glDeleteVertexArrays && glad_glBindVertexArray; +} + +/** + * Initialize GLAD loader + * + * @param load Function pointer to load GL function pointers (e.g., SDL_GL_GetProcAddress) + * @return GL version (major * 10000 + minor), or 0 on failure + */ +int gladLoadGL(GLADloadfunc load) { + int major = 0, minor = 0; + const char* version; + + if (load == NULL) { + return 0; + } + + /* First, we need glGetString to get the version */ + glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + if (glad_glGetString == NULL) { + return 0; + } + + version = (const char*)glad_glGetString(0x1F02); /* GL_VERSION */ + if (version == NULL) { + return 0; + } + + glad_parse_version(version, &major, &minor); + + /* Set version flags */ + GLAD_GL_VERSION_1_0 = (major > 1 || (major == 1 && minor >= 0)); + GLAD_GL_VERSION_1_1 = (major > 1 || (major == 1 && minor >= 1)); + GLAD_GL_VERSION_1_2 = (major > 1 || (major == 1 && minor >= 2)); + GLAD_GL_VERSION_1_3 = (major > 1 || (major == 1 && minor >= 3)); + GLAD_GL_VERSION_1_4 = (major > 1 || (major == 1 && minor >= 4)); + GLAD_GL_VERSION_1_5 = (major > 1 || (major == 1 && minor >= 5)); + GLAD_GL_VERSION_2_0 = (major > 2 || (major == 2 && minor >= 0)); + GLAD_GL_VERSION_2_1 = (major > 2 || (major == 2 && minor >= 1)); + GLAD_GL_VERSION_3_0 = (major > 3 || (major == 3 && minor >= 0)); + GLAD_GL_VERSION_3_1 = (major > 3 || (major == 3 && minor >= 1)); + GLAD_GL_VERSION_3_2 = (major > 3 || (major == 3 && minor >= 2)); + GLAD_GL_VERSION_3_3 = (major > 3 || (major == 3 && minor >= 3)); + + /* Load functions by version */ + if (GLAD_GL_VERSION_1_0 && !glad_load_gl_1_0(load)) return 0; + if (GLAD_GL_VERSION_1_3 && !glad_load_gl_1_3(load)) return 0; + if (GLAD_GL_VERSION_1_5 && !glad_load_gl_1_5(load)) return 0; + if (GLAD_GL_VERSION_2_0 && !glad_load_gl_2_0(load)) return 0; + if (GLAD_GL_VERSION_3_0 && !glad_load_gl_3_0(load)) return 0; + + return major * 10000 + minor; +} diff --git a/libs/imgui/LICENSE.txt b/libs/imgui/LICENSE.txt new file mode 100644 index 0000000..d5ba315 --- /dev/null +++ b/libs/imgui/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2026 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/libs/imgui/backends/imgui_impl_dx11.cpp b/libs/imgui/backends/imgui_impl_dx11.cpp new file mode 100644 index 0000000..36b936e --- /dev/null +++ b/libs/imgui/backends/imgui_impl_dx11.cpp @@ -0,0 +1,843 @@ +// dear imgui: Renderer Backend for DirectX11 +// This needs to be used along with a Platform Backend (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2026-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2026-01-19: DirectX11: Added 'SamplerNearest' in ImGui_ImplDX11_RenderState. Renamed 'SamplerDefault' to 'SamplerLinear'. +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. +// 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. +// 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). +// 2025-02-24: [Docking] Added undocumented ImGui_ImplDX11_SetSwapChainDescs() to configure swap chain creation for secondary viewports. +// 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler. +// 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap. +// 2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) +// 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer. +// 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled). +// 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX11_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore. +// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility. +// 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions. +// 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example. +// 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself. +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2016-05-07: DirectX11: Disabling depth-write. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_dx11.h" + +// DirectX +#include +#include +#include +#ifdef _MSC_VER +#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + +// DirectX11 data +struct ImGui_ImplDX11_Texture +{ + ID3D11Texture2D* pTexture; + ID3D11ShaderResourceView* pTextureView; +}; + +struct ImGui_ImplDX11_Data +{ + ID3D11Device* pd3dDevice; + ID3D11DeviceContext* pd3dDeviceContext; + IDXGIFactory* pFactory; + ID3D11Buffer* pVB; + ID3D11Buffer* pIB; + ID3D11VertexShader* pVertexShader; + ID3D11InputLayout* pInputLayout; + ID3D11Buffer* pVertexConstantBuffer; + ID3D11PixelShader* pPixelShader; + ID3D11SamplerState* pTexSamplerLinear; + ID3D11SamplerState* pTexSamplerNearest; + ID3D11RasterizerState* pRasterizerState; + ID3D11BlendState* pBlendState; + ID3D11DepthStencilState* pDepthStencilState; + int VertexBufferSize; + int IndexBufferSize; + ImVector SwapChainDescsForViewports; + + ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } +}; + +struct VERTEX_CONSTANT_BUFFER_DX11 +{ + float mvp[4][4]; +}; + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +// Forward Declarations +static void ImGui_ImplDX11_InitMultiViewportSupport(); +static void ImGui_ImplDX11_ShutdownMultiViewportSupport(); + +// Functions +static void ImGui_ImplDX11_SetupRenderState(const ImDrawData* draw_data, ID3D11DeviceContext* device_ctx) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + + // Setup viewport + D3D11_VIEWPORT vp = {}; + vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x; + vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + vp.TopLeftX = vp.TopLeftY = 0; + device_ctx->RSSetViewports(1, &vp); + + // Setup orthographic projection matrix into our constant buffer + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + D3D11_MAPPED_SUBRESOURCE mapped_resource; + if (device_ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK) + { + VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float mvp[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, + }; + memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); + device_ctx->Unmap(bd->pVertexConstantBuffer, 0); + } + + // Setup shader and vertex buffers + unsigned int stride = sizeof(ImDrawVert); + unsigned int offset = 0; + device_ctx->IASetInputLayout(bd->pInputLayout); + device_ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset); + device_ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); + device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0); + device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); + device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0); + device_ctx->PSSetSamplers(0, 1, &bd->pTexSamplerLinear); + device_ctx->GSSetShader(nullptr, nullptr, 0); + device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. + device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. + device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. + + // Setup render state + const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; + device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff); + device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0); + device_ctx->RSSetState(bd->pRasterizerState); +} + +// Render function +void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) +{ + // Avoid rendering when minimized + if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + return; + + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + ID3D11DeviceContext* device = bd->pd3dDeviceContext; + + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplDX11_UpdateTexture(tex); + + // Create and grow vertex/index buffers if needed + if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) + { + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } + bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; + D3D11_BUFFER_DESC desc = {}; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) + return; + } + if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) + { + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } + bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; + D3D11_BUFFER_DESC desc = {}; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) + return; + } + + // Upload vertex/index data into a single contiguous GPU buffer + D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; + if (device->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) + return; + if (device->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK) + return; + ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; + ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; + for (const ImDrawList* draw_list : draw_data->CmdLists) + { + memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + vtx_dst += draw_list->VtxBuffer.Size; + idx_dst += draw_list->IdxBuffer.Size; + } + device->Unmap(bd->pVB, 0); + device->Unmap(bd->pIB, 0); + + // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) + struct BACKUP_DX11_STATE + { + UINT ScissorRectsCount, ViewportsCount; + D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; + D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; + ID3D11RasterizerState* RS; + ID3D11BlendState* BlendState; + FLOAT BlendFactor[4]; + UINT SampleMask; + UINT StencilRef; + ID3D11DepthStencilState* DepthStencilState; + ID3D11ShaderResourceView* PSShaderResource; + ID3D11SamplerState* PSSampler; + ID3D11PixelShader* PS; + ID3D11VertexShader* VS; + ID3D11GeometryShader* GS; + UINT PSInstancesCount, VSInstancesCount, GSInstancesCount; + ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation + D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; + ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; + UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; + DXGI_FORMAT IndexBufferFormat; + ID3D11InputLayout* InputLayout; + }; + BACKUP_DX11_STATE old = {}; + old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; + device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); + device->RSGetViewports(&old.ViewportsCount, old.Viewports); + device->RSGetState(&old.RS); + device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); + device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); + device->PSGetShaderResources(0, 1, &old.PSShaderResource); + device->PSGetSamplers(0, 1, &old.PSSampler); + old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256; + device->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); + device->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); + device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); + device->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount); + + device->IAGetPrimitiveTopology(&old.PrimitiveTopology); + device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); + device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); + device->IAGetInputLayout(&old.InputLayout); + + // Setup desired DX state + ImGui_ImplDX11_SetupRenderState(draw_data, device); + + // Setup render state structure (for callbacks and custom texture bindings) + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + ImGui_ImplDX11_RenderState render_state; + render_state.Device = bd->pd3dDevice; + render_state.DeviceContext = bd->pd3dDeviceContext; + render_state.SamplerLinear = bd->pTexSamplerLinear; + render_state.SamplerNearest = bd->pTexSamplerNearest; + render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; + platform_io.Renderer_RenderState = &render_state; + + // Render command lists + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_idx_offset = 0; + int global_vtx_offset = 0; + ImVec2 clip_off = draw_data->DisplayPos; + ImVec2 clip_scale = draw_data->FramebufferScale; + for (const ImDrawList* draw_list : draw_data->CmdLists) + { + for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != nullptr) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX11_SetupRenderState(draw_data, device); + else + pcmd->UserCallback(draw_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // Apply scissor/clipping rectangle + const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; + device->RSSetScissorRects(1, &r); + + // Bind texture, Draw + ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID(); + device->PSSetShaderResources(0, 1, &texture_srv); + device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); + } + } + global_idx_offset += draw_list->IdxBuffer.Size; + global_vtx_offset += draw_list->VtxBuffer.Size; + } + platform_io.Renderer_RenderState = nullptr; + + // Restore modified DX state + device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); + device->RSSetViewports(old.ViewportsCount, old.Viewports); + device->RSSetState(old.RS); if (old.RS) old.RS->Release(); + device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); + device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); + device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); + device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); + device->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release(); + for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); + device->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); + device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); + device->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release(); + for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); + device->IASetPrimitiveTopology(old.PrimitiveTopology); + device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); + device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); + device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); +} + +static void ImGui_ImplDX11_DestroyTexture(ImTextureData* tex) +{ + if (ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); + backend_tex->pTextureView->Release(); + backend_tex->pTexture->Release(); + IM_DELETE(backend_tex); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } + tex->SetStatus(ImTextureStatus_Destroyed); +} + +void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + unsigned int* pixels = (unsigned int*)tex->GetPixels(); + ImGui_ImplDX11_Texture* backend_tex = IM_NEW(ImGui_ImplDX11_Texture)(); + + // Create texture + D3D11_TEXTURE2D_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.Width = (UINT)tex->Width; + desc.Height = (UINT)tex->Height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.CPUAccessFlags = 0; + D3D11_SUBRESOURCE_DATA subResource; + subResource.pSysMem = pixels; + subResource.SysMemPitch = desc.Width * 4; + subResource.SysMemSlicePitch = 0; + bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture); + IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!"); + + // Create texture view + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; + ZeroMemory(&srvDesc, sizeof(srvDesc)); + srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Texture2D.MostDetailedMip = 0; + bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srvDesc, &backend_tex->pTextureView); + IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!"); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView); + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = backend_tex; + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // Update selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. + ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData; + IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); + for (ImTextureRect& r : tex->Updates) + { + D3D11_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r .h), (UINT)1 }; + bd->pd3dDeviceContext->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0); + } + tex->SetStatus(ImTextureStatus_OK); + } + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplDX11_DestroyTexture(tex); +} + +bool ImGui_ImplDX11_CreateDeviceObjects() +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + if (!bd->pd3dDevice) + return false; + ImGui_ImplDX11_InvalidateDeviceObjects(); + + // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) + // If you would like to use this DX11 sample code but remove this dependency you can: + // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution] + // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. + // See https://github.com/ocornut/imgui/pull/638 for sources and details. + + // Create the vertex shader + { + static const char* vertexShader = + "cbuffer vertexBuffer : register(b0) \ + {\ + float4x4 ProjectionMatrix; \ + };\ + struct VS_INPUT\ + {\ + float2 pos : POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ + };\ + \ + struct PS_INPUT\ + {\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ + };\ + \ + PS_INPUT main(VS_INPUT input)\ + {\ + PS_INPUT output;\ + output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ + output.col = input.col;\ + output.uv = input.uv;\ + return output;\ + }"; + + ID3DBlob* vertexShaderBlob; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK) + { + vertexShaderBlob->Release(); + return false; + } + + // Create the input layout + D3D11_INPUT_ELEMENT_DESC local_layout[] = + { + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) + { + vertexShaderBlob->Release(); + return false; + } + vertexShaderBlob->Release(); + + // Create the constant buffer + { + D3D11_BUFFER_DESC desc = {}; + desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11); + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); + } + } + + // Create the pixel shader + { + static const char* pixelShader = + "struct PS_INPUT\ + {\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ + };\ + sampler sampler0;\ + Texture2D texture0;\ + \ + float4 main(PS_INPUT input) : SV_Target\ + {\ + float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ + return out_col; \ + }"; + + ID3DBlob* pixelShaderBlob; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK) + { + pixelShaderBlob->Release(); + return false; + } + pixelShaderBlob->Release(); + } + + // Create the blending setup + { + D3D11_BLEND_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.AlphaToCoverageEnable = false; + desc.RenderTarget[0].BlendEnable = true; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState); + } + + // Create the rasterizer state + { + D3D11_RASTERIZER_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.FillMode = D3D11_FILL_SOLID; + desc.CullMode = D3D11_CULL_NONE; + desc.ScissorEnable = true; + desc.DepthClipEnable = true; + bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState); + } + + // Create depth-stencil State + { + D3D11_DEPTH_STENCIL_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.DepthEnable = false; + desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + desc.DepthFunc = D3D11_COMPARISON_ALWAYS; + desc.StencilEnable = false; + desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + desc.BackFace = desc.FrontFace; + bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState); + } + + // Create texture sampler + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + { + D3D11_SAMPLER_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; + desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; + desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + desc.MipLODBias = 0.f; + desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; + desc.MinLOD = 0.f; + desc.MaxLOD = 0.f; + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear); + desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerNearest); + } + + return true; +} + +void ImGui_ImplDX11_InvalidateDeviceObjects() +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + if (!bd->pd3dDevice) + return; + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplDX11_DestroyTexture(tex); + + if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } + if (bd->pTexSamplerNearest) { bd->pTexSamplerNearest->Release(); bd->pTexSamplerNearest = nullptr; } + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } + if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } + if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } + if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } + if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } + if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } + if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } + if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } +} + +bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_dx11"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + + // Get factory from device + IDXGIDevice* pDXGIDevice = nullptr; + IDXGIAdapter* pDXGIAdapter = nullptr; + IDXGIFactory* pFactory = nullptr; + + if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) + if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) + if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) + { + bd->pd3dDevice = device; + bd->pd3dDeviceContext = device_context; + bd->pFactory = pFactory; + } + if (pDXGIDevice) pDXGIDevice->Release(); + if (pDXGIAdapter) pDXGIAdapter->Release(); + bd->pd3dDevice->AddRef(); + bd->pd3dDeviceContext->AddRef(); + + ImGui_ImplDX11_InitMultiViewportSupport(); + + return true; +} + +void ImGui_ImplDX11_Shutdown() +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + + ImGui_ImplDX11_ShutdownMultiViewportSupport(); + ImGui_ImplDX11_InvalidateDeviceObjects(); + if (bd->pFactory) { bd->pFactory->Release(); } + if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } + if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports); + platform_io.ClearRendererHandlers(); + IM_DELETE(bd); +} + +void ImGui_ImplDX11_NewFrame() +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?"); + + if (!bd->pVertexShader) + if (!ImGui_ImplDX11_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplDX11_CreateDeviceObjects() failed!"); +} + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +struct ImGui_ImplDX11_ViewportData +{ + IDXGISwapChain* SwapChain; + ID3D11RenderTargetView* RTView; + + ImGui_ImplDX11_ViewportData() { SwapChain = nullptr; RTView = nullptr; } + ~ImGui_ImplDX11_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); } +}; + +// Multi-Viewports: configure templates used when creating swapchains for secondary viewports. Will try them in order. +// This is intentionally not declared in the .h file yet, so you will need to copy this declaration: +void ImGui_ImplDX11_SetSwapChainDescs(const DXGI_SWAP_CHAIN_DESC* desc_templates, int desc_templates_count); +void ImGui_ImplDX11_SetSwapChainDescs(const DXGI_SWAP_CHAIN_DESC* desc_templates, int desc_templates_count) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + bd->SwapChainDescsForViewports.resize(desc_templates_count); + memcpy(bd->SwapChainDescsForViewports.Data, desc_templates, sizeof(DXGI_SWAP_CHAIN_DESC)); +} + +static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + ImGui_ImplDX11_ViewportData* vd = IM_NEW(ImGui_ImplDX11_ViewportData)(); + viewport->RendererUserData = vd; + + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID). + // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; + IM_ASSERT(hwnd != 0); + IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr); + + // Create swap chain + HRESULT hr = DXGI_ERROR_UNSUPPORTED; + for (const DXGI_SWAP_CHAIN_DESC& sd_template : bd->SwapChainDescsForViewports) + { + IM_ASSERT(sd_template.BufferDesc.Width == 0 && sd_template.BufferDesc.Height == 0 && sd_template.OutputWindow == nullptr); + DXGI_SWAP_CHAIN_DESC sd = sd_template; + sd.BufferDesc.Width = (UINT)viewport->Size.x; + sd.BufferDesc.Height = (UINT)viewport->Size.y; + sd.OutputWindow = hwnd; + hr = bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain); + if (SUCCEEDED(hr)) + break; + } + IM_ASSERT(SUCCEEDED(hr)); + bd->pFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); // Disable e.g. Alt+Enter + + // Create the render target + if (vd->SwapChain != nullptr) + { + ID3D11Texture2D* pBackBuffer; + vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView); + pBackBuffer->Release(); + } +} + +static void ImGui_ImplDX11_DestroyWindow(ImGuiViewport* viewport) +{ + // The main viewport (owned by the application) will always have RendererUserData == nullptr since we didn't create the data for it. + if (ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData) + { + if (vd->SwapChain) + vd->SwapChain->Release(); + vd->SwapChain = nullptr; + if (vd->RTView) + vd->RTView->Release(); + vd->RTView = nullptr; + IM_DELETE(vd); + } + viewport->RendererUserData = nullptr; +} + +static void ImGui_ImplDX11_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData; + if (vd->RTView) + { + vd->RTView->Release(); + vd->RTView = nullptr; + } + if (vd->SwapChain) + { + ID3D11Texture2D* pBackBuffer = nullptr; + vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0); + vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX11_SetWindowSize() failed creating buffers.\n"); return; } + bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView); + pBackBuffer->Release(); + } +} + +static void ImGui_ImplDX11_RenderWindow(ImGuiViewport* viewport, void*) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData; + ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + bd->pd3dDeviceContext->OMSetRenderTargets(1, &vd->RTView, nullptr); + if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) + bd->pd3dDeviceContext->ClearRenderTargetView(vd->RTView, (float*)&clear_color); + ImGui_ImplDX11_RenderDrawData(viewport->DrawData); +} + +static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport, void*) +{ + ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData; + if (vd->SwapChain) + vd->SwapChain->Present(0, 0); // Present without vsync +} + +static void ImGui_ImplDX11_InitMultiViewportSupport() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_CreateWindow = ImGui_ImplDX11_CreateWindow; + platform_io.Renderer_DestroyWindow = ImGui_ImplDX11_DestroyWindow; + platform_io.Renderer_SetWindowSize = ImGui_ImplDX11_SetWindowSize; + platform_io.Renderer_RenderWindow = ImGui_ImplDX11_RenderWindow; + platform_io.Renderer_SwapBuffers = ImGui_ImplDX11_SwapBuffers; + + // Default swapchain format + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.BufferCount = 1; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + sd.Flags = 0; + ImGui_ImplDX11_SetSwapChainDescs(&sd, 1); +} + +static void ImGui_ImplDX11_ShutdownMultiViewportSupport() +{ + ImGui::DestroyPlatformWindows(); +} + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/backends/imgui_impl_dx11.h b/libs/imgui/backends/imgui_impl_dx11.h new file mode 100644 index 0000000..bf27e42 --- /dev/null +++ b/libs/imgui/backends/imgui_impl_dx11.h @@ -0,0 +1,53 @@ +// dear imgui: Renderer Backend for DirectX11 +// This needs to be used along with a Platform Backend (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct ID3D11Device; +struct ID3D11DeviceContext; +struct ID3D11SamplerState; +struct ID3D11Buffer; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); +IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); + +// Use if you want to reset your rendering device without losing Dear ImGui state. +IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); + +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. +IMGUI_IMPL_API void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex); + +// [BETA] Selected render state data shared with callbacks. +// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call. +// (Please open an issue if you feel you need access to more data) +struct ImGui_ImplDX11_RenderState +{ + ID3D11Device* Device; + ID3D11DeviceContext* DeviceContext; + ID3D11SamplerState* SamplerLinear; + ID3D11SamplerState* SamplerNearest; + ID3D11Buffer* VertexConstantBuffer; +}; + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/backends/imgui_impl_opengl3.cpp b/libs/imgui/backends/imgui_impl_opengl3.cpp new file mode 100644 index 0000000..b515ce0 --- /dev/null +++ b/libs/imgui/backends/imgui_impl_opengl3.cpp @@ -0,0 +1,1104 @@ +// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline +// - Desktop GL: 2.x 3.x 4.x +// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// About WebGL/ES: +// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +// - This is done automatically on iOS, Android and Emscripten targets. +// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2026-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2025-12-11: OpenGL: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. +// 2025-07-22: OpenGL: Add and call embedded loader shutdown during ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) +// 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy. +// 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). +// 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) +// 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) +// 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. +// 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) +// 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) +// 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447) +// 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. +// 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983) +// 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445) +// 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333) +// 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375) +// 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333) +// 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224) +// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns nullptr. (#6154, #4445, #3530) +// 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224) +// 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes). +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'. +// 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127). +// 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states. +// 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers. +// 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions. +// 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader. +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state. +// 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader. +// 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version. +// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) +// 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater. +// 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer. +// 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state. +// 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state. +// 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x) +// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre-3.3 context which have the defines set by a loader. +// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. +// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. +// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. +// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. +// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. +// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader. +// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders. +// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility. +// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call. +// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. +// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. +// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). +// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. +// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. +// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN. +// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used. +// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES". +// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation. +// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link. +// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples. +// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state. +// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer. +// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150". +// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself. +// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150. +// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode. +// 2017-05-01: OpenGL: Fixed save and restore of current blend func state. +// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE. +// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. +// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752) + +//---------------------------------------- +// OpenGL GLSL GLSL +// version version string +//---------------------------------------- +// 2.0 110 "#version 110" +// 2.1 120 "#version 120" +// 3.0 130 "#version 130" +// 3.1 140 "#version 140" +// 3.2 150 "#version 150" +// 3.3 330 "#version 330 core" +// 4.0 400 "#version 400 core" +// 4.1 410 "#version 410 core" +// 4.2 420 "#version 410 core" +// 4.3 430 "#version 430 core" +// ES 2.0 100 "#version 100" = WebGL 1.0 +// ES 3.0 300 "#version 300 es" = WebGL 2.0 +//---------------------------------------- + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_opengl3.h" +#include +#include // intptr_t +#if defined(__APPLE__) +#include +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) +#endif +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 +#endif + +// GL includes +#if defined(IMGUI_IMPL_OPENGL_ES2) +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) +#include // Use GL ES 2 +#else +#include // Use GL ES 2 +#endif +#if defined(__EMSCRIPTEN__) +#ifndef GL_GLEXT_PROTOTYPES +#define GL_GLEXT_PROTOTYPES +#endif +#include +#endif +#elif defined(IMGUI_IMPL_OPENGL_ES3) +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) +#include // Use GL ES 3 +#else +#include // Use GL ES 3 +#endif +#elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) +// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. +// Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w. +// In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.). +// If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp): +// - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped +// Typically you would run: python3 ./gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt +// - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases +// Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version. +#define IMGL3W_IMPL +#define IMGUI_IMPL_OPENGL_LOADER_IMGL3W +#include "imgui_impl_opengl3_loader.h" +#endif + +// Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension +#ifndef IMGUI_IMPL_OPENGL_ES2 +#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY +#elif defined(__EMSCRIPTEN__) +#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY +#define glBindVertexArray glBindVertexArrayOES +#define glGenVertexArrays glGenVertexArraysOES +#define glDeleteVertexArrays glDeleteVertexArraysOES +#define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES +#endif + +// Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have.. +// A desktop ES context can technically compile fine with our loader, so we also perform a runtime checks +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) +#define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // may have glPolygonMode() +#endif + +// Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target. +#if !defined(IMGUI_IMPL_OPENGL_ES2) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK +#endif + +// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART +#endif + +// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET +#endif + +// Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler() +#if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3)) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER +#endif + +// [Debugging] +//#define IMGUI_IMPL_OPENGL_DEBUG +#ifdef IMGUI_IMPL_OPENGL_DEBUG +#include +#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check +#else +#define GL_CALL(_CALL) _CALL // Call without error check +#endif + +// OpenGL Data +struct ImGui_ImplOpenGL3_Data +{ + GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2) + char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings. + bool GlProfileIsES2; + bool GlProfileIsES3; + bool GlProfileIsCompat; + GLint GlProfileMask; + GLint MaxTextureSize; + GLuint ShaderHandle; + GLint AttribLocationTex; // Uniforms location + GLint AttribLocationProjMtx; + GLuint AttribLocationVtxPos; // Vertex attributes location + GLuint AttribLocationVtxUV; + GLuint AttribLocationVtxColor; + unsigned int VboHandle, ElementsHandle; + GLsizeiptr VertexBufferSize; + GLsizeiptr IndexBufferSize; + bool HasPolygonMode; + bool HasBindSampler; + bool HasClipOrigin; + bool UseBufferSubData; + ImVector TempBuffer; + + ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +// Forward Declarations +static void ImGui_ImplOpenGL3_InitMultiViewportSupport(); +static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport(); + +// OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY +struct ImGui_ImplOpenGL3_VtxAttribState +{ + GLint Enabled, Size, Type, Normalized, Stride; + GLvoid* Ptr; + + void GetState(GLint index) + { + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride); + glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr); + } + void SetState(GLint index) + { + glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr); + if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index); + } +}; +#endif + +// Not static to allow third-party code to use that if they want to (but undocumented) +bool ImGui_ImplOpenGL3_InitLoader(); +bool ImGui_ImplOpenGL3_InitLoader() +{ + // Lazily initialize our loader if not already done + // (to facilitate handling multiple DLL boundaries and multiple context shutdowns we call this from all main entry points) +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + if (glGetIntegerv == nullptr && imgl3wInit() != 0) + { + fprintf(stderr, "Failed to initialize OpenGL loader!\n"); + return false; + } +#endif + return true; +} + +static void ImGui_ImplOpenGL3_ShutdownLoader() +{ +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + imgl3wShutdown(); +#endif +} + +// Functions +bool ImGui_ImplOpenGL3_Init(const char* glsl_version) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Initialize loader + if (!ImGui_ImplOpenGL3_InitLoader()) + return false; + + // Setup backend capabilities flags + ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_opengl3"; + + // Query for GL version (e.g. 320 for GL 3.2) + const char* gl_version_str = (const char*)glGetString(GL_VERSION); +#if defined(IMGUI_IMPL_OPENGL_ES2) + // GLES 2 + bd->GlVersion = 200; + bd->GlProfileIsES2 = true; + IM_UNUSED(gl_version_str); +#else + // Desktop or GLES 3 + GLint major = 0; + GLint minor = 0; + glGetIntegerv(GL_MAJOR_VERSION, &major); + glGetIntegerv(GL_MINOR_VERSION, &minor); + if (major == 0 && minor == 0) + sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "." + bd->GlVersion = (GLuint)(major * 100 + minor * 10); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &bd->MaxTextureSize); + +#if defined(IMGUI_IMPL_OPENGL_ES3) + bd->GlProfileIsES3 = true; +#else + if (strncmp(gl_version_str, "OpenGL ES 3", 11) == 0) + bd->GlProfileIsES3 = true; +#endif + +#if defined(GL_CONTEXT_PROFILE_MASK) + if (!bd->GlProfileIsES3 && bd->GlVersion >= 320) + glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); + bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; +#endif + + bd->UseBufferSubData = false; + /* + // Query vendor to enable glBufferSubData kludge +#ifdef _WIN32 + if (const char* vendor = (const char*)glGetString(GL_VENDOR)) + if (strncmp(vendor, "Intel", 5) == 0) + bd->UseBufferSubData = true; +#endif + */ +#endif + +#ifdef IMGUI_IMPL_OPENGL_DEBUG + printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2/IsEs3 = %d/%d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] +#endif + +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET + if (bd->GlVersion >= 320) + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. +#endif + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = (int)bd->MaxTextureSize; + + // Store GLSL version string so we can refer to it later in case we recreate shaders. + // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. + if (glsl_version == nullptr) + { +#if defined(IMGUI_IMPL_OPENGL_ES2) + glsl_version = "#version 100"; +#elif defined(IMGUI_IMPL_OPENGL_ES3) + glsl_version = "#version 300 es"; +#elif defined(__APPLE__) + glsl_version = "#version 150"; +#else + glsl_version = "#version 130"; +#endif + } + IM_ASSERT((int)strlen(glsl_version) + 2 < IM_COUNTOF(bd->GlslVersionString)); + strcpy(bd->GlslVersionString, glsl_version); + strcat(bd->GlslVersionString, "\n"); + + // Make an arbitrary GL call (we don't actually need the result) + // IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know! + GLint current_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture); + + // Detect extensions we support +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE + bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3); +#endif +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + bd->HasBindSampler = (bd->GlVersion >= 330 || bd->GlProfileIsES3); +#endif + bd->HasClipOrigin = (bd->GlVersion >= 450); +#ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS + GLint num_extensions = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); + for (GLint i = 0; i < num_extensions; i++) + { + const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i); + if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0) + bd->HasClipOrigin = true; + } +#endif + + ImGui_ImplOpenGL3_InitMultiViewportSupport(); + + return true; +} + +void ImGui_ImplOpenGL3_Shutdown() +{ + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + + ImGui_ImplOpenGL3_ShutdownMultiViewportSupport(); + ImGui_ImplOpenGL3_DestroyDeviceObjects(); + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports); + platform_io.ClearRendererHandlers(); + IM_DELETE(bd); + + ImGui_ImplOpenGL3_ShutdownLoader(); +} + +void ImGui_ImplOpenGL3_NewFrame() +{ + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?"); + + ImGui_ImplOpenGL3_InitLoader(); + if (!bd->ShaderHandle) + if (!ImGui_ImplOpenGL3_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplOpenGL3_CreateDeviceObjects() failed!"); +} + +static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) +{ + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_STENCIL_TEST); + glEnable(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) + glDisable(GL_PRIMITIVE_RESTART); +#endif +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE + if (bd->HasPolygonMode) + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); +#endif + + // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) +#if defined(GL_CLIP_ORIGIN) + bool clip_origin_lower_left = true; + if (bd->HasClipOrigin) + { + GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); + if (current_clip_origin == GL_UPPER_LEFT) + clip_origin_lower_left = false; + } +#endif + + // Setup viewport, orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; +#if defined(GL_CLIP_ORIGIN) + if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left +#endif + const float ortho_projection[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, + }; + glUseProgram(bd->ShaderHandle); + glUniform1i(bd->AttribLocationTex, 0); + glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); + +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + if (bd->HasBindSampler) + glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise. +#endif + + (void)vertex_array_object; +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + glBindVertexArray(vertex_array_object); +#endif + + // Bind vertex/index buffers and setup attributes for ImDrawVert + GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle)); + GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor)); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos))); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv))); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col))); +} + +// OpenGL3 Render function. +// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. +// This is in order to be able to run within an OpenGL engine that doesn't do so. +void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0) + return; + + ImGui_ImplOpenGL3_InitLoader(); + + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplOpenGL3_UpdateTexture(tex); + + // Backup GL state + GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); + glActiveTexture(GL_TEXTURE0); + GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); + GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + GLuint last_sampler; if (bd->HasBindSampler) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } +#endif + GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + // This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+. + GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor); +#endif +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); +#endif +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE + GLint last_polygon_mode[2]; if (bd->HasPolygonMode) { glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); } +#endif + GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb); + GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb); + GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha); + GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha); + GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb); + GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha); + GLboolean last_enable_blend = glIsEnabled(GL_BLEND); + GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); + GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); + GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST); + GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; +#endif + + // Setup desired GL state + // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) + // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. + GLuint vertex_array_object = 0; +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + GL_CALL(glGenVertexArrays(1, &vertex_array_object)); +#endif + ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists + for (const ImDrawList* draw_list : draw_data->CmdLists) + { + // Upload vertex/index buffers + // - OpenGL drivers are in a very sorry state nowadays.... + // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports + // of leaks on Intel GPU when using multi-viewports on Windows. + // - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel. + // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code. + // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path. + // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues. + const GLsizeiptr vtx_buffer_size = (GLsizeiptr)draw_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); + const GLsizeiptr idx_buffer_size = (GLsizeiptr)draw_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); + if (bd->UseBufferSubData) + { + if (bd->VertexBufferSize < vtx_buffer_size) + { + bd->VertexBufferSize = vtx_buffer_size; + GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW)); + } + if (bd->IndexBufferSize < idx_buffer_size) + { + bd->IndexBufferSize = idx_buffer_size; + GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW)); + } + GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data)); + GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data)); + } + else + { + GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data, GL_STREAM_DRAW)); + GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data, GL_STREAM_DRAW)); + } + + for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != nullptr) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); + else + pcmd->UserCallback(draw_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // Apply scissor/clipping rectangle (Y is inverted in OpenGL) + GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y))); + + // Bind texture, Draw + GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID())); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET + if (bd->GlVersion >= 320) + GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset)); + else +#endif + GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)))); + } + } + } + + // Destroy the temporary VAO +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + GL_CALL(glDeleteVertexArrays(1, &vertex_array_object)); +#endif + + // Restore modified GL state + // This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220. + if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program); + glBindTexture(GL_TEXTURE_2D, last_texture); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + if (bd->HasBindSampler) + glBindSampler(0, last_sampler); +#endif + glActiveTexture(last_active_texture); +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + glBindVertexArray(last_vertex_array_object); +#endif + glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); + last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos); + last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV); + last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor); +#endif + glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); + glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); + if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); + if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); + if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); + if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); + if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } +#endif + +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE + // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons + if (bd->HasPolygonMode) { if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) { glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); } else { glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); } } +#endif // IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE + + glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); + glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); + (void)bd; // Not all compilation paths use this +} + +static void ImGui_ImplOpenGL3_DestroyTexture(ImTextureData* tex) +{ + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + glDeleteTextures(1, &gl_tex_id); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); +} + +void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) +{ + // FIXME: Consider backing up and restoring + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) + { +#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#endif +#ifdef GL_UNPACK_ALIGNMENT + GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); +#endif + } + + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + const void* pixels = tex->GetPixels(); + GLuint gl_texture_id = 0; + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + GL_CALL(glGenTextures(1, &gl_texture_id)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); + GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id); + tex->SetStatus(ImTextureStatus_OK); + + // Restore state + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // Update selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); +#if GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); + for (ImTextureRect& r : tex->Updates) + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#else + // GL ES doesn't have GL_UNPACK_ROW_LENGTH, so we need to (A) copy to a contiguous buffer or (B) upload line by line. + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + for (ImTextureRect& r : tex->Updates) + { + const int src_pitch = r.w * tex->BytesPerPixel; + bd->TempBuffer.resize(r.h * src_pitch); + char* out_p = bd->TempBuffer.Data; + for (int y = 0; y < r.h; y++, out_p += src_pitch) + memcpy(out_p, tex->GetPixelsAt(r.x, r.y + y), src_pitch); + IM_ASSERT(out_p == bd->TempBuffer.end()); + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, bd->TempBuffer.Data)); + } +#endif + tex->SetStatus(ImTextureStatus_OK); + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state + } + else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplOpenGL3_DestroyTexture(tex); +} + +// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file. +static bool CheckShader(GLuint handle, const char* desc) +{ + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + GLint status = 0, log_length = 0; + glGetShaderiv(handle, GL_COMPILE_STATUS, &status); + glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length); + if ((GLboolean)status == GL_FALSE) + fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString); + if (log_length > 1) + { + ImVector buf; + buf.resize((int)(log_length + 1)); + glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); + fprintf(stderr, "%s\n", buf.begin()); + } + return (GLboolean)status == GL_TRUE; +} + +// If you get an error please report on GitHub. You may try different GL context version or GLSL version. +static bool CheckProgram(GLuint handle, const char* desc) +{ + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + GLint status = 0, log_length = 0; + glGetProgramiv(handle, GL_LINK_STATUS, &status); + glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length); + if ((GLboolean)status == GL_FALSE) + fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString); + if (log_length > 1) + { + ImVector buf; + buf.resize((int)(log_length + 1)); + glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); + fprintf(stderr, "%s\n", buf.begin()); + } + return (GLboolean)status == GL_TRUE; +} + +bool ImGui_ImplOpenGL3_CreateDeviceObjects() +{ + ImGui_ImplOpenGL3_InitLoader(); + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + + // Backup GL state + GLint last_texture, last_array_buffer; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK + GLint last_pixel_unpack_buffer = 0; + if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } +#endif +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + GLint last_vertex_array; + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); +#endif + + // Parse GLSL version string + int glsl_version = 130; + sscanf(bd->GlslVersionString, "#version %d", &glsl_version); + + const GLchar* vertex_shader_glsl_120 = + "uniform mat4 ProjMtx;\n" + "attribute vec2 Position;\n" + "attribute vec2 UV;\n" + "attribute vec4 Color;\n" + "varying vec2 Frag_UV;\n" + "varying vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* vertex_shader_glsl_130 = + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* vertex_shader_glsl_300_es = + "precision highp float;\n" + "layout (location = 0) in vec2 Position;\n" + "layout (location = 1) in vec2 UV;\n" + "layout (location = 2) in vec4 Color;\n" + "uniform mat4 ProjMtx;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* vertex_shader_glsl_410_core = + "layout (location = 0) in vec2 Position;\n" + "layout (location = 1) in vec2 UV;\n" + "layout (location = 2) in vec4 Color;\n" + "uniform mat4 ProjMtx;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* fragment_shader_glsl_120 = + "#ifdef GL_ES\n" + " precision mediump float;\n" + "#endif\n" + "uniform sampler2D Texture;\n" + "varying vec2 Frag_UV;\n" + "varying vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" + "}\n"; + + const GLchar* fragment_shader_glsl_130 = + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; + + const GLchar* fragment_shader_glsl_300_es = + "precision mediump float;\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "layout (location = 0) out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; + + const GLchar* fragment_shader_glsl_410_core = + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "uniform sampler2D Texture;\n" + "layout (location = 0) out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; + + // Select shaders matching our GLSL versions + const GLchar* vertex_shader = nullptr; + const GLchar* fragment_shader = nullptr; + if (glsl_version < 130) + { + vertex_shader = vertex_shader_glsl_120; + fragment_shader = fragment_shader_glsl_120; + } + else if (glsl_version >= 410) + { + vertex_shader = vertex_shader_glsl_410_core; + fragment_shader = fragment_shader_glsl_410_core; + } + else if (glsl_version == 300) + { + vertex_shader = vertex_shader_glsl_300_es; + fragment_shader = fragment_shader_glsl_300_es; + } + else + { + vertex_shader = vertex_shader_glsl_130; + fragment_shader = fragment_shader_glsl_130; + } + + // Create shaders + const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader }; + GLuint vert_handle; + GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER)); + glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr); + glCompileShader(vert_handle); + if (!CheckShader(vert_handle, "vertex shader")) + return false; + + const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader }; + GLuint frag_handle; + GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER)); + glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr); + glCompileShader(frag_handle); + if (!CheckShader(frag_handle, "fragment shader")) + return false; + + // Link + bd->ShaderHandle = glCreateProgram(); + glAttachShader(bd->ShaderHandle, vert_handle); + glAttachShader(bd->ShaderHandle, frag_handle); + glLinkProgram(bd->ShaderHandle); + if (!CheckProgram(bd->ShaderHandle, "shader program")) + return false; + + glDetachShader(bd->ShaderHandle, vert_handle); + glDetachShader(bd->ShaderHandle, frag_handle); + glDeleteShader(vert_handle); + glDeleteShader(frag_handle); + + bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture"); + bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx"); + bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position"); + bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV"); + bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color"); + + // Create buffers + glGenBuffers(1, &bd->VboHandle); + glGenBuffers(1, &bd->ElementsHandle); + + // Restore modified GL state + glBindTexture(GL_TEXTURE_2D, last_texture); + glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK + if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); } +#endif +#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + glBindVertexArray(last_vertex_array); +#endif + + return true; +} + +void ImGui_ImplOpenGL3_DestroyDeviceObjects() +{ + ImGui_ImplOpenGL3_InitLoader(); + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; } + if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; } + if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; } + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplOpenGL3_DestroyTexture(tex); +} + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*) +{ + if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) + { + ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + } + ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData); +} + +static void ImGui_ImplOpenGL3_InitMultiViewportSupport() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow; +} + +static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport() +{ + ImGui::DestroyPlatformWindows(); +} + +//----------------------------------------------------------------------------- + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/backends/imgui_impl_opengl3.h b/libs/imgui/backends/imgui_impl_opengl3.h new file mode 100644 index 0000000..7855c43 --- /dev/null +++ b/libs/imgui/backends/imgui_impl_opengl3.h @@ -0,0 +1,69 @@ +// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline +// - Desktop GL: 2.x 3.x 4.x +// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// About WebGL/ES: +// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +// - This is done automatically on iOS, Android and Emscripten targets. +// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// About GLSL version: +// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. +// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" +// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); +IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); + +// (Optional) Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); + +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. +IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); + +// Configuration flags to add in your imconfig file: +//#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) +//#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) + +// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. +#if !defined(IMGUI_IMPL_OPENGL_ES2) \ + && !defined(IMGUI_IMPL_OPENGL_ES3) + +// Try to detect GLES on matching platforms +#if defined(__APPLE__) +#include +#endif +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) +#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" +#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__) +#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" +#else +// Otherwise imgui_impl_opengl3_loader.h will be used. +#endif + +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/backends/imgui_impl_opengl3_loader.h b/libs/imgui/backends/imgui_impl_opengl3_loader.h new file mode 100644 index 0000000..2c48584 --- /dev/null +++ b/libs/imgui/backends/imgui_impl_opengl3_loader.h @@ -0,0 +1,958 @@ +//----------------------------------------------------------------------------- +// About imgui_impl_opengl3_loader.h: +// +// We embed our own OpenGL loader to not require user to provide their own or to have to use ours, +// which proved to be endless problems for users. +// Our loader is custom-generated, based on gl3w but automatically filtered to only include +// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small. +// +// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY. +// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE. +// +// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions): +// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h' +// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER. +// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS) +// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT. +// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp +// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT. +// +// Regenerate with: +// python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt +// +// More info: +// https://github.com/dearimgui/gl3w_stripped +// https://github.com/ocornut/imgui/issues/4445 +//----------------------------------------------------------------------------- + +/* + * This file was generated with gl3w_gen.py, part of imgl3w + * (hosted at https://github.com/dearimgui/gl3w_stripped) + * + * This is free and unencumbered software released into the public domain. + * + * Anyone is free to copy, modify, publish, use, compile, sell, or + * distribute this software, either in source code form or as a compiled + * binary, for any purpose, commercial or non-commercial, and by any + * means. + * + * In jurisdictions that recognize copyright laws, the author or authors + * of this software dedicate any and all copyright interest in the + * software to the public domain. We make this dedication for the benefit + * of the public at large and to the detriment of our heirs and + * successors. We intend this dedication to be an overt act of + * relinquishment in perpetuity of all present and future rights to this + * software under copyright law. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __gl3w_h_ +#define __gl3w_h_ + +// Adapted from KHR/khrplatform.h to avoid including entire file. +#ifndef __khrplatform_h_ +typedef float khronos_float_t; +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef signed long long int khronos_ssize_t; +#else +typedef signed long int khronos_intptr_t; +typedef signed long int khronos_ssize_t; +#endif + +#if defined(_MSC_VER) && !defined(__clang__) +typedef signed __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100) +#include +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#else +typedef signed long long khronos_int64_t; +typedef unsigned long long khronos_uint64_t; +#endif +#endif // __khrplatform_h_ + +#ifndef __gl_glcorearb_h_ +#define __gl_glcorearb_h_ 1 +#ifdef __cplusplus +extern "C" { +#endif +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: MIT +** +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** https://github.com/KhronosGroup/OpenGL-Registry +*/ +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif +#ifndef GLAPI +#define GLAPI extern +#endif +/* glcorearb.h is for use with OpenGL core profile implementations. +** It should should be placed in the same directory as gl.h and +** included as . +** +** glcorearb.h includes only APIs in the latest OpenGL core profile +** implementation together with APIs in newer ARB extensions which +** can be supported by the core profile. It does not, and never will +** include functionality removed from the core profile, such as +** fixed-function vertex and fragment processing. +** +** Do not #include both and either of or +** in the same source file. +*/ +/* Generated C header for: + * API: gl + * Profile: core + * Versions considered: .* + * Versions emitted: .* + * Default extensions included: glcore + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ +#ifndef GL_VERSION_1_0 +typedef void GLvoid; +typedef unsigned int GLenum; + +typedef khronos_float_t GLfloat; +typedef int GLint; +typedef int GLsizei; +typedef unsigned int GLbitfield; +typedef double GLdouble; +typedef unsigned int GLuint; +typedef unsigned char GLboolean; +typedef khronos_uint8_t GLubyte; +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_TRIANGLES 0x0004 +#define GL_ONE 1 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_POLYGON_MODE 0x0B40 +#define GL_CULL_FACE 0x0B44 +#define GL_DEPTH_TEST 0x0B71 +#define GL_STENCIL_TEST 0x0B90 +#define GL_VIEWPORT 0x0BA2 +#define GL_BLEND 0x0BE2 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_RGBA 0x1908 +#define GL_FILL 0x1B02 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_REPEAT 0x2901 +typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode); +typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap); +typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap); +typedef void (APIENTRYP PFNGLFLUSHPROC) (void); +typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void); +typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); +typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); +typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); +typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode); +GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glClear (GLbitfield mask); +GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI void APIENTRY glDisable (GLenum cap); +GLAPI void APIENTRY glEnable (GLenum cap); +GLAPI void APIENTRY glFlush (void); +GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param); +GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +GLAPI GLenum APIENTRY glGetError (void); +GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data); +GLAPI const GLubyte *APIENTRY glGetString (GLenum name); +GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap); +GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_VERSION_1_0 */ +#ifndef GL_VERSION_1_1 +typedef khronos_float_t GLclampf; +typedef double GLclampd; +#define GL_TEXTURE_BINDING_2D 0x8069 +typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); +typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); +GLAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture); +GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); +GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures); +#endif +#endif /* GL_VERSION_1_1 */ +#ifndef GL_VERSION_1_2 +#define GL_CLAMP_TO_EDGE 0x812F +#endif /* GL_VERSION_1_2 */ +#ifndef GL_VERSION_1_3 +#define GL_TEXTURE0 0x84C0 +#define GL_ACTIVE_TEXTURE 0x84E0 +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTexture (GLenum texture); +#endif +#endif /* GL_VERSION_1_3 */ +#ifndef GL_VERSION_1_4 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_FUNC_ADD 0x8006 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI void APIENTRY glBlendEquation (GLenum mode); +#endif +#endif /* GL_VERSION_1_4 */ +#ifndef GL_VERSION_1_5 +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_intptr_t GLintptr; +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_STREAM_DRAW 0x88E0 +typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +#endif +#endif /* GL_VERSION_1_5 */ +#ifndef GL_VERSION_2_0 +typedef char GLchar; +typedef khronos_int16_t GLshort; +typedef khronos_int8_t GLbyte; +typedef khronos_uint16_t GLushort; +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_UPPER_LEFT 0x8CA2 +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glCompileShader (GLuint shader); +GLAPI GLuint APIENTRY glCreateProgram (void); +GLAPI GLuint APIENTRY glCreateShader (GLenum type); +GLAPI void APIENTRY glDeleteProgram (GLuint program); +GLAPI void APIENTRY glDeleteShader (GLuint shader); +GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); +GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgram (GLuint program); +GLAPI void APIENTRY glLinkProgram (GLuint program); +GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI void APIENTRY glUseProgram (GLuint program); +GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); +GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#endif +#endif /* GL_VERSION_2_0 */ +#ifndef GL_VERSION_2_1 +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#endif /* GL_VERSION_2_1 */ +#ifndef GL_VERSION_3_0 +typedef khronos_uint16_t GLhalf; +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); +typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); +GLAPI void APIENTRY glBindVertexArray (GLuint array); +GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); +#endif +#endif /* GL_VERSION_3_0 */ +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +#define GL_PRIMITIVE_RESTART 0x8F9D +#endif /* GL_VERSION_3_1 */ +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +typedef struct __GLsync *GLsync; +typedef khronos_uint64_t GLuint64; +typedef khronos_int64_t GLint64; +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +#endif +#endif /* GL_VERSION_3_2 */ +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +#define GL_SAMPLER_BINDING 0x8919 +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); +GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); +GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); +GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); +#endif +#endif /* GL_VERSION_3_3 */ +#ifndef GL_VERSION_4_1 +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); +#endif /* GL_VERSION_4_1 */ +#ifndef GL_VERSION_4_3 +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#endif /* GL_VERSION_4_3 */ +#ifndef GL_VERSION_4_5 +#define GL_CLIP_ORIGIN 0x935C +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +#endif /* GL_VERSION_4_5 */ +#ifndef GL_ARB_bindless_texture +typedef khronos_uint64_t GLuint64EXT; +#endif /* GL_ARB_bindless_texture */ +#ifndef GL_ARB_cl_event +struct _cl_context; +struct _cl_event; +#endif /* GL_ARB_cl_event */ +#ifndef GL_ARB_clip_control +#define GL_ARB_clip_control 1 +#endif /* GL_ARB_clip_control */ +#ifndef GL_ARB_debug_output +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#endif /* GL_ARB_debug_output */ +#ifndef GL_EXT_EGL_image_storage +typedef void *GLeglImageOES; +#endif /* GL_EXT_EGL_image_storage */ +#ifndef GL_EXT_direct_state_access +typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); +#endif /* GL_EXT_direct_state_access */ +#ifndef GL_NV_draw_vulkan_image +typedef void (APIENTRY *GLVULKANPROCNV)(void); +#endif /* GL_NV_draw_vulkan_image */ +#ifndef GL_NV_gpu_shader5 +typedef khronos_int64_t GLint64EXT; +#endif /* GL_NV_gpu_shader5 */ +#ifndef GL_NV_vertex_buffer_unified_memory +typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); +#endif /* GL_NV_vertex_buffer_unified_memory */ +#ifdef __cplusplus +} +#endif +#endif + +#ifndef GL3W_API +#define GL3W_API +#endif + +#ifndef __gl_h_ +#define __gl_h_ +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define GL3W_OK 0 +#define GL3W_ERROR_INIT -1 +#define GL3W_ERROR_LIBRARY_OPEN -2 +#define GL3W_ERROR_OPENGL_VERSION -3 + +typedef void (*GL3WglProc)(void); +typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc); + +/* gl3w api */ +GL3W_API int imgl3wInit(void); +GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc); +GL3W_API void imgl3wShutdown(void); +GL3W_API int imgl3wIsSupported(int major, int minor); +GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); + +/* gl3w internal state */ +union ImGL3WProcs { + GL3WglProc ptr[63]; + struct { + PFNGLACTIVETEXTUREPROC ActiveTexture; + PFNGLATTACHSHADERPROC AttachShader; + PFNGLBINDBUFFERPROC BindBuffer; + PFNGLBINDSAMPLERPROC BindSampler; + PFNGLBINDTEXTUREPROC BindTexture; + PFNGLBINDVERTEXARRAYPROC BindVertexArray; + PFNGLBLENDEQUATIONPROC BlendEquation; + PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate; + PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate; + PFNGLBUFFERDATAPROC BufferData; + PFNGLBUFFERSUBDATAPROC BufferSubData; + PFNGLCLEARPROC Clear; + PFNGLCLEARCOLORPROC ClearColor; + PFNGLCOMPILESHADERPROC CompileShader; + PFNGLCREATEPROGRAMPROC CreateProgram; + PFNGLCREATESHADERPROC CreateShader; + PFNGLDELETEBUFFERSPROC DeleteBuffers; + PFNGLDELETEPROGRAMPROC DeleteProgram; + PFNGLDELETESAMPLERSPROC DeleteSamplers; + PFNGLDELETESHADERPROC DeleteShader; + PFNGLDELETETEXTURESPROC DeleteTextures; + PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays; + PFNGLDETACHSHADERPROC DetachShader; + PFNGLDISABLEPROC Disable; + PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray; + PFNGLDRAWELEMENTSPROC DrawElements; + PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex; + PFNGLENABLEPROC Enable; + PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray; + PFNGLFLUSHPROC Flush; + PFNGLGENBUFFERSPROC GenBuffers; + PFNGLGENSAMPLERSPROC GenSamplers; + PFNGLGENTEXTURESPROC GenTextures; + PFNGLGENVERTEXARRAYSPROC GenVertexArrays; + PFNGLGETATTRIBLOCATIONPROC GetAttribLocation; + PFNGLGETERRORPROC GetError; + PFNGLGETINTEGERVPROC GetIntegerv; + PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog; + PFNGLGETPROGRAMIVPROC GetProgramiv; + PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog; + PFNGLGETSHADERIVPROC GetShaderiv; + PFNGLGETSTRINGPROC GetString; + PFNGLGETSTRINGIPROC GetStringi; + PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation; + PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv; + PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv; + PFNGLISENABLEDPROC IsEnabled; + PFNGLISPROGRAMPROC IsProgram; + PFNGLLINKPROGRAMPROC LinkProgram; + PFNGLPIXELSTOREIPROC PixelStorei; + PFNGLPOLYGONMODEPROC PolygonMode; + PFNGLREADPIXELSPROC ReadPixels; + PFNGLSAMPLERPARAMETERIPROC SamplerParameteri; + PFNGLSCISSORPROC Scissor; + PFNGLSHADERSOURCEPROC ShaderSource; + PFNGLTEXIMAGE2DPROC TexImage2D; + PFNGLTEXPARAMETERIPROC TexParameteri; + PFNGLTEXSUBIMAGE2DPROC TexSubImage2D; + PFNGLUNIFORM1IPROC Uniform1i; + PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; + PFNGLUSEPROGRAMPROC UseProgram; + PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer; + PFNGLVIEWPORTPROC Viewport; + } gl; +}; + +GL3W_API extern union ImGL3WProcs imgl3wProcs; + +/* OpenGL functions */ +#define glActiveTexture imgl3wProcs.gl.ActiveTexture +#define glAttachShader imgl3wProcs.gl.AttachShader +#define glBindBuffer imgl3wProcs.gl.BindBuffer +#define glBindSampler imgl3wProcs.gl.BindSampler +#define glBindTexture imgl3wProcs.gl.BindTexture +#define glBindVertexArray imgl3wProcs.gl.BindVertexArray +#define glBlendEquation imgl3wProcs.gl.BlendEquation +#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate +#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate +#define glBufferData imgl3wProcs.gl.BufferData +#define glBufferSubData imgl3wProcs.gl.BufferSubData +#define glClear imgl3wProcs.gl.Clear +#define glClearColor imgl3wProcs.gl.ClearColor +#define glCompileShader imgl3wProcs.gl.CompileShader +#define glCreateProgram imgl3wProcs.gl.CreateProgram +#define glCreateShader imgl3wProcs.gl.CreateShader +#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers +#define glDeleteProgram imgl3wProcs.gl.DeleteProgram +#define glDeleteSamplers imgl3wProcs.gl.DeleteSamplers +#define glDeleteShader imgl3wProcs.gl.DeleteShader +#define glDeleteTextures imgl3wProcs.gl.DeleteTextures +#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays +#define glDetachShader imgl3wProcs.gl.DetachShader +#define glDisable imgl3wProcs.gl.Disable +#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray +#define glDrawElements imgl3wProcs.gl.DrawElements +#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex +#define glEnable imgl3wProcs.gl.Enable +#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray +#define glFlush imgl3wProcs.gl.Flush +#define glGenBuffers imgl3wProcs.gl.GenBuffers +#define glGenSamplers imgl3wProcs.gl.GenSamplers +#define glGenTextures imgl3wProcs.gl.GenTextures +#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays +#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation +#define glGetError imgl3wProcs.gl.GetError +#define glGetIntegerv imgl3wProcs.gl.GetIntegerv +#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog +#define glGetProgramiv imgl3wProcs.gl.GetProgramiv +#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog +#define glGetShaderiv imgl3wProcs.gl.GetShaderiv +#define glGetString imgl3wProcs.gl.GetString +#define glGetStringi imgl3wProcs.gl.GetStringi +#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation +#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv +#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv +#define glIsEnabled imgl3wProcs.gl.IsEnabled +#define glIsProgram imgl3wProcs.gl.IsProgram +#define glLinkProgram imgl3wProcs.gl.LinkProgram +#define glPixelStorei imgl3wProcs.gl.PixelStorei +#define glPolygonMode imgl3wProcs.gl.PolygonMode +#define glReadPixels imgl3wProcs.gl.ReadPixels +#define glSamplerParameteri imgl3wProcs.gl.SamplerParameteri +#define glScissor imgl3wProcs.gl.Scissor +#define glShaderSource imgl3wProcs.gl.ShaderSource +#define glTexImage2D imgl3wProcs.gl.TexImage2D +#define glTexParameteri imgl3wProcs.gl.TexParameteri +#define glTexSubImage2D imgl3wProcs.gl.TexSubImage2D +#define glUniform1i imgl3wProcs.gl.Uniform1i +#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv +#define glUseProgram imgl3wProcs.gl.UseProgram +#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer +#define glViewport imgl3wProcs.gl.Viewport + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef IMGL3W_IMPL +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include + +static HMODULE libgl = NULL; +typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR); +static GL3WglGetProcAddr wgl_get_proc_address; + +static int open_libgl(void) +{ + libgl = LoadLibraryA("opengl32.dll"); + if (!libgl) + return GL3W_ERROR_LIBRARY_OPEN; + wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress"); + return GL3W_OK; +} + +static void close_libgl(void) { FreeLibrary(libgl); libgl = NULL; } +static GL3WglProc get_proc(const char *proc) +{ + GL3WglProc res; + res = (GL3WglProc)wgl_get_proc_address(proc); + if (!res) + res = (GL3WglProc)GetProcAddress(libgl, proc); + return res; +} +#elif defined(__APPLE__) +#include + +static void *libgl = NULL; +static int open_libgl(void) +{ + libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL); + if (!libgl) + return GL3W_ERROR_LIBRARY_OPEN; + return GL3W_OK; +} + +static void close_libgl(void) { dlclose(libgl); libgl = NULL; } + +static GL3WglProc get_proc(const char *proc) +{ + GL3WglProc res; + *(void **)(&res) = dlsym(libgl, proc); + return res; +} +#else +#include + +static void* libgl; // OpenGL library +static void* libglx; // GLX library +static void* libegl; // EGL library +static GL3WGetProcAddressProc gl_get_proc_address; + +static void close_libgl(void) +{ + if (libgl) { + dlclose(libgl); + libgl = NULL; + } + if (libegl) { + dlclose(libegl); + libegl = NULL; + } + if (libglx) { + dlclose(libglx); + libglx = NULL; + } +} + +static int is_library_loaded(const char* name, void** lib) +{ +#if defined(__HAIKU__) + *lib = NULL; // no support for RTLD_NOLOAD on Haiku. +#else + *lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); +#endif + return *lib != NULL; +} + +static int open_libs(void) +{ + // On Linux we have two APIs to get process addresses: EGL and GLX. + // EGL is supported under both X11 and Wayland, whereas GLX is X11-specific. + + libgl = NULL; + libegl = NULL; + libglx = NULL; + + // First check what's already loaded, the windowing library might have + // already loaded either EGL or GLX and we want to use the same one. + + if (is_library_loaded("libEGL.so.1", &libegl) || + is_library_loaded("libGLX.so.0", &libglx)) { + libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL); + if (libgl) + return GL3W_OK; + else + close_libgl(); + } + + if (is_library_loaded("libGL.so", &libgl)) + return GL3W_OK; + if (is_library_loaded("libGL.so.1", &libgl)) + return GL3W_OK; + if (is_library_loaded("libGL.so.3", &libgl)) + return GL3W_OK; + + // Neither is already loaded, so we have to load one. Try EGL first + // because it is supported under both X11 and Wayland. + + // Load OpenGL + EGL + libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL); + libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL); + if (libgl && libegl) + return GL3W_OK; + else + close_libgl(); + + // Fall back to legacy libGL, which includes GLX + // While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983 + libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL); + if (!libgl) + libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); + if (!libgl) + libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL); + + if (libgl) + return GL3W_OK; + + return GL3W_ERROR_LIBRARY_OPEN; +} + +static int open_libgl(void) +{ + int res = open_libs(); + if (res) + return res; + + if (libegl) + *(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress"); + else if (libglx) + *(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB"); + else + *(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB"); + + if (!gl_get_proc_address) { + close_libgl(); + return GL3W_ERROR_LIBRARY_OPEN; + } + + return GL3W_OK; +} + +static GL3WglProc get_proc(const char* proc) +{ + GL3WglProc res = NULL; + + // Before EGL version 1.5, eglGetProcAddress doesn't support querying core + // functions and may return a dummy function if we try, so try to load the + // function from the GL library directly first. + if (libegl) + *(void**)(&res) = dlsym(libgl, proc); + + if (!res) + res = gl_get_proc_address(proc); + + if (!libegl && !res) + *(void**)(&res) = dlsym(libgl, proc); + + return res; +} +#endif + +static struct { int major, minor; } version; + +static int parse_version(void) +{ + if (!glGetIntegerv) + return GL3W_ERROR_INIT; + glGetIntegerv(GL_MAJOR_VERSION, &version.major); + glGetIntegerv(GL_MINOR_VERSION, &version.minor); + if (version.major == 0 && version.minor == 0) + { + // Query GL_VERSION in desktop GL 2.x, the string will start with "." + if (const char* gl_version = (const char*)glGetString(GL_VERSION)) + sscanf(gl_version, "%d.%d", &version.major, &version.minor); + } + if (version.major < 2) + return GL3W_ERROR_OPENGL_VERSION; + return GL3W_OK; +} + +static void load_procs(GL3WGetProcAddressProc proc); +static void clear_procs(); + +int imgl3wInit(void) +{ + int res = open_libgl(); + if (res) + return res; + atexit(close_libgl); + return imgl3wInit2(get_proc); +} + +int imgl3wInit2(GL3WGetProcAddressProc proc) +{ + load_procs(proc); + return parse_version(); +} + +void imgl3wShutdown(void) +{ + close_libgl(); + clear_procs(); +} + +int imgl3wIsSupported(int major, int minor) +{ + if (major < 2) + return 0; + if (version.major == major) + return version.minor >= minor; + return version.major >= major; +} + +GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); } + +static const char *proc_names[] = { + "glActiveTexture", + "glAttachShader", + "glBindBuffer", + "glBindSampler", + "glBindTexture", + "glBindVertexArray", + "glBlendEquation", + "glBlendEquationSeparate", + "glBlendFuncSeparate", + "glBufferData", + "glBufferSubData", + "glClear", + "glClearColor", + "glCompileShader", + "glCreateProgram", + "glCreateShader", + "glDeleteBuffers", + "glDeleteProgram", + "glDeleteSamplers", + "glDeleteShader", + "glDeleteTextures", + "glDeleteVertexArrays", + "glDetachShader", + "glDisable", + "glDisableVertexAttribArray", + "glDrawElements", + "glDrawElementsBaseVertex", + "glEnable", + "glEnableVertexAttribArray", + "glFlush", + "glGenBuffers", + "glGenSamplers", + "glGenTextures", + "glGenVertexArrays", + "glGetAttribLocation", + "glGetError", + "glGetIntegerv", + "glGetProgramInfoLog", + "glGetProgramiv", + "glGetShaderInfoLog", + "glGetShaderiv", + "glGetString", + "glGetStringi", + "glGetUniformLocation", + "glGetVertexAttribPointerv", + "glGetVertexAttribiv", + "glIsEnabled", + "glIsProgram", + "glLinkProgram", + "glPixelStorei", + "glPolygonMode", + "glReadPixels", + "glSamplerParameteri", + "glScissor", + "glShaderSource", + "glTexImage2D", + "glTexParameteri", + "glTexSubImage2D", + "glUniform1i", + "glUniformMatrix4fv", + "glUseProgram", + "glVertexAttribPointer", + "glViewport", +}; + +GL3W_API union ImGL3WProcs imgl3wProcs; + +static void load_procs(GL3WGetProcAddressProc proc) +{ + size_t i; + for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++) + imgl3wProcs.ptr[i] = proc(proc_names[i]); +} + +static void clear_procs() +{ + size_t i; + for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++) + imgl3wProcs.ptr[i] = nullptr; +} + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/imgui/backends/imgui_impl_sdl3.cpp b/libs/imgui/backends/imgui_impl_sdl3.cpp new file mode 100644 index 0000000..368f261 --- /dev/null +++ b/libs/imgui/backends/imgui_impl_sdl3.cpp @@ -0,0 +1,1293 @@ +// dear imgui: Platform Backend for SDL3 +// This needs to be used along with a Renderer (e.g. SDL_GPU, DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] +// [X] Platform: Gamepad support. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [x] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable' -> the OS animation effect when window gets created/destroyed is problematic. SDL2 backend doesn't have issue. +// Missing features or Issues: +// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows). +// [x] Platform: IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2026-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) +// 2025-11-05: Fixed an issue with missing characters events when an already active text field changes viewports. (#9054) +// 2025-10-22: Fixed Platform_OpenInShellFn() return value (unused in core). +// 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_EVENT_MOUSE_MOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. +// 2025-09-15: Use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) +// 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727) +// 2025-05-15: [Docking] Add Platform_GetWindowFramebufferScale() handler, to allow varying Retina display density on multiple monitors. +// 2025-05-06: [Docking] macOS: fixed secondary viewports not appearing on other monitors before of parenting. +// 2025-04-09: [Docking] Revert update monitors and work areas information every frame. Only do it on Windows. (#8415, #8558) +// 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. +// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) +// 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) +// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) +// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) +// 2025-02-25: [Docking] Revert to use SDL_GetDisplayBounds() for WorkPos/WorkRect if SDL_GetDisplayUsableBounds() failed. +// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. +// 2025-02-21: [Docking] Update monitors and work areas information every frame, as the later may change regardless of monitor changes. (#8415) +// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. +// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. +// 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. +// 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. +// 2024-09-11: (Docking) Added support for viewport->ParentViewportId field to support parenting at OS level. (#7973) +// 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn +// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn +// 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. +// 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) +// 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) +// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) +// 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) +// 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). +// 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). +// 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. +// 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. +// 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames. +// 2024-05-15: Update for SDL3 api changes: SDLK_ renames. +// 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME. +// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode(). +// 2023-11-13: Updated for recent SDL3 API changes. +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. +// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391) +// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) +// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) +// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdl3.h" + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif + +// SDL +#include +#include // for snprintf() +#if defined(__APPLE__) +#include +#endif +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + +#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 +#else +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 +#endif + +// FIXME-LEGACY: remove when SDL 3.1.3 preview is released. +#ifndef SDLK_APOSTROPHE +#define SDLK_APOSTROPHE SDLK_QUOTE +#endif +#ifndef SDLK_GRAVE +#define SDLK_GRAVE SDLK_BACKQUOTE +#endif + +// SDL Data +struct ImGui_ImplSDL3_Data +{ + SDL_Window* Window; + SDL_WindowID WindowID; + SDL_Renderer* Renderer; + Uint64 Time; + char* ClipboardTextData; + char BackendPlatformName[48]; + bool UseVulkan; + bool WantUpdateMonitors; + + // IME handling + SDL_Window* ImeWindow; + ImGuiPlatformImeData ImeData; + bool ImeDirty; + + // Mouse handling + Uint32 MouseWindowID; + int MouseButtonsDown; + SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; + SDL_Cursor* MouseLastCursor; + int MousePendingLeaveFrame; + bool MouseCanUseGlobalState; + bool MouseCanUseCapture; + bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state. + + // Gamepad handling + ImVector Gamepads; + ImGui_ImplSDL3_GamepadMode GamepadMode; + bool WantUpdateGamepadsList; + + ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; +} + +// Forward Declarations +static void ImGui_ImplSDL3_UpdateIme(); +static void ImGui_ImplSDL3_UpdateMonitors(); +static void ImGui_ImplSDL3_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context); +static void ImGui_ImplSDL3_ShutdownMultiViewportSupport(); + +// Functions +static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + if (SDL_HasClipboardText()) + bd->ClipboardTextData = SDL_GetClipboardText(); + else + bd->ClipboardTextData = nullptr; + return bd->ClipboardTextData; +} + +static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text) +{ + SDL_SetClipboardText(text); +} + +static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) +{ + return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id); +} + +static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + bd->ImeData = *data; + bd->ImeDirty = true; + ImGui_ImplSDL3_UpdateIme(); +} + +// We discard viewport passed via ImGuiPlatformImeData and always call SDL_StartTextInput() on SDL_GetKeyboardFocus(). +static void ImGui_ImplSDL3_UpdateIme() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiPlatformImeData* data = &bd->ImeData; + SDL_Window* window = SDL_GetKeyboardFocus(); + + // Stop previous input + if ((!(data->WantVisible || data->WantTextInput) || bd->ImeWindow != window) && bd->ImeWindow != nullptr) + { + SDL_StopTextInput(bd->ImeWindow); + bd->ImeWindow = nullptr; + } + if ((!bd->ImeDirty && bd->ImeWindow == window) || (window == nullptr)) + return; + + // Start/update current input + bd->ImeDirty = false; + if (data->WantVisible) + { + ImVec2 viewport_pos; + if (ImGuiViewport* viewport = ImGui_ImplSDL3_GetViewportForWindowID(SDL_GetWindowID(window))) + viewport_pos = viewport->Pos; + SDL_Rect r; + r.x = (int)(data->InputPos.x - viewport_pos.x); + r.y = (int)(data->InputPos.y - viewport_pos.y); + r.w = 1; + r.h = (int)data->InputLineHeight; + SDL_SetTextInputArea(window, &r, 0); + bd->ImeWindow = window; + } + if (!SDL_TextInputActive(window) && (data->WantVisible || data->WantTextInput)) + SDL_StartTextInput(window); +} + +// Not static to allow third-party code to use that if they want to (but undocumented) +ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode); +ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) +{ + // Keypad doesn't have individual key values in SDL3 + switch (scancode) + { + case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0; + case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1; + case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2; + case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3; + case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4; + case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5; + case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6; + case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7; + case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8; + case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9; + case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal; + case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract; + case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd; + case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter; + case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual; + default: break; + } + switch (keycode) + { + case SDLK_TAB: return ImGuiKey_Tab; + case SDLK_LEFT: return ImGuiKey_LeftArrow; + case SDLK_RIGHT: return ImGuiKey_RightArrow; + case SDLK_UP: return ImGuiKey_UpArrow; + case SDLK_DOWN: return ImGuiKey_DownArrow; + case SDLK_PAGEUP: return ImGuiKey_PageUp; + case SDLK_PAGEDOWN: return ImGuiKey_PageDown; + case SDLK_HOME: return ImGuiKey_Home; + case SDLK_END: return ImGuiKey_End; + case SDLK_INSERT: return ImGuiKey_Insert; + case SDLK_DELETE: return ImGuiKey_Delete; + case SDLK_BACKSPACE: return ImGuiKey_Backspace; + case SDLK_SPACE: return ImGuiKey_Space; + case SDLK_RETURN: return ImGuiKey_Enter; + case SDLK_ESCAPE: return ImGuiKey_Escape; + //case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; + case SDLK_COMMA: return ImGuiKey_Comma; + //case SDLK_MINUS: return ImGuiKey_Minus; + case SDLK_PERIOD: return ImGuiKey_Period; + //case SDLK_SLASH: return ImGuiKey_Slash; + case SDLK_SEMICOLON: return ImGuiKey_Semicolon; + //case SDLK_EQUALS: return ImGuiKey_Equal; + //case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + //case SDLK_BACKSLASH: return ImGuiKey_Backslash; + //case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + //case SDLK_GRAVE: return ImGuiKey_GraveAccent; + case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; + case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; + case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; + case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; + case SDLK_PAUSE: return ImGuiKey_Pause; + case SDLK_LCTRL: return ImGuiKey_LeftCtrl; + case SDLK_LSHIFT: return ImGuiKey_LeftShift; + case SDLK_LALT: return ImGuiKey_LeftAlt; + case SDLK_LGUI: return ImGuiKey_LeftSuper; + case SDLK_RCTRL: return ImGuiKey_RightCtrl; + case SDLK_RSHIFT: return ImGuiKey_RightShift; + case SDLK_RALT: return ImGuiKey_RightAlt; + case SDLK_RGUI: return ImGuiKey_RightSuper; + case SDLK_APPLICATION: return ImGuiKey_Menu; + case SDLK_0: return ImGuiKey_0; + case SDLK_1: return ImGuiKey_1; + case SDLK_2: return ImGuiKey_2; + case SDLK_3: return ImGuiKey_3; + case SDLK_4: return ImGuiKey_4; + case SDLK_5: return ImGuiKey_5; + case SDLK_6: return ImGuiKey_6; + case SDLK_7: return ImGuiKey_7; + case SDLK_8: return ImGuiKey_8; + case SDLK_9: return ImGuiKey_9; + case SDLK_A: return ImGuiKey_A; + case SDLK_B: return ImGuiKey_B; + case SDLK_C: return ImGuiKey_C; + case SDLK_D: return ImGuiKey_D; + case SDLK_E: return ImGuiKey_E; + case SDLK_F: return ImGuiKey_F; + case SDLK_G: return ImGuiKey_G; + case SDLK_H: return ImGuiKey_H; + case SDLK_I: return ImGuiKey_I; + case SDLK_J: return ImGuiKey_J; + case SDLK_K: return ImGuiKey_K; + case SDLK_L: return ImGuiKey_L; + case SDLK_M: return ImGuiKey_M; + case SDLK_N: return ImGuiKey_N; + case SDLK_O: return ImGuiKey_O; + case SDLK_P: return ImGuiKey_P; + case SDLK_Q: return ImGuiKey_Q; + case SDLK_R: return ImGuiKey_R; + case SDLK_S: return ImGuiKey_S; + case SDLK_T: return ImGuiKey_T; + case SDLK_U: return ImGuiKey_U; + case SDLK_V: return ImGuiKey_V; + case SDLK_W: return ImGuiKey_W; + case SDLK_X: return ImGuiKey_X; + case SDLK_Y: return ImGuiKey_Y; + case SDLK_Z: return ImGuiKey_Z; + case SDLK_F1: return ImGuiKey_F1; + case SDLK_F2: return ImGuiKey_F2; + case SDLK_F3: return ImGuiKey_F3; + case SDLK_F4: return ImGuiKey_F4; + case SDLK_F5: return ImGuiKey_F5; + case SDLK_F6: return ImGuiKey_F6; + case SDLK_F7: return ImGuiKey_F7; + case SDLK_F8: return ImGuiKey_F8; + case SDLK_F9: return ImGuiKey_F9; + case SDLK_F10: return ImGuiKey_F10; + case SDLK_F11: return ImGuiKey_F11; + case SDLK_F12: return ImGuiKey_F12; + case SDLK_F13: return ImGuiKey_F13; + case SDLK_F14: return ImGuiKey_F14; + case SDLK_F15: return ImGuiKey_F15; + case SDLK_F16: return ImGuiKey_F16; + case SDLK_F17: return ImGuiKey_F17; + case SDLK_F18: return ImGuiKey_F18; + case SDLK_F19: return ImGuiKey_F19; + case SDLK_F20: return ImGuiKey_F20; + case SDLK_F21: return ImGuiKey_F21; + case SDLK_F22: return ImGuiKey_F22; + case SDLK_F23: return ImGuiKey_F23; + case SDLK_F24: return ImGuiKey_F24; + case SDLK_AC_BACK: return ImGuiKey_AppBack; + case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + default: break; + } + + // Fallback to scancode + switch (scancode) + { + case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent; + case SDL_SCANCODE_MINUS: return ImGuiKey_Minus; + case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal; + case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102; + case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash; + case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon; + case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe; + case SDL_SCANCODE_COMMA: return ImGuiKey_Comma; + case SDL_SCANCODE_PERIOD: return ImGuiKey_Period; + case SDL_SCANCODE_SLASH: return ImGuiKey_Slash; + default: break; + } + return ImGuiKey_None; +} + +static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0); + io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); +} + +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + switch (event->type) + { + case SDL_EVENT_MOUSE_MOTION: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr) + return false; + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + int window_x, window_y; + SDL_GetWindowPosition(SDL_GetWindowFromID(event->motion.windowID), &window_x, &window_y); + mouse_pos.x += window_x; + mouse_pos.y += window_y; + } + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); + return true; + } + case SDL_EVENT_MOUSE_WHEEL: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr) + return false; + //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); + float wheel_x = -event->wheel.x; + float wheel_y = event->wheel.y; + io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseWheelEvent(wheel_x, wheel_y); + return true; + } + case SDL_EVENT_MOUSE_BUTTON_DOWN: + case SDL_EVENT_MOUSE_BUTTON_UP: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr) + return false; + int mouse_button = -1; + if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } + if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } + if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } + if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } + if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } + if (mouse_button == -1) + break; + io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN)); + bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); + return true; + } + case SDL_EVENT_TEXT_INPUT: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr) + return false; + io.AddInputCharactersUTF8(event->text.text); + return true; + } + case SDL_EVENT_KEY_DOWN: + case SDL_EVENT_KEY_UP: + { + ImGuiViewport* viewport = ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID); + if (viewport == nullptr) + return false; + //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%s : key=0x%08X ('%s'), scancode=%d ('%s'), mod=%X, windowID=%d, viewport=%08X\n", + // (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP ", event->key.key, SDL_GetKeyName(event->key.key), event->key.scancode, SDL_GetScancodeName(event->key.scancode), event->key.mod, event->key.windowID, viewport ? viewport->ID : 0); + ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); + ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); + io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); + io.SetKeyEventNativeData(key, (int)event->key.key, (int)event->key.scancode, (int)event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + return true; + } + case SDL_EVENT_DISPLAY_ORIENTATION: + case SDL_EVENT_DISPLAY_ADDED: + case SDL_EVENT_DISPLAY_REMOVED: + case SDL_EVENT_DISPLAY_MOVED: + case SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED: + { + bd->WantUpdateMonitors = true; + return true; + } + case SDL_EVENT_WINDOW_MOUSE_ENTER: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MouseWindowID = event->window.windowID; + bd->MousePendingLeaveFrame = 0; + return true; + } + // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, + // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why + // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. + // FIXME: Unconfirmed whether this is still needed with SDL3. + case SDL_EVENT_WINDOW_MOUSE_LEAVE: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; + return true; + } + case SDL_EVENT_WINDOW_FOCUS_GAINED: + case SDL_EVENT_WINDOW_FOCUS_LOST: + { + ImGuiViewport* viewport = ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID); + if (viewport == nullptr) + return false; + //IMGUI_DEBUG_LOG("%s: windowId %d, viewport: %08X\n", (event->type == SDL_EVENT_WINDOW_FOCUS_GAINED) ? "SDL_EVENT_WINDOW_FOCUS_GAINED" : "SDL_WINDOWEVENT_FOCUS_LOST", event->window.windowID, viewport ? viewport->ID : 0); + io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED); + return true; + } + case SDL_EVENT_WINDOW_CLOSE_REQUESTED: + case SDL_EVENT_WINDOW_MOVED: + case SDL_EVENT_WINDOW_RESIZED: + { + ImGuiViewport* viewport = ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID); + if (viewport == NULL) + return false; + if (event->type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) + viewport->PlatformRequestClose = true; + if (event->type == SDL_EVENT_WINDOW_MOVED) + viewport->PlatformRequestMove = true; + if (event->type == SDL_EVENT_WINDOW_RESIZED) + viewport->PlatformRequestResize = true; + return true; + } + case SDL_EVENT_GAMEPAD_ADDED: + case SDL_EVENT_GAMEPAD_REMOVED: + { + bd->WantUpdateGamepadsList = true; + return true; + } + default: + break; + } + return false; +} + +static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) +{ + viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window); + viewport->PlatformHandleRaw = nullptr; +#if defined(_WIN32) && !defined(__WINRT__) + viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); +#elif defined(__APPLE__) + viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); +#endif +} + +static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + IM_UNUSED(sdl_gl_context); // Unused in this branch + //SDL_SetHint(SDL_HINT_EVENT_LOGGING, "2"); + + const int ver_linked = SDL_GetVersion(); + + // Setup backend capabilities flags + ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl3 (%d.%d.%d; %d.%d.%d)", + SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION, SDL_VERSIONNUM_MAJOR(ver_linked), SDL_VERSIONNUM_MINOR(ver_linked), SDL_VERSIONNUM_MICRO(ver_linked)); + io.BackendPlatformUserData = (void*)bd; + io.BackendPlatformName = bd->BackendPlatformName; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + // (ImGuiBackendFlags_PlatformHasViewports and ImGuiBackendFlags_HasParentViewport may be set just below) + // (ImGuiBackendFlags_HasMouseHoveredViewport is set dynamically in our _NewFrame function) + + bd->Window = window; + bd->WindowID = SDL_GetWindowID(window); + bd->Renderer = renderer; + + // SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960) + // We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame. +#ifndef __APPLE__ + bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState; +#else + bd->MouseCanReportHoveredViewport = false; +#endif + + // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse() + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bd->MouseCanUseGlobalState = false; + bd->MouseCanUseCapture = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (const char* item : capture_and_global_state_whitelist) + if (strncmp(sdl_backend, item, strlen(item)) == 0) + bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true; +#endif + if (bd->MouseCanUseGlobalState) + { + io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) + io.BackendFlags |= ImGuiBackendFlags_HasParentViewport; // We can honor viewport->ParentViewportId by applying the corresponding parent/child relationship at platform level (optional) + } + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; + platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; + platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url); }; + + // Update monitor a first time during init + ImGui_ImplSDL3_UpdateMonitors(); + + // Gamepad handling + bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; + bd->WantUpdateGamepadsList = true; + + // Load mouse cursors + bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT); + bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); + bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT); + bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_PROGRESS); + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); + + // Set platform dependent data in viewport + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window); + + // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. + // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. + // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. + // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: + // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_EVENT_WINDOW_FOCUS_GAINED) + SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); + + // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) + SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); + + // SDL 3.x : see https://github.com/libsdl-org/SDL/issues/6659 + SDL_SetHint("SDL_BORDERLESS_WINDOWED_STYLE", "0"); + + // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports. + // We left the call to ImGui_ImplSDL3_InitPlatformInterface() outside of #ifdef to avoid unused-function warnings. + if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) + ImGui_ImplSDL3_InitMultiViewportSupport(window, sdl_gl_context); + + return true; +} + +// Should technically be a SDL_GLContext but due to typedef it is sane to keep it void* in public interface. +bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) +{ + return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context); +} + +bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window) +{ + if (!ImGui_ImplSDL3_Init(window, nullptr, nullptr)) + return false; + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + bd->UseVulkan = true; + return true; +} + +bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window) +{ +#if !defined(_WIN32) + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) +{ + return ImGui_ImplSDL3_Init(window, renderer, nullptr); +} + +bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForOther(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +static void ImGui_ImplSDL3_CloseGamepads(); + +void ImGui_ImplSDL3_Shutdown() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + + ImGui_ImplSDL3_ShutdownMultiViewportSupport(); + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) + SDL_DestroyCursor(bd->MouseCursors[cursor_n]); + ImGui_ImplSDL3_CloseGamepads(); + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport | ImGuiBackendFlags_HasParentViewport); + platform_io.ClearPlatformHandlers(); + IM_DELETE(bd); +} + +// This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4. +static void ImGui_ImplSDL3_UpdateMouseData() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + + // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture. + if (bd->MouseCanUseCapture) + { + bool want_capture = false; + for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) + if (ImGui::IsMouseDragging(button_n, 1.0f)) + want_capture = true; + SDL_CaptureMouse(want_capture); + } + + SDL_Window* focused_window = SDL_GetKeyboardFocus(); + const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL3_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL)); +#else + SDL_Window* focused_window = bd->Window; + const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only +#endif + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user) + if (io.WantSetMousePos) + { +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + SDL_WarpMouseGlobal(io.MousePos.x, io.MousePos.y); + else +#endif + SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); + } + + // (Optional) Fallback to provide unclamped mouse position when focused but not hovered (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + // Note that SDL_GetGlobalMouseState() is in theory slow on X11, but this only runs on rather specific cases. If a problem we may provide a way to opt-out this feature. + SDL_Window* hovered_window = SDL_GetMouseFocus(); + const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); + if (hovered_window == nullptr && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) + { + // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) + float mouse_x, mouse_y; + int window_x, window_y; + SDL_GetGlobalMouseState(&mouse_x, &mouse_y); + if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)) + { + SDL_GetWindowPosition(focused_window, &window_x, &window_y); + mouse_x -= window_x; + mouse_y -= window_y; + } + io.AddMousePosEvent(mouse_x, mouse_y); + } + } + + // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering. + // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic. + // - [!] SDL backend does NOT correctly ignore viewports with the _NoInputs flag. + // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window + // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported + // by the backend, and use its flawed heuristic to guess the viewport behind. + // - [X] SDL backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target). + if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) + { + ImGuiID mouse_viewport_id = 0; + if (ImGuiViewport* mouse_viewport = ImGui_ImplSDL3_GetViewportForWindowID(bd->MouseWindowID)) + mouse_viewport_id = mouse_viewport->ID; + io.AddMouseViewportEvent(mouse_viewport_id); + } +} + +static void ImGui_ImplSDL3_UpdateMouseCursor() +{ + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return; + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + SDL_HideCursor(); + } + else + { + // Show OS mouse cursor + SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; + if (bd->MouseLastCursor != expected_cursor) + { + SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) + bd->MouseLastCursor = expected_cursor; + } + SDL_ShowCursor(); + } +} + +static void ImGui_ImplSDL3_CloseGamepads() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + for (SDL_Gamepad* gamepad : bd->Gamepads) + SDL_CloseGamepad(gamepad); + bd->Gamepads.resize(0); +} + +void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGui_ImplSDL3_CloseGamepads(); + if (mode == ImGui_ImplSDL3_GamepadMode_Manual) + { + IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0); + for (int n = 0; n < manual_gamepads_count; n++) + bd->Gamepads.push_back(manual_gamepads_array[n]); + } + else + { + IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); + bd->WantUpdateGamepadsList = true; + } + bd->GamepadMode = mode; +} + +static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no) +{ + bool merged_value = false; + for (SDL_Gamepad* gamepad : bd->Gamepads) + merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0; + io.AddKeyEvent(key, merged_value); +} + +static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } +static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1) +{ + float merged_value = 0.0f; + for (SDL_Gamepad* gamepad : bd->Gamepads) + { + float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); + if (merged_value < vn) + merged_value = vn; + } + io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); +} + +static void ImGui_ImplSDL3_UpdateGamepads() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + // Update list of gamepads to use + if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + { + ImGui_ImplSDL3_CloseGamepads(); + int sdl_gamepads_count = 0; + SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); + for (int n = 0; n < sdl_gamepads_count; n++) + if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) + { + bd->Gamepads.push_back(gamepad); + if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst) + break; + } + bd->WantUpdateGamepadsList = false; + SDL_free(sdl_gamepads); + } + + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + if (bd->Gamepads.Size == 0) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + + // Update gamepad inputs + const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value. + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767); +} + +static void ImGui_ImplSDL3_UpdateMonitors() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Monitors.resize(0); + bd->WantUpdateMonitors = false; + + int display_count; + SDL_DisplayID* displays = SDL_GetDisplays(&display_count); + for (int n = 0; n < display_count; n++) + { + // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime. + SDL_DisplayID display_id = displays[n]; + ImGuiPlatformMonitor monitor; + SDL_Rect r; + SDL_GetDisplayBounds(display_id, &r); + monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y); + monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h); + if (SDL_GetDisplayUsableBounds(display_id, &r) && r.w > 0 && r.h > 0) + { + monitor.WorkPos = ImVec2((float)r.x, (float)r.y); + monitor.WorkSize = ImVec2((float)r.w, (float)r.h); + } + monitor.DpiScale = SDL_GetDisplayContentScale(display_id); // See https://wiki.libsdl.org/SDL3/README-highdpi for details. + monitor.PlatformHandle = (void*)(intptr_t)n; + if (monitor.DpiScale <= 0.0f) + continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902. + platform_io.Monitors.push_back(monitor); + } + SDL_free(displays); +} + +static void ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(SDL_Window* window, ImVec2* out_size, ImVec2* out_framebuffer_scale) +{ + int w, h; + SDL_GetWindowSize(window, &w, &h); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + +#if defined(__APPLE__) + float fb_scale_x = SDL_GetWindowDisplayScale(window); // Seems more reliable during resolution change (#8703) + float fb_scale_y = fb_scale_x; +#else + int display_w, display_h; + SDL_GetWindowSizeInPixels(window, &display_w, &display_h); + float fb_scale_x = (w > 0) ? (float)display_w / (float)w : 1.0f; + float fb_scale_y = (h > 0) ? (float)display_h / (float)h : 1.0f; +#endif + + if (out_size != nullptr) + *out_size = ImVec2((float)w, (float)h); + if (out_framebuffer_scale != nullptr) + *out_framebuffer_scale = ImVec2(fb_scale_x, fb_scale_y); +} + +void ImGui_ImplSDL3_NewFrame() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + // Setup main viewport size (every frame to accommodate for window resizing) + ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale); + + // Update monitors +#ifdef WIN32 + bd->WantUpdateMonitors = true; // Keep polling under Windows to handle changes of work area when resizing task-bar (#8415) +#endif + if (bd->WantUpdateMonitors) + ImGui_ImplSDL3_UpdateMonitors(); + + // Setup time step (we could also use SDL_GetTicksNS() available since SDL3) + // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) + static Uint64 frequency = SDL_GetPerformanceFrequency(); + Uint64 current_time = SDL_GetPerformanceCounter(); + if (current_time <= bd->Time) + current_time = bd->Time + 1; + io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); + bd->Time = current_time; + + if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) + { + bd->MouseWindowID = 0; + bd->MousePendingLeaveFrame = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } + + // Our io.AddMouseViewportEvent() calls will only be valid when not capturing. + // Technically speaking testing for 'bd->MouseButtonsDown == 0' would be more rigorous, but testing for payload reduces noise and potential side-effects. + if (bd->MouseCanReportHoveredViewport && ImGui::GetDragDropPayload() == nullptr) + io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; + else + io.BackendFlags &= ~ImGuiBackendFlags_HasMouseHoveredViewport; + + ImGui_ImplSDL3_UpdateMouseData(); + ImGui_ImplSDL3_UpdateMouseCursor(); + ImGui_ImplSDL3_UpdateIme(); + + // Update game controllers (if enabled and available) + ImGui_ImplSDL3_UpdateGamepads(); +} + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +// Helper structure we store in the void* PlatformUserData field of each ImGuiViewport to easily retrieve our backend data. +struct ImGui_ImplSDL3_ViewportData +{ + SDL_Window* Window; + SDL_Window* ParentWindow; + Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID. + bool WindowOwned; + SDL_GLContext GLContext; + + ImGui_ImplSDL3_ViewportData() { Window = ParentWindow = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; } + ~ImGui_ImplSDL3_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); } +}; + +static SDL_Window* ImGui_ImplSDL3_GetSDLWindowFromViewport(ImGuiViewport* viewport) +{ + if (viewport != nullptr) + { + SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; + return SDL_GetWindowFromID(window_id); + } + return nullptr; +} + +static void ImGui_ImplSDL3_CreateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGui_ImplSDL3_ViewportData* vd = IM_NEW(ImGui_ImplSDL3_ViewportData)(); + viewport->PlatformUserData = vd; + + vd->ParentWindow = ImGui_ImplSDL3_GetSDLWindowFromViewport(viewport->ParentViewport); + + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplSDL3_ViewportData* main_viewport_data = (ImGui_ImplSDL3_ViewportData*)main_viewport->PlatformUserData; + + // Share GL resources with main context + bool use_opengl = (main_viewport_data->GLContext != nullptr); + SDL_GLContext backup_context = nullptr; + if (use_opengl) + { + backup_context = SDL_GL_GetCurrentContext(); + SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); + SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext); + } + + SDL_WindowFlags sdl_flags = 0; + sdl_flags |= SDL_WINDOW_HIDDEN; + sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : (bd->UseVulkan ? SDL_WINDOW_VULKAN : 0); + sdl_flags |= SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_HIGH_PIXEL_DENSITY; + sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0; + sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE; + sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_UTILITY : 0; + sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0; + vd->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags); +#ifndef __APPLE__ // On Mac, SDL3 Parenting appears to prevent viewport from appearing in another monitor + SDL_SetWindowParent(vd->Window, vd->ParentWindow); +#endif + SDL_SetWindowPosition(vd->Window, (int)viewport->Pos.x, (int)viewport->Pos.y); + vd->WindowOwned = true; + if (use_opengl) + { + vd->GLContext = SDL_GL_CreateContext(vd->Window); + SDL_GL_SetSwapInterval(0); + } + if (use_opengl && backup_context) + SDL_GL_MakeCurrent(vd->Window, backup_context); + + ImGui_ImplSDL3_SetupPlatformHandles(viewport, vd->Window); +} + +static void ImGui_ImplSDL3_DestroyWindow(ImGuiViewport* viewport) +{ + if (ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData) + { + if (vd->GLContext && vd->WindowOwned) + SDL_GL_DestroyContext(vd->GLContext); + if (vd->Window && vd->WindowOwned) + SDL_DestroyWindow(vd->Window); + vd->GLContext = nullptr; + vd->Window = nullptr; + IM_DELETE(vd); + } + viewport->PlatformUserData = viewport->PlatformHandle = nullptr; +} + +static void ImGui_ImplSDL3_ShowWindow(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; +#if defined(_WIN32) && !(defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))) + HWND hwnd = (HWND)viewport->PlatformHandleRaw; + + // SDL hack: Show icon in task bar (#7989) + // Note: SDL_WINDOW_UTILITY can be used to control task bar visibility, but on Windows, it does not affect child windows. + if (!(viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)) + { + LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); + ex_style |= WS_EX_APPWINDOW; + ex_style &= ~WS_EX_TOOLWINDOW; + ::ShowWindow(hwnd, SW_HIDE); + ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); + } +#endif + +#ifdef __APPLE__ + SDL_SetHint(SDL_HINT_WINDOW_ACTIVATE_WHEN_SHOWN, "1"); // Otherwise new window appear under +#else + SDL_SetHint(SDL_HINT_WINDOW_ACTIVATE_WHEN_SHOWN, (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ? "0" : "1"); +#endif + SDL_ShowWindow(vd->Window); +} + +static void ImGui_ImplSDL3_UpdateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + IM_UNUSED(vd); + +#ifndef __APPLE__ // On Mac, SDL3 Parenting appears to prevent viewport from appearing in another monitor + // Update SDL3 parent if it changed _after_ creation. + // This is for advanced apps that are manipulating ParentViewportID manually. + SDL_Window* new_parent = ImGui_ImplSDL3_GetSDLWindowFromViewport(viewport->ParentViewport); + if (new_parent != vd->ParentWindow) + { + vd->ParentWindow = new_parent; + SDL_SetWindowParent(vd->Window, vd->ParentWindow); + } +#endif +} + +static ImVec2 ImGui_ImplSDL3_GetWindowPos(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + int x = 0, y = 0; + SDL_GetWindowPosition(vd->Window, &x, &y); + return ImVec2((float)x, (float)y); +} + +static void ImGui_ImplSDL3_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + SDL_SetWindowPosition(vd->Window, (int)pos.x, (int)pos.y); +} + +static ImVec2 ImGui_ImplSDL3_GetWindowSize(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + int w = 0, h = 0; + SDL_GetWindowSize(vd->Window, &w, &h); + return ImVec2((float)w, (float)h); +} + +static void ImGui_ImplSDL3_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y); +} + +static ImVec2 ImGui_ImplSDL3_GetWindowFramebufferScale(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + ImVec2 framebuffer_scale; + ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(vd->Window, nullptr, &framebuffer_scale); + return framebuffer_scale; +} + +static void ImGui_ImplSDL3_SetWindowTitle(ImGuiViewport* viewport, const char* title) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + SDL_SetWindowTitle(vd->Window, title); +} + +static void ImGui_ImplSDL3_SetWindowAlpha(ImGuiViewport* viewport, float alpha) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + SDL_SetWindowOpacity(vd->Window, alpha); +} + +static void ImGui_ImplSDL3_SetWindowFocus(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + SDL_RaiseWindow(vd->Window); +} + +static bool ImGui_ImplSDL3_GetWindowFocus(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; +} + +static bool ImGui_ImplSDL3_GetWindowMinimized(ImGuiViewport* viewport) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_MINIMIZED) != 0; +} + +static void ImGui_ImplSDL3_RenderWindow(ImGuiViewport* viewport, void*) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + if (vd->GLContext) + SDL_GL_MakeCurrent(vd->Window, vd->GLContext); +} + +static void ImGui_ImplSDL3_SwapBuffers(ImGuiViewport* viewport, void*) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + if (vd->GLContext) + { + SDL_GL_MakeCurrent(vd->Window, vd->GLContext); + SDL_GL_SwapWindow(vd->Window); + } +} + +// Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface) +// SDL is graceful enough to _not_ need so we can safely include this. +#include +static int ImGui_ImplSDL3_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface) +{ + ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData; + (void)vk_allocator; + bool ret = SDL_Vulkan_CreateSurface(vd->Window, (VkInstance)vk_instance, (const VkAllocationCallbacks*)vk_allocator, (VkSurfaceKHR*)out_vk_surface); + return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY +} + +static void ImGui_ImplSDL3_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context) +{ + // Register platform interface (will be coupled with a renderer interface) + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_CreateWindow = ImGui_ImplSDL3_CreateWindow; + platform_io.Platform_DestroyWindow = ImGui_ImplSDL3_DestroyWindow; + platform_io.Platform_ShowWindow = ImGui_ImplSDL3_ShowWindow; + platform_io.Platform_UpdateWindow = ImGui_ImplSDL3_UpdateWindow; + platform_io.Platform_SetWindowPos = ImGui_ImplSDL3_SetWindowPos; + platform_io.Platform_GetWindowPos = ImGui_ImplSDL3_GetWindowPos; + platform_io.Platform_SetWindowSize = ImGui_ImplSDL3_SetWindowSize; + platform_io.Platform_GetWindowSize = ImGui_ImplSDL3_GetWindowSize; + platform_io.Platform_GetWindowFramebufferScale = ImGui_ImplSDL3_GetWindowFramebufferScale; + platform_io.Platform_SetWindowFocus = ImGui_ImplSDL3_SetWindowFocus; + platform_io.Platform_GetWindowFocus = ImGui_ImplSDL3_GetWindowFocus; + platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL3_GetWindowMinimized; + platform_io.Platform_SetWindowTitle = ImGui_ImplSDL3_SetWindowTitle; + platform_io.Platform_RenderWindow = ImGui_ImplSDL3_RenderWindow; + platform_io.Platform_SwapBuffers = ImGui_ImplSDL3_SwapBuffers; + platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL3_SetWindowAlpha; + platform_io.Platform_CreateVkSurface = ImGui_ImplSDL3_CreateVkSurface; + + // Register main window handle (which is owned by the main application, not by us) + // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplSDL3_ViewportData* vd = IM_NEW(ImGui_ImplSDL3_ViewportData)(); + vd->Window = window; + vd->WindowID = SDL_GetWindowID(window); + vd->WindowOwned = false; + vd->GLContext = (SDL_GLContext)sdl_gl_context; + main_viewport->PlatformUserData = vd; + main_viewport->PlatformHandle = (void*)(intptr_t)vd->WindowID; +} + +static void ImGui_ImplSDL3_ShutdownMultiViewportSupport() +{ + ImGui::DestroyPlatformWindows(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/backends/imgui_impl_sdl3.h b/libs/imgui/backends/imgui_impl_sdl3.h new file mode 100644 index 0000000..31f43aa --- /dev/null +++ b/libs/imgui/backends/imgui_impl_sdl3.h @@ -0,0 +1,50 @@ +// dear imgui: Platform Backend for SDL3 +// This needs to be used along with a Renderer (e.g. SDL_GPU, DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] +// [X] Platform: Gamepad support. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [x] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable' -> the OS animation effect when window gets created/destroyed is problematic. SDL2 backend doesn't have issue. +// Missing features or Issues: +// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows). +// [x] Platform: IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Window; +struct SDL_Renderer; +struct SDL_Gamepad; +typedef union SDL_Event SDL_Event; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window); +IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); +IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); + +// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. +// When using manual mode, caller is responsible for opening/closing gamepad. +enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; +IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1); + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imconfig.h b/libs/imgui/imconfig.h new file mode 100644 index 0000000..322e5b8 --- /dev/null +++ b/libs/imgui/imconfig.h @@ -0,0 +1,147 @@ +//----------------------------------------------------------------------------- +// DEAR IMGUI COMPILE-TIME OPTIONS +// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. +// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. +//----------------------------------------------------------------------------- +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) +// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. +//----------------------------------------------------------------------------- +// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp +// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. +// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. +// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using. +//----------------------------------------------------------------------------- + +#pragma once + +//---- Define assertion handler. Defaults to calling assert(). +// - If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +// - Compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes. +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) +//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() +// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. +//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export +//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import +//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden + +//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//---- Disable all of Dear ImGui or don't implement standard windows/tools. +// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. +//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. +//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. +//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty. + +//---- Don't implement some functions to reduce linkage requirements. +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) +//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) +//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). +//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). +//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. +//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) +//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. +//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). +//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded fonts (ProggyClean/ProggyVector), remove ~9 KB + ~17 KB from output binary. AddFontDefaultXXX() functions will assert. +//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available + +//---- Enable Test Engine / Automation features. +//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details. + +//---- Include imgui_user.h at the end of imgui.h as a convenience +// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. +//#define IMGUI_INCLUDE_IMGUI_USER_H +//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h" + +//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support. +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate. +//#define IMGUI_USE_LEGACY_CRC32_ADLER + +//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) +//#define IMGUI_USE_WCHAR32 + +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined. +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined. + +//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. +//#define IMGUI_USE_STB_SPRINTF + +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). +// Note that imgui_freetype.cpp may be used _without_ this define, if you manually call ImFontAtlas::SetFontLoader(). The define is simply a convenience. +// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. +//#define IMGUI_ENABLE_FREETYPE + +//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT) +// Only works in combination with IMGUI_ENABLE_FREETYPE. +// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions. +// - Both require headers to be available in the include path + program to be linked with the library code (not provided). +// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) +//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG +//#define IMGUI_ENABLE_FREETYPE_LUNASVG + +//---- Use stb_truetype to build and rasterize the font atlas (default) +// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. +//#define IMGUI_ENABLE_STB_TRUETYPE + +//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. +// This will be inlined as part of ImVec2 and ImVec4 class declarations. +/* +#define IM_VEC2_CLASS_EXTRA \ + constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ +//---- ...Or use Dear ImGui's own very basic math operators. +//#define IMGUI_DEFINE_MATH_OPERATORS + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +//#define ImDrawIdx unsigned int + +//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) +//struct ImDrawList; +//struct ImDrawCmd; +//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +//#define ImDrawCallback MyImDrawCallback + +//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase) +// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) +//#define IM_DEBUG_BREAK IM_ASSERT(0) +//#define IM_DEBUG_BREAK __debugbreak() + +//---- Debug Tools: Enable highlight ID conflicts _before_ hovering items. When io.ConfigDebugHighlightIdConflicts is set. +// (THIS WILL SLOW DOWN DEAR IMGUI. Only use occasionally and disable after use) +//#define IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + +//---- Debug Tools: Enable slower asserts +//#define IMGUI_DEBUG_PARANOID + +//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files) +/* +namespace ImGui +{ + void MyFunction(const char* name, MyMatrix44* mtx); +} +*/ diff --git a/libs/imgui/imgui.cpp b/libs/imgui/imgui.cpp new file mode 100644 index 0000000..eebffff --- /dev/null +++ b/libs/imgui/imgui.cpp @@ -0,0 +1,24139 @@ +// dear imgui, v1.92.6 WIP +// (main code and documentation) + +// Help: +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// - Read top of imgui.cpp for more details, links and comments. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including imgui.h (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. + +// Resources: +// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) +// - Homepage ................... https://github.com/ocornut/imgui +// - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) +// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) +// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) +// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) +// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui +// - Issues & support ........... https://github.com/ocornut/imgui/issues +// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +// - Web version of the Demo .... https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html (w/ source code browser) + +// For FIRST-TIME users having issues compiling/linking/running: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. +// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// Since 1.92, we encourage font loading questions to also be posted in 'Issues'. + +// Copyright (c) 2014-2026 Omar Cornut +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// See LICENSE.txt for copyright and licensing details (standard MIT License). +// This library is free but needs your support to sustain development and maintenance. +// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts. +// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding +// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine. + +// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library. +// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without +// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't +// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you +// to a better solution or official support for them. + +/* + +Index of this file: + +DOCUMENTATION + +- MISSION STATEMENT +- CONTROLS GUIDE +- PROGRAMMER GUIDE + - READ FIRST + - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI + - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE + - HOW A SIMPLE APPLICATION MAY LOOK LIKE + - USING CUSTOM BACKEND / CUSTOM ENGINE +- API BREAKING CHANGES (read me when you update!) +- FREQUENTLY ASKED QUESTIONS (FAQ) + - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer) + +CODE +(search for "[SECTION]" in the code to find them) + +// [SECTION] INCLUDES +// [SECTION] FORWARD DECLARATIONS +// [SECTION] CONTEXT AND MEMORY ALLOCATORS +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) +// [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +// [SECTION] MISC HELPERS/UTILITIES (File functions) +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +// [SECTION] MISC HELPERS/UTILITIES (Color functions) +// [SECTION] ImGuiStorage +// [SECTION] ImGuiTextFilter +// [SECTION] ImGuiTextBuffer, ImGuiTextIndex +// [SECTION] ImGuiListClipper +// [SECTION] STYLING +// [SECTION] RENDER HELPERS +// [SECTION] INITIALIZATION, SHUTDOWN +// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +// [SECTION] FONTS, TEXTURES +// [SECTION] ID STACK +// [SECTION] INPUTS +// [SECTION] ERROR CHECKING, STATE RECOVERY +// [SECTION] ITEM SUBMISSION +// [SECTION] LAYOUT +// [SECTION] SCROLLING +// [SECTION] TOOLTIPS +// [SECTION] POPUPS +// [SECTION] WINDOW FOCUS +// [SECTION] KEYBOARD/GAMEPAD NAVIGATION +// [SECTION] DRAG AND DROP +// [SECTION] LOGGING/CAPTURING +// [SECTION] SETTINGS +// [SECTION] LOCALIZATION +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +// [SECTION] DOCKING +// [SECTION] PLATFORM DEPENDENT HELPERS +// [SECTION] METRICS/DEBUGGER WINDOW +// [SECTION] DEBUG LOG WINDOW +// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) + +*/ + +//----------------------------------------------------------------------------- +// DOCUMENTATION +//----------------------------------------------------------------------------- + +/* + + MISSION STATEMENT + ================= + + - Easy to use to create code-driven and data-driven tools. + - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. + - Easy to hack and improve. + - Minimize setup and maintenance. + - Minimize state storage on user side. + - Minimize state synchronization. + - Portable, minimize dependencies, run on target (consoles, phones, etc.). + - Efficient runtime and memory consumption. + + Designed primarily for developers and content-creators, not the typical end-user! + Some of the current weaknesses (which we aim to address in the future) includes: + + - Doesn't look fancy by default. + - Limited layout features, intricate layouts are typically crafted in code. + + + CONTROLS GUIDE + ============== + + - MOUSE CONTROLS + - Mouse wheel: Scroll vertically. + - Shift+Mouse wheel: Scroll horizontally. + - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin(). + - Click ^, Double-Click title: Collapse window. + - Drag on corner/border: Resize window (double-click to auto fit window to its contents). + - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true). + - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack). + + - TEXT EDITOR + - Hold Shift or Drag Mouse: Select text. + - Ctrl+Left/Right: Word jump. + - Ctrl+Shift+Left/Right: Select words. + - Ctrl+A or Double-Click: Select All. + - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard. + - Ctrl+Z Undo. + - Ctrl+Y or Ctrl+Shift+Z: Redo. + - ESCAPE: Revert text to its original value. + - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors. + (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS). + + - KEYBOARD CONTROLS + - Basic: + - Tab, Shift+Tab Cycle through text editable fields. + - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows. + - Ctrl+Click Input text into a Slider or Drag widget. + - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`: + - Tab, Shift+Tab: Cycle through every items. + - Arrow keys Move through items using directional navigation. Tweak value. + - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys). + - Enter Activate item (prefer text input when possible). + - Space Activate item (prefer tweaking with arrows when possible). + - Escape Deactivate item, leave child window, close popup. + - Page Up, Page Down Previous page, next page. + - Home, End Scroll to top, scroll to bottom. + - Alt Toggle between scrolling layer and menu layer. + - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving. + - Output when ImGuiConfigFlags_NavEnableKeyboard set, + - io.WantCaptureKeyboard flag is set when keyboard is claimed. + - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. + - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used). + + - GAMEPAD CONTROLS + - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. + - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse! + - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets + - Backend support: backend needs to: + - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys. + - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly. + Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.). + - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing, + with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved. + + - REMOTE INPUTS SHARING & MOUSE EMULATION + - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback. + - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app) + in order to share your PC mouse/keyboard. + - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions. + - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag. + Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements. + When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. + When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that. + (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!) + (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want + to set a boolean to ignore your other external mouse positions until the external source is moved again.) + + + PROGRAMMER GUIDE + ================ + + READ FIRST + ---------- + - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki + - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone! + The UI can be highly dynamic, there are no construction or destruction steps, less superfluous + data retention on your side, less state duplication, less state synchronization, fewer bugs. + - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features. + Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version. + - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build. + - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). + You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki. + - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. + For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI, + where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. + - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. + - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected). + If you get an assert, read the messages and comments around the assert. + - This codebase aims to be highly optimized: + - A typical idle frame should never call malloc/free. + - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible. + - We put particular energy in making sure performances are decent with typical "Debug" build settings as well. + Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all. + - This codebase aims to be both highly opinionated and highly flexible: + - This code works because of the things it choose to solve or not solve. + - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers, + and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now). + This is to increase compatibility, increase maintainability and facilitate use from other languages. + - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. + See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. + We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally. + - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction + (so don't use ImVector in your code or at our own risk!). + - Building: We don't use nor mandate a build system for the main library. + This is in an effort to ensure that it works in the real world aka with any esoteric build setup. + This is also because providing a build system for the main library would be of little-value. + The build problems are almost never coming from the main library but from specific backends. + + + HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI + ---------------------------------------------- + - Update submodule or copy/overwrite every file. + - About imconfig.h: + - You may modify your copy of imconfig.h, in this case don't overwrite it. + - or you may locally branch to modify imconfig.h and merge/rebase latest. + - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to + specify a custom path for your imconfig.h file and instead not have to modify the default one. + + - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h) + - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master". + - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file. + - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. + If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed + from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will + likely be a comment about it. Please report any issue to the GitHub page! + - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file. + - Try to keep your copy of Dear ImGui reasonably up to date! + + + GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE + --------------------------------------------------------------- + - See https://github.com/ocornut/imgui/wiki/Getting-Started. + - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. + - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder. + - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system. + It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL). + - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. + - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. + - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. + Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" + phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render(). + - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. + - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. + + + HOW A SIMPLE APPLICATION MAY LOOK LIKE + -------------------------------------- + + USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). + The sub-folders in examples/ contain examples applications following this structure. + + // Application init: create a dear imgui context, setup some options, load fonts + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. + // TODO: Fill optional fields of the io structure later. + // TODO: Load TTF/OTF fonts if you don't want to use the default font. + + // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp) + ImGui_ImplWin32_Init(hwnd); + ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); + + // Application main loop + while (true) + { + // Feed inputs to dear imgui, start new frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // Any application code here + ImGui::Text("Hello, world!"); + + // Render dear imgui into framebuffer + ImGui::Render(); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + g_pSwapChain->Present(1, 0); + } + + // Shutdown + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + + To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, + you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. + + +USING CUSTOM BACKEND / CUSTOM ENGINE +------------------------------------ + +IMPLEMENTING YOUR PLATFORM BACKEND: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. + -> the Platform backends in impl_impl_XXX.cpp files contain many implementations. + +IMPLEMENTING YOUR RenderDrawData() function: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function. + +IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function. + + Basic application/backend skeleton: + + // Application init: create a Dear ImGui context, setup some options, load fonts + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + // TODO: set io.ConfigXXX values, e.g. + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls + + // TODO: Load TTF/OTF fonts if you don't want to use the default font. + io.Fonts->AddFontFromFileTTF("NotoSans.ttf"); + + // Application main loop + while (true) + { + // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc. + // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends) + io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds) + io.DisplaySize.x = 1920.0f; // set the current display width + io.DisplaySize.y = 1280.0f; // set the current display height here + io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position + io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states + io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states + + // Call NewFrame(), after this point you can use ImGui::* functions anytime + // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere) + ImGui::NewFrame(); + + // Most of your application code here + ImGui::Text("Hello, world!"); + MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any Dear ImGui functions as well! + + // End the dear imgui frame + // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) + ImGui::EndFrame(); // this is automatically called by Render(), but available + ImGui::Render(); + + // Update textures + ImDrawData* draw_data = ImGui::GetDrawData(); + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); + + // Render dear imgui contents, swap buffers + MyImGuiBackend_RenderDrawData(draw_data); + SwapBuffers(); + } + + // Shutdown + ImGui::DestroyContext(); + + + + API BREAKING CHANGES + ==================== + + Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. + Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. + When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. + You can read releases logs https://github.com/ocornut/imgui/releases for more details. + +(Docking/Viewport Branch) + - 2026/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that: + - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore. + you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos) + - likewise io.MousePos and GetMousePos() will use OS coordinates. + If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. + + - 2026/01/08 (1.92.6) - Commented out legacy names obsoleted in 1.90 (Sept 2023): 'BeginChildFrame()' --> 'BeginChild()' with 'ImGuiChildFlags_FrameStyle'. 'EndChildFrame()' --> 'EndChild()'. 'ShowStackToolWindow()' --> 'ShowIDStackToolWindow()'. 'IM_OFFSETOF()' --> 'offsetof()'. + - 2026/01/07 (1.92.6) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). Default value has same meaning before and after. + - Refer to GitHub topic #9157 if you have any question. + - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default value in their function signature. + Explicitly passing a literal 0 meant ImGuiPopupFlags_MouseButtonLeft. The default literal 1 meant ImGuiPopupFlags_MouseButtonRight. + This was introduced by a change on 2020/06/23 (1.77) while changing the signature from 'int mouse_button' to 'ImGuiPopupFlags popup_flags' and trying to preserve then-legacy behavior. + We have now changed this behavior to cleanup a very old API quirk, facilitate use by bindings, and to remove the last and error-prone non-zero default value. + Also because we deemed it extremely rare to use those helper functions with the Left mouse button! As using the LMB would generally be triggered via another widget, e.g. a Button() + a OpenPopup()/BeginPopup() call. + - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft. + - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 1 also means ImGuiPopupFlags_MouseButtonRight (if legacy behavior are enabled) or will assert (if legacy behavior are disabled). + - TL;DR: if you don't want to use right mouse button for popups, always specify it explicitly using a named ImGuiPopupFlags_MouseButtonXXXX value. + Recap: + - BeginPopupContextItem("foo"); // Behavior unchanged (use Right button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft); // Behavior unchanged (use Left button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft | xxx); // Behavior unchanged (use Left button + flags) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonRight | xxx); // Behavior unchanged (use Right button + flags) + - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. + - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. + - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. + - 2025/12/23 (1.92.6) - Fonts:AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap(). + The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold. Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior. + - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. + - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now. + - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. + - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); + - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); + - This has the property of facilitating concatenating and manipulating identifiers using "###", and will allow fixing other dangling issues. + - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) + - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory. + (trivia: undetected since July 2015, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature, see #9086) + HOWEVER, fixing this bug is likely to surface bugs in user code using `FontDataOwnedByAtlas = false`. + - Prior to 1.92, font data only needed to be available during the atlas->AddFontXXX() call. + - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically until a shutdown of the owning context or font atlas. + - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether. + - 2025/11/06 (1.92.5) - BeginChild: commented out some legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024): + - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders + - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) + - ImGuiWindowFlags_AlwaysUseWindowPadding --> ImGuiChildFlags_AlwaysUseWindowPadding (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) + - 2025/11/06 (1.92.5) - Keys: commented out legacy names which were obsoleted in 1.89.0 (August 2022): + - ImGuiKey_ModCtrl --> ImGuiMod_Ctrl + - ImGuiKey_ModShift --> ImGuiMod_Shift + - ImGuiKey_ModAlt --> ImGuiMod_Alt + - ImGuiKey_ModSuper --> ImGuiMod_Super + - 2025/11/06 (1.92.5) - IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8 (Aug 2023). Calling io.ClearInputKeys() is enough. + - 2025/11/06 (1.92.5) - Commented out legacy SetItemAllowOverlap() obsoleted in 1.89.7: this never worked right. Use SetNextItemAllowOverlap() _before_ item instead. + - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); + - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap + - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap + - ImGuiListClipper::IncludeRangeByIndices() --> ImGuiListClipper::IncludeItemsByIndex() + - 2025/09/22 (1.92.4) - Viewports: renamed io.ConfigViewportPlatformFocusSetsImGuiFocus to io.ConfigViewportsPlatformFocusSetsImGuiFocus. Was a typo in the first place. (#6299, #6462) + - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) + - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). + - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM + to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) + - Incorrect way to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - Correct ways to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + Begin(...) + Dummy(ImVec2(200,200)) + End(); + - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries. + - 2025/06/11 (1.92.0) - Renamed/moved ImGuiConfigFlags_DpiEnableScaleFonts -> bool io.ConfigDpiScaleFonts. + - Renamed/moved ImGuiConfigFlags_DpiEnableScaleViewports -> bool io.ConfigDpiScaleViewports. **Neither of those flags are very useful in current code. They will be useful once we merge font changes.** + [there was a bug on 2025/06/12: when using the old config flags names, they were not imported correctly into the new ones, fixed on 2025/09/12] + - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED. + IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ + As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+). + If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes. + - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this! + - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f): + This WILL NOT map correctly to the new system! Because font will rasterize as requested size. + - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required. + - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. + - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized. + - PushFont() API now has a REQUIRED size parameter. + - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize). + - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value. + - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site. + - Kept inline single parameter function. Will obsolete. + - Fonts: **IMPORTANT** on Font Merging: + - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph. + Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font. + - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before! + - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. + After the update and when using a new backend, those glyphs may now loaded from Font Source 1! + - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source: + // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range + static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + ImFontConfig cfg1; + cfg1.GlyphExcludeRanges = exclude_ranges; + io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + // Add Font Source 2, which expects to use the range above + ImFontConfig cfg2; + cfg2.MergeMode = true; + io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); + - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. + - Fonts: **IMPORTANT** on Thread Safety: + - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded. + - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). + - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". + - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. + - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). + - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete). + - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling. + - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). + - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) + - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one), you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors. + - Fonts: obsoleted ImFont::Scale which is not useful anymore. + - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: + - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef. + - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] + - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. + - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. + - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance(). + - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels(). + - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.) + - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. + If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). + - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() + - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader() + - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1] + - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV(). + - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h. + - old: + const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id); + ImVec2 uv0, uv1; + atlas->GetCustomRectUV(r, &uv0, &uv1); + ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1); + - new; + ImFontAtlasRect r; + atlas->GetCustomRect(custom_rect_id, &r); + ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple. + - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code. + - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. + - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). + - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more. + - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition() + - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....); + - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....); + The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function. + - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). + - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) + - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead. + - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. + - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) + - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) + - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); + - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); + - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1)); + - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton(). + - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize. + - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable. + - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified. + - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg(). + - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount. + - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX. + - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. + prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. + the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls: + - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937) + - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions. + As a result, old .ini data may be partially lost (docking and tables information particularly). + Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data. + - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before) + - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022). + - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022). + - GetKeyIndex() is removed (obsoleted March 2022). The indirection is now unnecessary. + - pre-1.87 backends are not supported: + - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields. + - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields. + - for more reference: + - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88. + - read https://github.com/ocornut/imgui/issues/4921 + - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest. + - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END? + - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements. + - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete). + - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool. + moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!). + kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value! + - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641) + this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers. + you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image(). + in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning: + - May warn: ImGui::Image((void*)MyTextureData, ...); + - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...); + - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...); + - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like. + - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76) + - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed). + although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76) + - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) + it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() + - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag. + - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: + - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData. + - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line. + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn + - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) + - access those via GetPlatformIO() instead of GetIO(). + some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol. + - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder: + - old ImageButton() before 1.89 used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID) + - new ImageButton() since 1.89 requires an explicit 'const char* str_id' + - old ImageButton() before 1.89 had frame_padding' override argument. + - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar(). + - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) + you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way. + - instead of: GetWindowContentRegionMax().x - GetCursorPos().x + - you can use: GetContentRegionAvail().x + - instead of: GetWindowContentRegionMax().x + GetWindowPos().x + - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window + - instead of: GetContentRegionMax() + - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates + - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x + - you can use: GetContentRegionAvail() // when called from left edge of window + - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) + (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors) + - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). + - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) + - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) + - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. + - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness. + - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data); + - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow. + - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened); + - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0); + - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does. + - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. + - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. + - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). + - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library. + - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading. + - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022): + - old: CaptureKeyboardFromApp(bool) + - new: SetNextFrameWantCaptureKeyboard(bool) + - old: CaptureMouseFromApp(bool) + - new: SetNextFrameWantCaptureMouse(bool) + - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs). + - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest. + - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures: + - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0); + - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0); + - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures. + - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0); + - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); + - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0); + - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0); + for various reasons those changes makes sense. They are being made because making some of those API public. + only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL. + - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611) + - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...); + - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...); + - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys. + - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps. + - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456) + - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions. + - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282) + - old: TreeNode("##Hidden"); SameLine(); Text("Hello"); // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise). + - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values. + with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item. + You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent. + (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth). + - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417) + - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921) + - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) + - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'. + - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter. + - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges. + - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls. + - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80. + - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete). + - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete). + those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features. + - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work. + - old: BeginChild("Name", size, true) + - new: BeginChild("Name", size, ImGuiChildFlags_Border) + - old: BeginChild("Name", size, false) + - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None) + **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'** + - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow. + - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding); + - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0); + - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user). + - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631) + - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete). + - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...) + - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...); + - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...); + - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...); + - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions: + - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful. + - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources. + - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry! + - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878) + - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15). + - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete). + - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior. + - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610) + - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage. + - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3. + - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago: + - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference) + - ListBoxFooter() -> use EndListBox() + - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin(). + - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices(). + - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago: + - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp + - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite + - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic() + - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo() + - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete). + - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner. + - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h. + Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA, + it has been frequently requested by people to use our own. We had an opt-in define which was + previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164) + - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h" + - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h" + - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3. + - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79. + - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details. + - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete). + - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl + - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift + - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt + - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super + the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends. + the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions. + exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway. + - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers. + this will require uses of legacy backend-dependent indices to be casted, e.g. + - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A); + - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A') + - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now! + - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr); + - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020): + - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f. + - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f. + - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags) + - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries. + this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item. + - previously this would make the window content size ~200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - instead, please submit an item: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + - alternative: + Begin(...) + Dummy(ImVec2(200,200)) + End(); + - content size is now only extended when submitting an item! + - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert. + - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it. + - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete). + - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter. + - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1)); + - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values. + - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer. + - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1)); + - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier. + - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this. + - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes). + - Official backends from 1.87+ -> no issue. + - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating! + - Custom backends not writing to io.NavInputs[] -> no issue. + - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing! + - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[]. + - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete). + - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary. + - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO. + - 2022/01/20 (1.87) - inputs: reworded gamepad IO. + - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values. + - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used). + - 2022/01/17 (1.87) - inputs: reworked mouse IO. + - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent() + - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent() + - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent() + - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only] + note: for all calls to IO new functions, the Dear ImGui context should be bound/current. + read https://github.com/ocornut/imgui/issues/4921 for details. + - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. + - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) + - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) + - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes). + - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.* + - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert. + - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper. + - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum. + - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'. + - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019) + - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen() + - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x + - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing()); + - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect + - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex + - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings + - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function. + - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful. + - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019): + - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList() + - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder + - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID(). + - if you are using official backends from the source tree: you have nothing to do. + - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID(). + - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags. + - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft + - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight + - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc. + flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API. + breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners": + - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use) + - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use) + - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use) + - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f. + this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok. + the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts. + legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise). + - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018): + - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY() + - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing. + - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future. + - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'. + - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed. + - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete). + - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete). + - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete). + - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags. + - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags. + - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. + - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018): + - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit(). + - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg + - ImGuiInputTextCallback -> use ImGuiTextEditCallback + - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData + - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete). + - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added! + - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API. + - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures + - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. + - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend + - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) + - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT + - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT + - removed redirecting functions names that were marked obsolete in 1.61 (May 2018): + - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision. + - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter. + - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). + - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). + - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. + - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. + - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. + - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now! + - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). + replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: + - if you omitted the 'power' parameter (likely!), you are not affected. + - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + see https://github.com/ocornut/imgui/issues/3361 for all details. + kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. + for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. + - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. + - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79] + - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). + - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. + - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. + - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. + - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017): + - ShowTestWindow() -> use ShowDemoWindow() + - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow) + - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) + - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)) + - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing() + - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg + - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding + - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap + - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS + - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API. + - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it). + - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert. + - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency. + - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency. + - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017): + - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed + - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) + - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding() + - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f) + - ImFont::Glyph -> use ImFontGlyph + - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function. + if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix. + The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay). + If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you. + - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). + - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). + - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71. + - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have + overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. + This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows. + Please reach out if you are affected. + - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). + - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). + - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. + - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). + - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). + - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). + - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value! + - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). + - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! + - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). + - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. + - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags. + - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files. + - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete). + - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h. + If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths. + - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427) + - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp. + NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED. + Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions. + - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent). + - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete). + - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly). + - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature. + - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. + - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. + - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). + - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). + old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports. + when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call. + in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. + - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. + - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. + - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. + If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. + To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code. + If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them. + - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", + consistent with other functions. Kept redirection functions (will obsolete). + - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value. + - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch). + - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now. + - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. + - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. + - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. + - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display. + - 2018/02/07 (1.60) - reorganized context handling to be more explicit, + - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. + - removed Shutdown() function, as DestroyContext() serve this purpose. + - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance. + - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts. + - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. + - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths. + - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). + - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). + - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. + - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side. + - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete). + - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags + - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame. + - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. + - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete). + - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete). + - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete). + - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete). + - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete). + - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed. + - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up. + Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions. + - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. + - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg. + - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding. + - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); + - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency. + - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. + - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. + removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. + IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly) + IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior] + - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! + - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). + - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). + - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). + - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". + - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! + - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). + - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). + - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. + - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix. + - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. + - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. + - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). + - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete). + - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). + - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. + - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. + - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))' + - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse + - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. + - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. + - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild(). + - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. + - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. + - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal. + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color: + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount' + ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new. + ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'. + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. + - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API + - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. + - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. + - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing + - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) + - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. + - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. + - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. + - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior + - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() + - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) + - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. + - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. + - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. + - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..]; + - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier); + you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation. + - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID() + - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) + - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets + - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) + - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) + - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + FREQUENTLY ASKED QUESTIONS (FAQ) + ================================ + + Read all answers online: + https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) + Read all answers locally (with a text editor or ideally a Markdown viewer): + docs/FAQ.md + Some answers are copied down here to facilitate searching in code. + + Q&A: Basics + =========== + + Q: Where is the documentation? + A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++. + - Run the examples/ applications and explore them. + - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide. + - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. + - The demo covers most features of Dear ImGui, so you can read the code and see its output. + - See documentation and comments at the top of imgui.cpp + effectively imgui.h. + - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the + examples/ folder to explain how to integrate Dear ImGui with your own engine/application. + - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links. + - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful. + - Your programming IDE is your friend, find the type or function declaration to find comments + associated with it. + + Q: What is this library called? + Q: What is the difference between Dear ImGui and traditional UI toolkits? + Q: Which version should I get? + >> This library is called "Dear ImGui", please don't call it "ImGui" :) + >> See https://www.dearimgui.com/faq for details. + + Q&A: Integration + ================ + + Q: How to get started? + A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt. + + Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application? + A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this. + + Q. How can I enable keyboard or gamepad controls? + Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display) + Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... + Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around... + Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries... + >> See https://www.dearimgui.com/faq + + Q&A: Usage + ---------- + + Q: About the ID Stack system.. + - Why is my widget not reacting when I click on it? + - How can I have widgets with an empty label? + - How can I have multiple widgets with the same label? + - How can I have multiple windows with the same label? + Q: How can I display an image? What is ImTextureID, how does it work? + Q: How can I use my own math types instead of ImVec2? + Q: How can I interact with standard C++ types (such as std::string and std::vector)? + Q: How can I display custom shapes? (using low-level ImDrawList API) + >> See https://www.dearimgui.com/faq + + Q&A: Fonts, Text + ================ + + Q: How should I handle DPI in my application? + Q: How can I load a different font than the default? + Q: How can I easily use icons in my application? + Q: How can I load multiple fonts? + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md + + Q&A: Concerns + ============= + + Q: Who uses Dear ImGui? + Q: Can you create elaborate/serious tools with Dear ImGui? + Q: Can you reskin the look of Dear ImGui? + Q: Why using C++ (as opposed to C)? + >> See https://www.dearimgui.com/faq + + Q&A: Community + ============== + + Q: How can I help? + A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui! + We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. + This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project. + >>> See https://github.com/ocornut/imgui/wiki/Funding + - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine. + - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help! + - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. + You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers. + But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions. + - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately). + +*/ + +//------------------------------------------------------------------------- +// [SECTION] INCLUDES +//------------------------------------------------------------------------- + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_internal.h" + +// System includes +#include // vsnprintf, sscanf, printf +#include // intptr_t + +// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled +#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) +#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS +#endif + +// [Windows] OS specific includes (optional) +#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#define IMGUI_DISABLE_WIN32_FUNCTIONS +#endif +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef __MINGW32__ +#include // _wfopen, OpenClipboard +#else +#include +#endif +#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)) +// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions +#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS +#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif +#endif + +// [Apple] OS specific includes +#if defined(__APPLE__) +#include +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label +#elif defined(__GNUC__) +// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association. +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result +#endif + +// Debug options +#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold Ctrl to display for all candidates. Ctrl+Arrow to change last direction. +#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window + +// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. +static const float FONT_DEFAULT_SIZE_BASE = 20.0f; + +// When using Ctrl+Tab (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. +static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in +static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear +static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut. +static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. +static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. + +// Tooltip offset +static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale +static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale +static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale + +// Docking +static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. + +//------------------------------------------------------------------------- +// [SECTION] FORWARD DECLARATIONS +//------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow* window); +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); + +static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); + +// Settings +static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); +static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); +static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); +static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); +static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); + +// Platform Dependents default implementation for ImGuiPlatformIO functions +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx); +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text); +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); + +namespace ImGui +{ +// Item +static void ItemHandleShortcut(ImGuiID id); + +// Window Focus +static int FindWindowFocusIndex(ImGuiWindow* window); +static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags); + +// Navigation +static void NavUpdate(); +static void NavUpdateWindowing(); +static void NavUpdateWindowingApplyFocus(ImGuiWindow* window); +static void NavUpdateWindowingOverlay(); +static void NavUpdateCancelRequest(); +static void NavUpdateCreateMoveRequest(); +static void NavUpdateCreateTabbingRequest(); +static float NavUpdatePageUpPageDown(); +static inline void NavUpdateAnyRequestFlag(); +static void NavUpdateCreateWrappingRequest(); +static void NavEndFrame(); +static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb); +static void NavApplyItemToResult(ImGuiNavItemData* result); +static void NavProcessItem(); +static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags); +static ImGuiInputSource NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type); +static ImVec2 NavCalcPreferredRefPos(ImGuiWindowFlags window_type); +static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); +static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); +static void NavRestoreLayer(ImGuiNavLayer layer); + +// Error Checking and Debug Tools +static void ErrorCheckNewFrameSanityChecks(); +static void ErrorCheckEndFrameSanityChecks(); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +static void UpdateDebugToolItemPicker(); +static void UpdateDebugToolItemPathQuery(); +static void UpdateDebugToolFlashStyleColor(); +#endif + +// Inputs +static void UpdateKeyboardInputs(); +static void UpdateMouseInputs(); +static void UpdateMouseWheel(); +static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); + +// Misc +static void UpdateFontsNewFrame(); +static void UpdateFontsEndFrame(); +static void UpdateTexturesNewFrame(); +static void UpdateTexturesEndFrame(); +static void UpdateSettings(); +static int UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); +static void RenderWindowOuterBorders(ImGuiWindow* window); +static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); +static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); +static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col); +static void RenderDimmedBackgrounds(); +static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect); +static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect); + +// Viewports +const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. +static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags); +static void DestroyViewport(ImGuiViewportP* viewport); +static void UpdateViewportsNewFrame(); +static void UpdateViewportsEndFrame(); +static void WindowSelectViewport(ImGuiWindow* window); +static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack); +static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport); +static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window); +static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window); +static int FindPlatformMonitorForPos(const ImVec2& pos); +static int FindPlatformMonitorForRect(const ImRect& r); +static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport); + +} + +//----------------------------------------------------------------------------- +// [SECTION] CONTEXT AND MEMORY ALLOCATORS +//----------------------------------------------------------------------------- + +// DLL users: +// - Heaps and globals are not shared across DLL boundaries! +// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from. +// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL). +// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in). + +// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL. +// - ImGui::CreateContext() will automatically set this pointer if it is NULL. +// Change to a different context by calling ImGui::SetCurrentContext(). +// - Important: Dear ImGui functions are not thread-safe because of this pointer. +// If you want thread-safety to allow N threads to access N different contexts: +// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h: +// struct ImGuiContext; +// extern thread_local ImGuiContext* MyImGuiTLS; +// #define GImGui MyImGuiTLS +// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword. +// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace. +// - DLL users: read comments above. +#ifndef GImGui +ImGuiContext* GImGui = NULL; +#endif + +// Memory Allocator functions. Use SetAllocatorFunctions() to change them. +// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. +// - DLL users: read comments above. +#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS +static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); } +static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); } +#else +static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; } +static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); } +#endif +static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper; +static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper; +static void* GImAllocatorUserData = NULL; + +//----------------------------------------------------------------------------- +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. + FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + + Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. + DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + WindowPadding = ImVec2(8,8); // Padding within a window + WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. + WindowBorderHoverPadding = 4.0f; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders. + WindowMinSize = ImVec2(32,32); // Minimum window size + WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. + ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows + ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. + PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows + PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. + FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. + ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. + TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axises) + GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + ImageRounding = 0.0f; // Rounding of Image() calls. + ImageBorderSize = 0.0f; // Thickness of border around tabs. + TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + TabBorderSize = 0.0f; // Thickness of border around tabs. + TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy. + TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. + TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. + TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. + TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. + TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). + TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell + TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone; + TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line. + DragDropTargetRounding = 0.0f; // Radius of the drag and drop target frame. + DragDropTargetBorderSize = 2.0f; // Thickness of the drag and drop target border. + DragDropTargetPadding = 3.0f; // Size to expand the drag and drop target from actual target item size. + ColorMarkerSize = 3.0f; // Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags_ColorMarkers. + ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText() + SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). + SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. + DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + DockingNodeHasCloseButton = true; // Docking nodes have their own CloseButton() to close all docked windows. + DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows + MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). + CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + + // Behaviors + HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. + HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay. + HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). " + HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. + + // [Internal] + _MainScale = 1.0f; + _NextFrameFontSizeBase = 0.0f; + + // Default theme + ImGui::StyleColorsDark(this); +} + + +// Scale all spacing/padding/thickness values. Do not scale fonts. +// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. +void ImGuiStyle::ScaleAllSizes(float scale_factor) +{ + _MainScale *= scale_factor; + WindowPadding = ImTrunc(WindowPadding * scale_factor); + WindowRounding = ImTrunc(WindowRounding * scale_factor); + WindowMinSize = ImTrunc(WindowMinSize * scale_factor); + WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor); + ChildRounding = ImTrunc(ChildRounding * scale_factor); + PopupRounding = ImTrunc(PopupRounding * scale_factor); + FramePadding = ImTrunc(FramePadding * scale_factor); + FrameRounding = ImTrunc(FrameRounding * scale_factor); + ItemSpacing = ImTrunc(ItemSpacing * scale_factor); + ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor); + CellPadding = ImTrunc(CellPadding * scale_factor); + TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor); + IndentSpacing = ImTrunc(IndentSpacing * scale_factor); + ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor); + ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor); + ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor); + ScrollbarPadding = ImTrunc(ScrollbarPadding * scale_factor); + GrabMinSize = ImTrunc(GrabMinSize * scale_factor); + GrabRounding = ImTrunc(GrabRounding * scale_factor); + LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); + ImageRounding = ImTrunc(ImageRounding * scale_factor); + ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); + TabRounding = ImTrunc(TabRounding * scale_factor); + TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor); + TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor); + TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; + TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; + TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); + TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor); + DragDropTargetRounding = ImTrunc(DragDropTargetRounding * scale_factor); + DragDropTargetBorderSize = ImTrunc(DragDropTargetBorderSize * scale_factor); + DragDropTargetPadding = ImTrunc(DragDropTargetPadding * scale_factor); + ColorMarkerSize = ImTrunc(ColorMarkerSize * scale_factor); + SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); + DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor); + DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); + DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); + MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor); +} + +ImGuiIO::ImGuiIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + IM_STATIC_ASSERT(IM_COUNTOF(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_COUNTOF(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); + + // Settings + ConfigFlags = ImGuiConfigFlags_None; + BackendFlags = ImGuiBackendFlags_None; + DisplaySize = ImVec2(-1.0f, -1.0f); + DeltaTime = 1.0f / 60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables). + LogFilename = "imgui_log.txt"; + UserData = NULL; + + Fonts = NULL; + FontDefault = NULL; + FontAllowUserScaling = false; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + FontGlobalScale = 1.0f; // Use style.FontScaleMain instead! +#endif + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + + // Keyboard/Gamepad Navigation options + ConfigNavSwapGamepadButtons = false; + ConfigNavMoveSetMousePos = false; + ConfigNavCaptureKeyboard = true; + ConfigNavEscapeClearFocusItem = true; + ConfigNavEscapeClearFocusWindow = false; + ConfigNavCursorVisibleAuto = true; + ConfigNavCursorVisibleAlways = false; + + // Docking options (when ImGuiConfigFlags_DockingEnable is set) + ConfigDockingNoSplit = false; + ConfigDockingNoDockingOver = false; + ConfigDockingWithShift = false; + ConfigDockingAlwaysTabBar = false; + ConfigDockingTransparentPayload = false; + + // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) + ConfigViewportsNoAutoMerge = false; + ConfigViewportsNoTaskBarIcon = false; + ConfigViewportsNoDecoration = true; + ConfigViewportsNoDefaultParent = true; + ConfigViewportsPlatformFocusSetsImGuiFocus = true; + + // Miscellaneous options + MouseDrawCursor = false; +#ifdef __APPLE__ + ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag +#else + ConfigMacOSXBehaviors = false; +#endif + ConfigInputTrickleEventQueue = true; + ConfigInputTextCursorBlink = true; + ConfigInputTextEnterKeepActive = false; + ConfigDragClickToInputText = false; + ConfigWindowsResizeFromEdges = true; + ConfigWindowsMoveFromTitleBarOnly = false; + ConfigWindowsCopyContentsWithCtrlC = false; + ConfigScrollbarScrollByPage = true; + ConfigMemoryCompactTimer = 60.0f; + ConfigDebugIsDebuggerPresent = false; + ConfigDebugHighlightIdConflicts = true; + ConfigDebugHighlightIdConflictsShowItemPicker = true; + ConfigDebugBeginReturnValueOnce = false; + ConfigDebugBeginReturnValueLoop = false; + + ConfigErrorRecovery = true; + ConfigErrorRecoveryEnableAssert = true; + ConfigErrorRecoveryEnableDebugLog = true; + ConfigErrorRecoveryEnableTooltip = true; + + // Inputs Behaviors + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + MouseDragThreshold = 6.0f; + KeyRepeatDelay = 0.275f; + KeyRepeatRate = 0.050f; + + // Platform Functions + // Note: Initialize() will setup default clipboard/ime handlers. + BackendPlatformName = BackendRendererName = NULL; + BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; + + // Input (NB: we already have memset zero the entire structure!) + MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); + MouseSource = ImGuiMouseSource_Mouse; + for (int i = 0; i < IM_COUNTOF(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_COUNTOF(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; } + AppAcceptingEvents = true; +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API +void ImGuiIO::AddInputCharacter(unsigned int c) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + if (c == 0 || !AppAcceptingEvents) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Text; + e.Source = ImGuiInputSource_Keyboard; + e.EventId = g.InputEventsNextEventId++; + e.Text.Char = c; + g.InputEventsQueue.push_back(e); +} + +// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so +// we should save the high surrogate. +void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) +{ + if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents) + return; + + if ((c & 0xFC00) == 0xD800) // High surrogate, must save + { + if (InputQueueSurrogate != 0) + AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID); + InputQueueSurrogate = c; + return; + } + + ImWchar cp = c; + if (InputQueueSurrogate != 0) + { + if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate + { + AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID); + } + else + { +#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF + cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar +#else + cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000); +#endif + } + + InputQueueSurrogate = 0; + } + AddInputCharacter((unsigned)cp); +} + +void ImGuiIO::AddInputCharactersUTF8(const char* str) +{ + if (!AppAcceptingEvents) + return; + const char* str_end = str + strlen(str); + while (*str != 0) + { + unsigned int c = 0; + str += ImTextCharFromUtf8(&c, str, str_end); + AddInputCharacter(c); + } +} + +// Clear all incoming events. +void ImGuiIO::ClearEventsQueue() +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + g.InputEventsQueue.clear(); +} + +// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. +void ImGuiIO::ClearInputKeys() +{ + ImGuiContext& g = *Ctx; + for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++) + { + if (ImGui::IsMouseKey((ImGuiKey)key)) + continue; + ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN]; + key_data->Down = false; + key_data->DownDuration = -1.0f; + key_data->DownDurationPrev = -1.0f; + } + KeyCtrl = KeyShift = KeyAlt = KeySuper = false; + KeyMods = ImGuiMod_None; + InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters(). +} + +void ImGuiIO::ClearInputMouse() +{ + for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1)) + { + ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN]; + key_data->Down = false; + key_data->DownDuration = -1.0f; + key_data->DownDurationPrev = -1.0f; + } + MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + for (int n = 0; n < IM_COUNTOF(MouseDown); n++) + { + MouseDown[n] = false; + MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f; + } + MouseWheel = MouseWheelH = 0.0f; +} + +static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1) +{ + ImGuiContext& g = *ctx; + for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--) + { + ImGuiInputEvent* e = &g.InputEventsQueue[n]; + if (e->Type != type) + continue; + if (type == ImGuiInputEventType_Key && e->Key.Key != arg) + continue; + if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg) + continue; + return e; + } + return NULL; +} + +// Queue a new key down/up event. +// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) +// - bool down: Is the key down? use false to signify a key release. +// - float analog_value: 0.0f..1.0f +// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE. +// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT. +void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value) +{ + //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); } + IM_ASSERT(Ctx != NULL); + if (key == ImGuiKey_None || !AppAcceptingEvents) + return; + ImGuiContext& g = *Ctx; + IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API. + IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events. + + // MacOS: swap Cmd(Super) and Ctrl + if (g.IO.ConfigMacOSXBehaviors) + { + if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; } + else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; } + else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; } + else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; } + else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; } + else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; } + } + + // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); + const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key); + const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down; + const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue; + if (latest_key_down == down && latest_key_analog == analog_value) + return; + + // Add event + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Key; + e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard; + e.EventId = g.InputEventsNextEventId++; + e.Key.Key = key; + e.Key.Down = down; + e.Key.AnalogValue = analog_value; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down) +{ + if (!AppAcceptingEvents) + return; + AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f); +} + +// [Optional] Call after AddKeyEvent(). +// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices. +// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this. +void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index) +{ + if (key == ImGuiKey_None) + return; + IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512 + IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511 + IM_UNUSED(key); // Yet unused + IM_UNUSED(native_keycode); // Yet unused + IM_UNUSED(native_scancode); // Yet unused + IM_UNUSED(native_legacy_index); // Yet unused +} + +// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. +void ImGuiIO::SetAppAcceptingEvents(bool accepting_events) +{ + AppAcceptingEvents = accepting_events; +} + +// Queue a mouse move event +void ImGuiIO::AddMousePosEvent(float x, float y) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + if (!AppAcceptingEvents) + return; + + // Apply same flooring as UpdateMouseInputs() + ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y); + + // Filter duplicate + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); + const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos; + if (latest_pos.x == pos.x && latest_pos.y == pos.y) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MousePos; + e.Source = ImGuiInputSource_Mouse; + e.EventId = g.InputEventsNextEventId++; + e.MousePos.PosX = pos.x; + e.MousePos.PosY = pos.y; + e.MousePos.MouseSource = g.InputEventsNextMouseSource; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT); + if (!AppAcceptingEvents) + return; + + // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button. + if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick) + { + // Order of both statements matters: this event will still release mouse button 1 + mouse_button = 1; + if (!down) + MouseCtrlLeftAsRightClick = false; + } + + // Filter duplicate + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); + const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button]; + if (latest_button_down == down) + return; + + // On MacOS X: Convert Ctrl(Super)+Left click into Right-click. + // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us. + // - At this point we want from !down to down, so this is handling the initial press. + if (ConfigMacOSXBehaviors && mouse_button == 0 && down) + { + const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); + if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper) + { + IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n"); + MouseCtrlLeftAsRightClick = true; + AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again. + return; + } + } + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseButton; + e.Source = ImGuiInputSource_Mouse; + e.EventId = g.InputEventsNextEventId++; + e.MouseButton.Button = mouse_button; + e.MouseButton.Down = down; + e.MouseButton.MouseSource = g.InputEventsNextMouseSource; + g.InputEventsQueue.push_back(e); +} + +// Queue a mouse wheel event (some mouse/API may only have a Y component) +void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + + // Filter duplicate (unlike most events, wheel values are relative and easy to filter) + if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f)) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseWheel; + e.Source = ImGuiInputSource_Mouse; + e.EventId = g.InputEventsNextEventId++; + e.MouseWheel.WheelX = wheel_x; + e.MouseWheel.WheelY = wheel_y; + e.MouseWheel.MouseSource = g.InputEventsNextMouseSource; + g.InputEventsQueue.push_back(e); +} + +// This is not a real event, the data is latched in order to be stored in actual Mouse events. +// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes. +void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + g.InputEventsNextMouseSource = source; +} + +void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport); + if (!AppAcceptingEvents) + return; + + // Filter duplicate + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport); + const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport; + if (latest_viewport_id == viewport_id) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseViewport; + e.Source = ImGuiInputSource_Mouse; + e.MouseViewport.HoveredViewportID = viewport_id; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddFocusEvent(bool focused) +{ + IM_ASSERT(Ctx != NULL); + ImGuiContext& g = *Ctx; + + // Filter duplicate + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus); + const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost; + if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused)) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Focus; + e.EventId = g.InputEventsNextEventId++; + e.AppFocused.Focused = focused; + g.InputEventsQueue.push_back(e); +} + +ImGuiPlatformIO::ImGuiPlatformIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + Platform_LocaleDecimalPoint = '.'; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +//----------------------------------------------------------------------------- + +ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments) +{ + IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau() + ImVec2 p_last = p1; + ImVec2 p_closest; + float p_closest_dist2 = FLT_MAX; + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step); + ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); + float dist2 = ImLengthSqr(p - p_line); + if (dist2 < p_closest_dist2) + { + p_closest = p_line; + p_closest_dist2 = dist2; + } + p_last = p_current; + } + return p_closest; +} + +// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp +static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) + { + ImVec2 p_current(x4, y4); + ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); + float dist2 = ImLengthSqr(p - p_line); + if (dist2 < p_closest_dist2) + { + p_closest = p_line; + p_closest_dist2 = dist2; + } + p_last = p_current; + } + else if (level < 10) + { + float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; + float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; + float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; + float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; + float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; + float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); + } +} + +// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol +// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically. +ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol) +{ + IM_ASSERT(tess_tol > 0.0f); + ImVec2 p_last = p1; + ImVec2 p_closest; + float p_closest_dist2 = FLT_MAX; + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0); + return p_closest; +} + +ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) +{ + ImVec2 ap = p - a; + ImVec2 ab_dir = b - a; + float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; + if (dot < 0.0f) + return a; + float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; + if (dot > ab_len_sqr) + return b; + return a + ab_dir * dot / ab_len_sqr; +} + +bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return (b1 == b2) && (b2 == b3); +} + +void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) +{ + ImVec2 v0 = b - a; + ImVec2 v1 = c - a; + ImVec2 v2 = p - a; + const float denom = v0.x * v1.y - v1.x * v0.y; + out_v = (v2.x * v1.y - v1.x * v2.y) / denom; + out_w = (v0.x * v2.y - v2.x * v0.y) / denom; + out_u = 1.0f - out_v - out_w; +} + +ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) +{ + ImVec2 proj_ab = ImLineClosestPoint(a, b, p); + ImVec2 proj_bc = ImLineClosestPoint(b, c, p); + ImVec2 proj_ca = ImLineClosestPoint(c, a, p); + float dist2_ab = ImLengthSqr(p - proj_ab); + float dist2_bc = ImLengthSqr(p - proj_bc); + float dist2_ca = ImLengthSqr(p - proj_ca); + float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); + if (m == dist2_ab) + return proj_ab; + if (m == dist2_bc) + return proj_bc; + return proj_ca; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +//----------------------------------------------------------------------------- + +// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more. +int ImStricmp(const char* str1, const char* str2) +{ + int d; + while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; } + return d; +} + +int ImStrnicmp(const char* str1, const char* str2, size_t count) +{ + int d = 0; + while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + return d; +} + +void ImStrncpy(char* dst, const char* src, size_t count) +{ + if (count < 1) + return; + if (count > 1) + strncpy(dst, src, count - 1); // FIXME-OPT: strncpy not only doesn't guarantee 0-termination, it also always writes the whole array + dst[count - 1] = 0; +} + +char* ImStrdup(const char* str) +{ + size_t len = ImStrlen(str); + void* buf = IM_ALLOC(len + 1); + return (char*)memcpy(buf, (const void*)str, len + 1); +} + +void* ImMemdup(const void* src, size_t size) +{ + void* dst = IM_ALLOC(size); + return memcpy(dst, src, size); +} + +char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) +{ + size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1; + size_t src_size = ImStrlen(src) + 1; + if (dst_buf_size < src_size) + { + IM_FREE(dst); + dst = (char*)IM_ALLOC(src_size); + if (p_dst_size) + *p_dst_size = src_size; + } + return (char*)memcpy(dst, (const void*)src, src_size); +} + +const char* ImStrchrRange(const char* str, const char* str_end, char c) +{ + const char* p = (const char*)ImMemchr(str, (int)c, str_end - str); + return p; +} + +int ImStrlenW(const ImWchar* str) +{ + //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit + int n = 0; + while (*str++) n++; + return n; +} + +// Find end-of-line. Return pointer will point to either first \n, either str_end. +const char* ImStreolRange(const char* str, const char* str_end) +{ + const char* p = (const char*)ImMemchr(str, '\n', str_end - str); + return p ? p : str_end; +} + +const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line +{ + IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin)); + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) +{ + if (!needle_end) + needle_end = needle + ImStrlen(needle); + + const char un0 = (char)ImToUpper(*needle); + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) + { + if (ImToUpper(*haystack) == un0) + { + const char* b = needle + 1; + for (const char* a = haystack + 1; b < needle_end; a++, b++) + if (ImToUpper(*a) != ImToUpper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + +// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. +void ImStrTrimBlanks(char* buf) +{ + char* p = buf; + while (p[0] == ' ' || p[0] == '\t') // Leading blanks + p++; + char* p_start = p; + while (*p != 0) // Find end of string + p++; + while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks + p--; + if (p_start != buf) // Copy memory if we had leading blanks + memmove(buf, p_start, p - p_start); + buf[p - p_start] = 0; // Zero terminate +} + +const char* ImStrSkipBlank(const char* str) +{ + while (str[0] == ' ' || str[0] == '\t') + str++; + return str; +} + +// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +// B) When buf==NULL vsnprintf() will return the output size. +#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + +// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h) +// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS +// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are +// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.) +#ifdef IMGUI_USE_STB_SPRINTF +#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION +#define STB_SPRINTF_IMPLEMENTATION +#endif +#ifdef IMGUI_STB_SPRINTF_FILENAME +#include IMGUI_STB_SPRINTF_FILENAME +#else +#include "stb_sprintf.h" +#endif +#endif // #ifdef IMGUI_USE_STB_SPRINTF + +#if defined(_MSC_VER) && !defined(vsnprintf) +#define vsnprintf _vsnprintf +#endif + +int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); +#ifdef IMGUI_USE_STB_SPRINTF + int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); +#else + int w = vsnprintf(buf, buf_size, fmt, args); +#endif + va_end(args); + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) +{ +#ifdef IMGUI_USE_STB_SPRINTF + int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); +#else + int w = vsnprintf(buf, buf_size, fmt, args); +#endif + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} +#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + +void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args); + va_end(args); +} + +// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller) +// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g. +// ImGuiTempBufferToken token; +// ImFormatStringToTempBuffer(token, ...); +void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + { + const char* buf = va_arg(args, const char*); // Skip formatting when using "%s" + if (buf == NULL) + buf = "(null)"; + *out_buf = buf; + if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); } + } + else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0) + { + int buf_len = va_arg(args, int); // Skip formatting when using "%.*s" + const char* buf = va_arg(args, const char*); + if (buf == NULL) + { + buf = "(null)"; + buf_len = ImMin(buf_len, 6); + } + *out_buf = buf; + *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it. + } + else + { + int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args); + *out_buf = g.TempBuffer.Data; + if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; } + } +} + +#ifndef IMGUI_ENABLE_SSE4_2_CRC +// CRC32 needs a 1KB lookup table (not cache friendly) +// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily: +// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. +static const ImU32 GCrc32LookupTable[256] = +{ +#ifdef IMGUI_USE_LEGACY_CRC32_ADLER + // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data. + 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91, + 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5, + 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59, + 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D, + 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01, + 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65, + 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9, + 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD, + 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1, + 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5, + 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79, + 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D, + 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21, + 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45, + 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9, + 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D, +#else + // CRC32c table compatible with SSE 4.2 instructions + 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24, + 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B, + 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA, + 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595, + 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198, + 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7, + 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46, + 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829, + 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C, + 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033, + 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982, + 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED, + 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0, + 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F, + 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E, + 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351 +#endif +}; +#endif + +// Known size hash +// It is ok to call ImHashData on a string with known length but the ### operator won't be supported. +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed) +{ + ImU32 crc = ~seed; + const unsigned char* data = (const unsigned char*)data_p; + const unsigned char *data_end = (const unsigned char*)data_p + data_size; +#ifndef IMGUI_ENABLE_SSE4_2_CRC + const ImU32* crc32_lut = GCrc32LookupTable; + while (data < data_end) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++]; + return ~crc; +#else + while (data + 4 <= data_end) + { + crc = _mm_crc32_u32(crc, *(ImU32*)data); + data += 4; + } + while (data < data_end) + crc = _mm_crc32_u8(crc, *data++); + return ~crc; +#endif +} + +// Zero-terminated string hash, with support for ### to reset back to seed value. +// e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) +{ + seed = ~seed; + ImU32 crc = seed; + const unsigned char* data = (const unsigned char*)data_p; +#ifndef IMGUI_ENABLE_SSE4_2_CRC + const ImU32* crc32_lut = GCrc32LookupTable; +#endif + if (data_size != 0) + { + while (data_size-- > 0) + { + unsigned char c = *data++; + if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') + { + crc = seed; + data += 2; + data_size -= 2; + continue; + } +#ifndef IMGUI_ENABLE_SSE4_2_CRC + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; +#else + crc = _mm_crc32_u8(crc, c); +#endif + } + } + else + { + while (unsigned char c = *data++) + { + if (c == '#' && data[0] == '#' && data[1] == '#') + { + crc = seed; + data += 2; + continue; + } +#ifndef IMGUI_ENABLE_SSE4_2_CRC + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; +#else + crc = _mm_crc32_u8(crc, c); +#endif + } + } + return ~crc; +} + +// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() +// FIXME-OPT: This is not designed to be optimal. Use with care. +const char* ImHashSkipUncontributingPrefix(const char* label) +{ + const char* result = label; + while (unsigned char c = *label++) + if (c == '#' && label[0] == '#' && label[1] == '#') + result = label + 2; + return result; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (File functions) +//----------------------------------------------------------------------------- + +// Default file functions +#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + +ImFileHandle ImFileOpen(const char* filename, const char* mode) +{ +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__))) + // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. + // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32! + const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0); + const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0); + + // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator. + // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314). + wchar_t local_temp_stack[FILENAME_MAX]; + ImVector local_temp_heap; + if (filename_wsize + mode_wsize > IM_COUNTOF(local_temp_stack)) + local_temp_heap.resize(filename_wsize + mode_wsize); + wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack; + wchar_t* mode_wbuf = filename_wbuf + filename_wsize; + ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize); + return ::_wfopen(filename_wbuf, mode_wbuf); +#else + return fopen(filename, mode); +#endif +} + +// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way. +bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; } +ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; } +ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); } +ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); } +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + +// Helper: Load file content into memory +// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() +// This can't really be used with "rt" because fseek size won't match read size. +void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes) +{ + IM_ASSERT(filename && mode); + if (out_file_size) + *out_file_size = 0; + + ImFileHandle f; + if ((f = ImFileOpen(filename, mode)) == NULL) + return NULL; + + size_t file_size = (size_t)ImFileGetSize(f); + if (file_size == (size_t)-1) + { + ImFileClose(f); + return NULL; + } + + void* file_data = IM_ALLOC(file_size + padding_bytes); + if (file_data == NULL) + { + ImFileClose(f); + return NULL; + } + if (ImFileRead(file_data, 1, file_size, f) != file_size) + { + ImFileClose(f); + IM_FREE(file_data); + return NULL; + } + if (padding_bytes > 0) + memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes); + + ImFileClose(f); + if (out_file_size) + *out_file_size = file_size; + + return file_data; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +//----------------------------------------------------------------------------- + +IM_MSVC_RUNTIME_CHECKS_OFF + +// Convert UTF-8 to 32-bit character, process single character input. +// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) +{ + static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; + static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; + static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 }; + static const int shiftc[] = { 0, 18, 12, 6, 0 }; + static const int shifte[] = { 0, 6, 4, 2, 0 }; + int len = lengths[*(const unsigned char*)in_text >> 3]; + int wanted = len + (len ? 0 : 1); + + // IMPORTANT: if in_text_end == NULL it assume we have enough space! + if (in_text_end == NULL) + in_text_end = in_text + wanted; // Max length, nulls will be taken into account. + + // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + // so it is fast even with excessive branching. + unsigned char s[4]; + s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; + s[1] = in_text + 1 < in_text_end ? in_text[1] : 0; + s[2] = in_text + 2 < in_text_end ? in_text[2] : 0; + s[3] = in_text + 3 < in_text_end ? in_text[3] : 0; + + // Assume a four-byte character and load four bytes. Unused bits are shifted out. + *out_char = (uint32_t)(s[0] & masks[len]) << 18; + *out_char |= (uint32_t)(s[1] & 0x3f) << 12; + *out_char |= (uint32_t)(s[2] & 0x3f) << 6; + *out_char |= (uint32_t)(s[3] & 0x3f) << 0; + *out_char >>= shiftc[len]; + + // Accumulate the various error conditions. + int e = 0; + e = (*out_char < mins[len]) << 6; // non-canonical encoding + e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? + e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve) + e |= (s[1] & 0xc0) >> 2; + e |= (s[2] & 0xc0) >> 4; + e |= (s[3] ) >> 6; + e ^= 0x2a; // top two bits of each tail byte correct? + e >>= shifte[len]; + + if (e) + { + // No bytes are consumed when *in_text == 0 || in_text == in_text_end. + // One byte is consumed in case of invalid first byte of in_text. + // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. + wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]); + *out_char = IM_UNICODE_CODEPOINT_INVALID; + } + + return wanted; +} + +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } + if (c <= 0x10FFFF) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + // Invalid code point, the max unicode is 0x10FFFF + return 0; +} + +int ImTextCharToUtf8(char out_buf[5], unsigned int c) +{ + int count = ImTextCharToUtf8_inline(out_buf, 5, c); + out_buf[count] = 0; + return count; +} + +// Not optimal but we very rarely use this function. +int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) +{ + unsigned int unused = 0; + return ImTextCharFromUtf8(&unused, in_text, in_text_end); +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c < 0x10000) return 3; + if (c <= 0x10FFFF) return 4; + return 3; +} + +int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_p = out_buf; + const char* buf_end = out_buf + out_buf_size; + while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_p++ = (char)c; + else + buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c); + } + *buf_p = 0; + return (int)(buf_p - out_buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_p) +{ + while (in_p > in_text_start) + { + in_p--; + if ((*in_p & 0xC0) != 0x80) + return in_p; + } + return in_text_start; +} + +const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const char* in_text_end, const char* in_p) +{ + if (in_text_start == in_p) + return in_text_start; + const char* prev = ImTextFindPreviousUtf8Codepoint(in_text_start, in_p); + unsigned int prev_c; + int prev_c_len = ImTextCharFromUtf8(&prev_c, prev, in_text_end); + if (prev_c != IM_UNICODE_CODEPOINT_INVALID && prev_c_len <= (int)(in_p - prev)) + return in_p; + return prev; +} + +int ImTextCountLines(const char* in_text, const char* in_text_end) +{ + if (in_text_end == NULL) + in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now. + int count = 0; + while (in_text < in_text_end) + { + const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text); + in_text = line_end ? line_end + 1 : in_text_end; + count++; + } + return count; +} + +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (Color functions) +// Note: The Convert functions are early design which are not consistent with other API. +//----------------------------------------------------------------------------- + +IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b) +{ + float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; + int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); + int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); + int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); + return IM_COL32(r, g, b, 0xFF); +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f / 255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); +} + +ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) +{ + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; + return out; +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) +{ + float K = 0.f; + if (g < b) + { + ImSwap(g, b); + K = -1.f; + } + if (r < g) + { + ImSwap(r, g); + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = ImFmod(h, 1.0f) / (60.0f / 360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: out_r = v; out_g = t; out_b = p; break; + case 1: out_r = q; out_g = v; out_b = p; break; + case 2: out_r = p; out_g = v; out_b = t; break; + case 3: out_r = p; out_g = q; out_b = v; break; + case 4: out_r = t; out_g = p; out_b = v; break; + case 5: default: out_r = v; out_g = p; out_b = q; break; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStorage +// Helper: Key->value storage +//----------------------------------------------------------------------------- + +// std::lower_bound but without the bullshit +ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key) +{ + ImGuiStoragePair* in_p = in_begin; + for (size_t count = (size_t)(in_end - in_p); count > 0; ) + { + size_t count2 = count >> 1; + ImGuiStoragePair* mid = in_p + count2; + if (mid->key < key) + { + in_p = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return in_p; +} + +IM_MSVC_RUNTIME_CHECKS_OFF +static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) +{ + // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. + ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key; + ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key; + return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0); +} + +// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. +void ImGuiStorage::BuildSortByKey() +{ + ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID); +} + +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const +{ + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); + if (it == Data.Data + Data.Size || it->key != key) + return default_val; + return it->val_i; +} + +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const +{ + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); + if (it == Data.Data + Data.Size || it->key != key) + return default_val; + return it->val_f; +} + +void* ImGuiStorage::GetVoidPtr(ImGuiID key) const +{ + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); + if (it == Data.Data + Data.Size || it->key != key) + return NULL; + return it->val_p; +} + +// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. +int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_i; +} + +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + +float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_f; +} + +void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + Data.insert(it, ImGuiStoragePair(key, val)); + else + it->val_i = val; +} + +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + Data.insert(it, ImGuiStoragePair(key, val)); + else + it->val_f = val; +} + +void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) +{ + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); + if (it == Data.Data + Data.Size || it->key != key) + Data.insert(it, ImGuiStoragePair(key, val)); + else + it->val_p = val; +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (int i = 0; i < Data.Size; i++) + Data[i].val_i = v; +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextFilter +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 +{ + InputBuf[0] = 0; + CountGrep = 0; + if (default_filter) + { + ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); + Build(); + } +} + +bool ImGuiTextFilter::Draw(const char* label, float width) +{ + if (width != 0.0f) + ImGui::SetNextItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_COUNTOF(InputBuf)); + if (value_changed) + Build(); + return value_changed; +} + +void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector* out) const +{ + out->resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out->push_back(ImGuiTextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out->push_back(ImGuiTextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); + input_range.split(',', &Filters); + + CountGrep = 0; + for (ImGuiTextRange& f : Filters) + { + while (f.b < f.e && ImCharIsBlankA(f.b[0])) + f.b++; + while (f.e > f.b && ImCharIsBlankA(f.e[-1])) + f.e--; + if (f.empty()) + continue; + if (f.b[0] != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const +{ + if (Filters.Size == 0) + return true; + + if (text == NULL) + text = text_end = ""; + + for (const ImGuiTextRange& f : Filters) + { + if (f.b == f.e) + continue; + if (f.b[0] == '-') + { + // Subtract + if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.b, f.e) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextBuffer, ImGuiTextIndex +//----------------------------------------------------------------------------- + +// On some platform vsnprintf() takes va_list by reference and modifies it. +// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. +#ifndef va_copy +#if defined(__GNUC__) || defined(__clang__) +#define va_copy(dest, src) __builtin_va_copy(dest, src) +#else +#define va_copy(dest, src) (dest = src) +#endif +#endif + +char ImGuiTextBuffer::EmptyString[1] = { 0 }; + +void ImGuiTextBuffer::append(const char* str, const char* str_end) +{ + int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str); + + // Add zero-terminator the first time + const int write_off = (Buf.Size != 0) ? Buf.Size : 1; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int new_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); + } + + Buf.resize(needed_sz); + memcpy(&Buf[write_off - 1], str, (size_t)len); + Buf[write_off - 1 + len] = 0; +} + +void ImGuiTextBuffer::appendf(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + appendfv(fmt, args); + va_end(args); +} + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + if (len <= 0) + { + va_end(args_copy); + return; + } + + // Add zero-terminator the first time + const int write_off = (Buf.Size != 0) ? Buf.Size : 1; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int new_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); + } + + Buf.resize(needed_sz); + ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy); + va_end(args_copy); +} + +IM_MSVC_RUNTIME_CHECKS_OFF +void ImGuiTextIndex::append(const char* base, int old_size, int new_size) +{ + IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset); + if (old_size == new_size) + return; + if (EndOffset == 0 || base[EndOffset - 1] == '\n') + Offsets.push_back(EndOffset); + const char* base_end = base + new_size; + for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; ) + if (++p < base_end) // Don't push a trailing offset on last \n + Offsets.push_back((int)(intptr_t)(p - base)); + EndOffset = ImMax(EndOffset, new_size); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiListClipper +//----------------------------------------------------------------------------- + +// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. +static bool GetSkipItemForListClipping() +{ + ImGuiContext& g = *GImGui; + return g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems; +} + +static void ImGuiListClipper_SortAndFuseRanges(ImVector& ranges, int offset = 0) +{ + if (ranges.Size - offset <= 1) + return; + + // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries) + for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end) + for (int i = offset; i < sort_end + offset; ++i) + if (ranges[i].Min > ranges[i + 1].Min) + ImSwap(ranges[i], ranges[i + 1]); + + // Now fuse ranges together as much as possible. + for (int i = 1 + offset; i < ranges.Size; i++) + { + IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert); + if (ranges[i - 1].Max < ranges[i].Min) + continue; + ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min); + ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max); + ranges.erase(ranges.Data + i); + i--; + } +} + +static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clipper, float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek? + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float off_y = pos_y - window->DC.CursorPos.y; + window->DC.CursorPos.y = pos_y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (ImGuiOldColumns* columns = window->DC.CurrentColumns) + columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly + if (ImGuiTable* table = g.CurrentTable) + { + if (table->IsInsideRow) + ImGui::TableEndRow(table); + const int row_increase = (int)((off_y / line_height) + 0.5f); + if (row_increase > 0 && (clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886. + { + table->CurrentRow += row_increase; + table->RowBgColorCounter += row_increase; + } + table->RowPosY2 = window->DC.CursorPos.y; + } +} + +ImGuiListClipper::ImGuiListClipper() +{ + memset(this, 0, sizeof(*this)); +} + +ImGuiListClipper::~ImGuiListClipper() +{ + End(); +} + +void ImGuiListClipper::Begin(int items_count, float items_height) +{ + if (Ctx == NULL) + Ctx = ImGui::GetCurrentContext(); + + ImGuiContext& g = *Ctx; + ImGuiWindow* window = g.CurrentWindow; + IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name); + + if (ImGuiTable* table = g.CurrentTable) + if (table->IsInsideRow) + ImGui::TableEndRow(table); + + StartPosY = window->DC.CursorPos.y; + ItemsHeight = items_height; + ItemsCount = items_count; + DisplayStart = -1; + DisplayEnd = 0; + + // Acquire temporary buffer + if (++g.ClipperTempDataStacked > g.ClipperTempData.Size) + g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData()); + ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1]; + data->Reset(this); + data->LossynessOffset = window->DC.CursorStartPosLossyness.y; + TempData = data; + StartSeekOffsetY = data->LossynessOffset; +} + +void ImGuiListClipper::End() +{ + if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData) + { + // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user. + ImGuiContext& g = *Ctx; + IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name); + if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0) + SeekCursorForItem(ItemsCount); + + // Restore temporary buffer and fix back pointers which may be invalidated when nesting + IM_ASSERT(data->ListClipper == this); + data->StepNo = data->Ranges.Size; + if (--g.ClipperTempDataStacked > 0) + { + data = &g.ClipperTempData[g.ClipperTempDataStacked - 1]; + data->ListClipper->TempData = data; + } + TempData = NULL; + } + ItemsCount = -1; +} + +void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end) +{ + ImGuiListClipperData* data = (ImGuiListClipperData*)TempData; + IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet. + IM_ASSERT(item_begin <= item_end); + if (item_begin < item_end) + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end)); +} + +// This is already called while stepping. +// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand. +void ImGuiListClipper::SeekCursorForItem(int item_n) +{ + // - Perform the add and multiply with double to allow seeking through larger ranges. + // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight). + // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done. + float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight); + ImGuiListClipper_SeekCursorAndSetupPrevLine(this, pos_y, ItemsHeight); +} + +static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) +{ + ImGuiContext& g = *clipper->Ctx; + ImGuiWindow* window = g.CurrentWindow; + ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData; + IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?"); + + ImGuiTable* table = g.CurrentTable; + if (table && table->IsInsideRow) + ImGui::TableEndRow(table); + + // No items + if (clipper->ItemsCount == 0 || GetSkipItemForListClipping()) + return false; + + // While we are in frozen row state, keep displaying items one by one, unclipped + // FIXME: Could be stored as a table-agnostic state. + if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows) + { + clipper->DisplayStart = data->ItemsFrozen; + clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount); + if (clipper->DisplayStart < clipper->DisplayEnd) + data->ItemsFrozen++; + return true; + } + + // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) + bool calc_clipping = false; + if (data->StepNo == 0) + { + clipper->StartPosY = window->DC.CursorPos.y; + if (clipper->ItemsHeight <= 0.0f) + { + // Submit the first item (or range) so we can measure its height (generally the first range is 0..1) + data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1)); + clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen); + clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount); + data->StepNo = 1; + return true; + } + calc_clipping = true; // If on the first step with known item height, calculate clipping. + } + + // Step 1: Let the clipper infer height from first range + if (clipper->ItemsHeight <= 0.0f) + { + IM_ASSERT(data->StepNo == 1); + if (table) + IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y); + + bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); + if (affected_by_floating_point_precision) + { + // Mitigation/hack for very large range: assume last time height constitute line height. + clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries. + window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight); + } + else + { + clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart); + } + if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode. + return false; + IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); + calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards. + } + + // Step 0 or 1: Calculate the actual ranges of visible elements. + const int already_submitted = clipper->DisplayEnd; + if (calc_clipping) + { + // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done + clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight; + + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount)); + } + else + { + // Add range selected to be included for navigation + const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + const int nav_off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; + const int nav_off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; + if (is_nav_request) + { + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, nav_off_min, nav_off_max)); + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, nav_off_min, nav_off_max)); + } + if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1) + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount)); + + // Add focused/active item + ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]); + if (g.NavId != 0 && window->NavLastIds[0] == g.NavId) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)); + + float min_y = window->ClipRect.Min.y; + float max_y = window->ClipRect.Max.y; + + // Add box selection range + ImGuiBoxSelectState* bs = &g.BoxSelectState; + if (bs->IsActive && bs->Window == window) + { + // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + // As a workaround we currently half ItemSpacing worth on each side. + min_y -= g.Style.ItemSpacing.y; + max_y += g.Style.ItemSpacing.y; + + // Box-select on 2D area requires different clipping. + if (bs->UnclipMode) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0)); + } + + // Add main visible range + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, nav_off_min, nav_off_max)); + } + + // Convert position ranges to item index ranges + // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping. + // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list, + // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted. + for (ImGuiListClipperRange& range : data->Ranges) + if (range.PosToIndexConvert) + { + int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight); + int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f); + range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1); + range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount); + range.PosToIndexConvert = false; + } + ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo); + } + + // Step 0+ (if item height is given in advance) or 1+: Display the next range in line. + while (data->StepNo < data->Ranges.Size) + { + clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted); + clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount); + data->StepNo++; + if (clipper->DisplayStart >= clipper->DisplayEnd) + continue; + if (clipper->DisplayStart > already_submitted) + clipper->SeekCursorForItem(clipper->DisplayStart); + return true; + } + + // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + // Advance the cursor to the end of the list and then returns 'false' to end the loop. + if (clipper->ItemsCount < INT_MAX) + clipper->SeekCursorForItem(clipper->ItemsCount); + + return false; +} + +bool ImGuiListClipper::Step() +{ + ImGuiContext& g = *Ctx; + bool need_items_height = (ItemsHeight <= 0.0f); + bool ret = ImGuiListClipper_StepInternal(this); + if (ret && (DisplayStart >= DisplayEnd)) + ret = false; + if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false) + IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n"); + if (need_items_height && ItemsHeight > 0.0f) + IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight); + if (ret) + { + IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd); + } + else + { + IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n"); + End(); + } + return ret; +} + +// Generic helper, equivalent to old ImGui::CalcListClipping() but statelesss +void ImGui::CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end) +{ + *out_visible_start = ImMax((int)((clip_rect.Min.y - pos.y) / items_height), 0); + *out_visible_end = ImMax((int)ImCeil((clip_rect.Max.y - pos.y) / items_height), *out_visible_start); +} + +//----------------------------------------------------------------------------- +// [SECTION] STYLING +//----------------------------------------------------------------------------- + +ImGuiStyle& ImGui::GetStyle() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + return GImGui->Style; +} + +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImGuiStyle& style = GImGui->Style; + ImVec4 c = style.Colors[idx]; + c.w *= style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4& col) +{ + ImGuiStyle& style = GImGui->Style; + ImVec4 c = col; + c.w *= style.Alpha; + return ColorConvertFloat4ToU32(c); +} + +const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) +{ + ImGuiStyle& style = GImGui->Style; + return style.Colors[idx]; +} + +ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul) +{ + ImGuiStyle& style = GImGui->Style; + alpha_mul *= style.Alpha; + if (alpha_mul >= 1.0f) + return col; + ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; + a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. + return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); +} + +// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 +void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorStack.push_back(backup); + if (g.DebugFlashStyleColorIdx != idx) + g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) +{ + ImGuiContext& g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorStack.push_back(backup); + if (g.DebugFlashStyleColorIdx != idx) + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiContext& g = *GImGui; + if (g.ColorStack.Size < count) + { + IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!"); + count = g.ColorStack.Size; + } + while (count > 0) + { + ImGuiColorMod& backup = g.ColorStack.back(); + g.Style.Colors[backup.Col] = backup.BackupValue; + g.ColorStack.pop_back(); + count--; + } +} + +static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] = +{ + ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline, ImGuiCol_UnsavedMarker, +}; + +static const ImGuiStyleVarInfo GStyleVarsInfo[] = +{ + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageRounding) }, // ImGuiStyleVar_ImageRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize +}; + +const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) +{ + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); + IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT); + return &GStyleVarsInfo[idx]; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 1, "Calling PushStyleVar() variant with wrong type!"); + float* pvar = (float*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; +} + +void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + pvar->x = val_x; +} + +void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + pvar->y = val_y; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiContext& g = *GImGui; + if (g.StyleVarStack.Size < count) + { + IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!"); + count = g.StyleVarStack.Size; + } + while (count > 0) + { + // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. + ImGuiStyleMod& backup = g.StyleVarStack.back(); + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx); + void* data = var_info->GetVarPtr(&g.Style); + if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } + else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } + g.StyleVarStack.pop_back(); + count--; + } +} + +const char* ImGui::GetStyleColorName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; + case ImGuiCol_WindowBg: return "WindowBg"; + case ImGuiCol_ChildBg: return "ChildBg"; + case ImGuiCol_PopupBg: return "PopupBg"; + case ImGuiCol_Border: return "Border"; + case ImGuiCol_BorderShadow: return "BorderShadow"; + case ImGuiCol_FrameBg: return "FrameBg"; + case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; + case ImGuiCol_FrameBgActive: return "FrameBgActive"; + case ImGuiCol_TitleBg: return "TitleBg"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; + case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; + case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; + case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; + case ImGuiCol_CheckMark: return "CheckMark"; + case ImGuiCol_SliderGrab: return "SliderGrab"; + case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; + case ImGuiCol_Button: return "Button"; + case ImGuiCol_ButtonHovered: return "ButtonHovered"; + case ImGuiCol_ButtonActive: return "ButtonActive"; + case ImGuiCol_Header: return "Header"; + case ImGuiCol_HeaderHovered: return "HeaderHovered"; + case ImGuiCol_HeaderActive: return "HeaderActive"; + case ImGuiCol_Separator: return "Separator"; + case ImGuiCol_SeparatorHovered: return "SeparatorHovered"; + case ImGuiCol_SeparatorActive: return "SeparatorActive"; + case ImGuiCol_ResizeGrip: return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_InputTextCursor: return "InputTextCursor"; + case ImGuiCol_TabHovered: return "TabHovered"; + case ImGuiCol_Tab: return "Tab"; + case ImGuiCol_TabSelected: return "TabSelected"; + case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline"; + case ImGuiCol_TabDimmed: return "TabDimmed"; + case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected"; + case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline"; + case ImGuiCol_DockingPreview: return "DockingPreview"; + case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TableHeaderBg: return "TableHeaderBg"; + case ImGuiCol_TableBorderStrong: return "TableBorderStrong"; + case ImGuiCol_TableBorderLight: return "TableBorderLight"; + case ImGuiCol_TableRowBg: return "TableRowBg"; + case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; + case ImGuiCol_TextLink: return "TextLink"; + case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_TreeLines: return "TreeLines"; + case ImGuiCol_DragDropTarget: return "DragDropTarget"; + case ImGuiCol_DragDropTargetBg: return "DragDropTargetBg"; + case ImGuiCol_UnsavedMarker: return "UnsavedMarker"; + case ImGuiCol_NavCursor: return "NavCursor"; + case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; + case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; + case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; + } + IM_ASSERT(0); + return "Unknown"; +} + +//----------------------------------------------------------------------------- +// [SECTION] RENDER HELPERS +// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, +// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. +// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. +//----------------------------------------------------------------------------- + +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) +{ + const char* text_display_end = text; + if (!text_end) + text_end = (const char*)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Internal ImGui functions to render text +// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + ImStrlen(text); // FIXME-OPT + text_display_end = text_end; + } + + if (text != text_display_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); + } +} + +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (!text_end) + text_end = text + ImStrlen(text); // FIXME-OPT + + if (text != text_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_end); + } +} + +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList. +// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take +// better advantage of the render function taking size into account for coarse clipping. +void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) +{ + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + + const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); + + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } +} + +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) +{ + // Hide anything after a '##' string + const char* text_display_end = FindRenderedTextEnd(text, text_end); + const int text_len = (int)(text_display_end - text); + if (text_len == 0) + return; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect); + if (g.LogEnabled) + LogRenderedText(&pos_min, text, text_display_end); +} + +// Another overly complex function until we reorganize everything into a nice all-in-one helper. +// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it. +// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. +// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users. +void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) +{ + ImGuiContext& g = *GImGui; + if (text_end_full == NULL) + text_end_full = FindRenderedTextEnd(text); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); + + //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255)); + //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255)); + + // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels. + if (text_size.x > pos_max.x - pos_min.x) + { + // Hello wo... + // | | | + // min max ellipsis_max + // <-> this is generally some padding value + + ImFont* font = draw_list->_Data->Font; + const float font_size = draw_list->_Data->FontSize; + const float font_scale = draw_list->_Data->FontScale; + const char* text_end_ellipsis = NULL; + ImFontBaked* baked = font->GetFontBaked(font_size); + const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale; + + // We can now claim the space between pos_max.x and ellipsis_max.x + const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f); + float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; + while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) + { + // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) + text_end_ellipsis--; + text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte + } + + // Render text, render ellipsis + RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y); + ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y)); + font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); + } + else + { + RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + } + + if (g.LogEnabled) + LogRenderedText(&pos_min, text, text_end_full); +} + +// Render a rectangle shaped with optional rounding and borders +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + const float border_size = g.Style.FrameBorderSize; + if (borders && border_size > 0.0f) + { + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); + } +} + +void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const float border_size = g.Style.FrameBorderSize; + if (border_size > 0.0f) + { + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); + } +} + +void ImGui::RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding) +{ + if (bb.Min.x + 1 >= bb.Max.x) + return; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + RenderRectFilledInRangeH(window->DrawList, bb, col, bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding); +} + +void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags) +{ + ImGuiContext& g = *GImGui; + if (id != g.NavId) + return; + if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw)) + return; + if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav)) + return; + ImGuiWindow* window = g.CurrentWindow; + if (window->DC.NavHideHighlightOneFrame) + return; + + float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; + ImRect display_rect = bb; + display_rect.ClipWith(window->ClipRect); + const float thickness = 2.0f; + if (flags & ImGuiNavRenderCursorFlags_Compact) + { + window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness); + } + else + { + const float distance = 3.0f + thickness * 0.5f; + display_rect.Expand(ImVec2(distance, distance)); + bool fully_visible = window->ClipRect.Contains(display_rect); + if (!fully_visible) + window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); + window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness); + if (!fully_visible) + window->DrawList->PopClipRect(); + } +} + +void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow) +{ + ImGuiContext& g = *GImGui; + if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values. + mouse_cursor = ImGuiMouseCursor_Arrow; + ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas; + for (ImGuiViewportP* viewport : g.Viewports) + { + // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. + ImVec2 offset, size, uv[4]; + if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2])) + continue; + const ImVec2 pos = base_pos - offset; + const float scale = base_scale * viewport->DpiScale; + if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) + continue; + ImDrawList* draw_list = GetForegroundDrawList(viewport); + ImTextureRef tex_ref = font_atlas->TexRef; + draw_list->PushTexture(tex_ref); + draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill); + if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress) + { + float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI); + float a_max = a_min + IM_PI * 1.65f; + draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max); + draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale); + } + draw_list->PopTexture(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] INITIALIZATION, SHUTDOWN +//----------------------------------------------------------------------------- + +// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext* ImGui::GetCurrentContext() +{ + return GImGui; +} + +void ImGui::SetCurrentContext(ImGuiContext* ctx) +{ +#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC + IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. +#else + GImGui = ctx; +#endif +} + +void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data) +{ + GImAllocatorAllocFunc = alloc_func; + GImAllocatorFreeFunc = free_func; + GImAllocatorUserData = user_data; +} + +// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space) +void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data) +{ + *p_alloc_func = GImAllocatorAllocFunc; + *p_free_func = GImAllocatorFreeFunc; + *p_user_data = GImAllocatorUserData; +} + +ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) +{ + ImGuiContext* prev_ctx = GetCurrentContext(); + ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); + SetCurrentContext(ctx); + Initialize(); + if (prev_ctx != NULL) + SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one. + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext* ctx) +{ + ImGuiContext* prev_ctx = GetCurrentContext(); + if (ctx == NULL) //-V1051 + ctx = prev_ctx; + SetCurrentContext(ctx); + Shutdown(); + SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL); + IM_DELETE(ctx); +} + +// IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation. +static const ImGuiLocEntry GLocalizationEntriesEnUS[] = +{ + { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, + { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" }, + { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" }, + { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" }, + { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" }, + { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, + { ImGuiLocKey_WindowingPopup, "(Popup)" }, + { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, + { ImGuiLocKey_OpenLink_s, "Open '%s'" }, + { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, + { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" }, + { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." }, + { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." }, +}; + +ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) +{ + IO.Ctx = this; + InputTextState.Ctx = this; + + Initialized = false; + WithinFrameScope = WithinFrameScopeWithImplicitWindow = false; + TestEngineHookItems = false; + FrameCount = 0; + FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1; + Time = 0.0f; + memset(ContextName, 0, sizeof(ContextName)); + ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None; + + Font = NULL; + FontBaked = NULL; + FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f; + FontRasterizerDensity = 1.0f; + IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + if (shared_font_atlas == NULL) + IO.Fonts->OwnerContext = this; + WithinEndChildID = 0; + TestEngine = NULL; + + InputEventsNextMouseSource = ImGuiMouseSource_Mouse; + InputEventsNextEventId = 1; + + WindowsActiveCount = 0; + WindowsBorderHoverPadding = 0.0f; + CurrentWindow = NULL; + HoveredWindow = NULL; + HoveredWindowUnderMovingWindow = NULL; + HoveredWindowBeforeClear = NULL; + MovingWindow = NULL; + WheelingWindow = NULL; + WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1; + WheelingWindowReleaseTimer = 0.0f; + + DebugDrawIdConflictsId = 0; + DebugHookIdInfoId = 0; + HoveredId = HoveredIdPreviousFrame = 0; + HoveredIdPreviousFrameItemCount = 0; + HoveredIdAllowOverlap = false; + HoveredIdIsDisabled = false; + HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; + ItemUnclipByLog = false; + ActiveId = 0; + ActiveIdIsAlive = 0; + ActiveIdTimer = 0.0f; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdNoClearOnFocusLoss = false; + ActiveIdHasBeenPressedBefore = false; + ActiveIdHasBeenEditedBefore = false; + ActiveIdHasBeenEditedThisFrame = false; + ActiveIdFromShortcut = false; + ActiveIdClickOffset = ImVec2(-1, -1); + ActiveIdSource = ImGuiInputSource_None; + ActiveIdWindow = NULL; + ActiveIdMouseButton = -1; + ActiveIdDisabledId = 0; + ActiveIdPreviousFrame = 0; + memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData)); + memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation)); + LastActiveId = 0; + LastActiveIdTimer = 0.0f; + + LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0; + + ActiveIdUsingNavDirMask = 0x00; + ActiveIdUsingAllKeyboardKeys = false; + + CurrentFocusScopeId = 0; + CurrentItemFlags = ImGuiItemFlags_None; + DebugShowGroupRects = false; + GcCompactAll = false; + + CurrentViewport = NULL; + MouseViewport = MouseLastHoveredViewport = NULL; + PlatformLastFocusedViewportId = 0; + ViewportCreatedCount = PlatformWindowsCreatedCount = 0; + ViewportFocusedStampCount = 0; + + NavCursorVisible = false; + NavHighlightItemUnderNav = false; + NavMousePosDirty = false; + NavIdIsAlive = false; + NavId = 0; + NavWindow = NULL; + NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0; + NavLayer = ImGuiNavLayer_Main; + NavNextActivateId = 0; + NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None; + NavHighlightActivatedId = 0; + NavHighlightActivatedTimer = 0.0f; + NavInputSource = ImGuiInputSource_Keyboard; + NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + NavCursorHideFrames = 0; + + NavAnyRequest = false; + NavInitRequest = false; + NavInitRequestFromMove = false; + NavMoveSubmitted = false; + NavMoveScoringItems = false; + NavMoveForwardToNextFrame = false; + NavMoveFlags = ImGuiNavMoveFlags_None; + NavMoveScrollFlags = ImGuiScrollFlags_None; + NavMoveKeyMods = ImGuiMod_None; + NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None; + NavScoringDebugCount = 0; + NavTabbingDir = 0; + NavTabbingCounter = 0; + + NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0; + NavJustMovedToKeyMods = ImGuiMod_None; + NavJustMovedToIsTabbing = false; + NavJustMovedToHasSelectionData = false; + + // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... + // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. + ConfigNavWindowingWithGamepad = true; + ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); + ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); + NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; + NavWindowingInputSource = ImGuiInputSource_None; + NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; + NavWindowingToggleLayer = false; + NavWindowingToggleKey = ImGuiKey_None; + + DimBgRatio = 0.0f; + + DragDropActive = DragDropWithinSource = DragDropWithinTarget = false; + DragDropSourceFlags = ImGuiDragDropFlags_None; + DragDropSourceFrameCount = -1; + DragDropMouseButton = -1; + DragDropTargetId = 0; + DragDropTargetFullViewport = 0; + DragDropAcceptFlagsCurr = DragDropAcceptFlagsPrev = ImGuiDragDropFlags_None; + DragDropAcceptIdCurrRectSurface = 0.0f; + DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; + DragDropAcceptFrameCount = -1; + DragDropHoldJustPressedId = 0; + memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); + + ClipperTempDataStacked = 0; + + CurrentTable = NULL; + TablesTempDataStacked = 0; + CurrentTabBar = NULL; + CurrentMultiSelect = NULL; + MultiSelectTempDataStacked = 0; + + HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0; + HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f; + + MouseCursor = ImGuiMouseCursor_Arrow; + MouseStationaryTimer = 0.0f; + + InputTextPasswordFontBackupFlags = ImFontFlags_None; + TempInputId = 0; + memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue)); + BeginMenuDepth = BeginComboDepth = 0; + ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_; + ColorEditCurrentID = ColorEditSavedID = 0; + ColorEditSavedHue = ColorEditSavedSat = 0.0f; + ColorEditSavedColor = 0; + WindowResizeRelativeMode = false; + ScrollbarSeekMode = 0; + ScrollbarClickDeltaToGrabCenter = 0.0f; + SliderGrabClickOffset = 0.0f; + SliderCurrentAccum = 0.0f; + SliderCurrentAccumDirty = false; + DragCurrentAccumDirty = false; + DragCurrentAccum = 0.0f; + DragSpeedDefaultRatio = 1.0f / 100.0f; + DisabledAlphaBackup = 0.0f; + DisabledStackSize = 0; + TooltipOverrideCount = 0; + TooltipPreviousWindow = NULL; + + PlatformImeData.InputPos = ImVec2(0.0f, 0.0f); + PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission + + DockNodeWindowMenuHandler = NULL; + + SettingsLoaded = false; + SettingsDirtyTimer = 0.0f; + HookIdNext = 0; + + memset(LocalizationTable, 0, sizeof(LocalizationTable)); + + LogEnabled = false; + LogLineFirstItem = false; + LogFlags = ImGuiLogFlags_None; + LogWindow = NULL; + LogNextPrefix = LogNextSuffix = NULL; + LogFile = NULL; + LogLinePosY = FLT_MAX; + LogDepthRef = 0; + LogDepthToExpand = LogDepthToExpandDefault = 2; + + ErrorCallback = NULL; + ErrorCallbackUserData = NULL; + ErrorFirst = true; + ErrorCountCurrentFrame = 0; + StackSizesInBeginForCurrentWindow = NULL; + + DebugDrawIdConflictsCount = 0; + DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY; + DebugLocateId = 0; + DebugLogSkippedErrors = 0; + DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None; + DebugLogAutoDisableFrames = 0; + DebugLocateFrames = 0; + DebugBeginReturnValueCullDepth = -1; + DebugItemPickerActive = false; + DebugItemPickerMouseButton = ImGuiMouseButton_Left; + DebugItemPickerBreakId = 0; + DebugFlashStyleColorTime = 0.0f; + DebugFlashStyleColorIdx = ImGuiCol_COUNT; + DebugHoveredDockNode = NULL; + + // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations + DebugBreakInWindow = 0; + DebugBreakInTable = 0; + DebugBreakInLocateId = false; + DebugBreakKeyChord = ImGuiKey_Pause; + DebugBreakInShortcutRouting = ImGuiKey_None; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0; + FramerateSecPerFrameAccum = 0.0f; + WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1; + memset(TempKeychordName, 0, sizeof(TempKeychordName)); +} + +ImGuiContext::~ImGuiContext() +{ + IM_ASSERT(Initialized == false && "Forgot to call DestroyContext()?"); +} + +void ImGui::Initialize() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(!g.Initialized && !g.SettingsLoaded); + + // Add .ini handle for ImGuiWindow and ImGuiTable types + { + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Window"; + ini_handler.TypeHash = ImHashStr("Window"); + ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; + ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; + AddSettingsHandler(&ini_handler); + } + TableSettingsAddSettingsHandler(); + + // Setup default localization table + LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_COUNTOF(GLocalizationEntriesEnUS)); + + // Setup default ImGuiPlatformIO clipboard/IME handlers. + g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl; + g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl; + g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl; + + // Create default viewport + ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID; + viewport->Idx = 0; + viewport->PlatformWindowCreated = true; + viewport->Flags = ImGuiViewportFlags_OwnedByApp; + g.Viewports.push_back(viewport); + g.TempBuffer.resize(1024 * 3 + 1, 0); + g.ViewportCreatedCount++; + g.PlatformIO.Viewports.push_back(g.Viewports[0]); + + // Build KeysMayBeCharInput[] lookup table (1 bit per named key) + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) + if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9) + || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period + || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent + || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual) + g.KeysMayBeCharInput.SetBit(key); + +#ifdef IMGUI_HAS_DOCK + // Initialize Docking + DockContextInitialize(&g); +#endif + + // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow. + // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED. +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + + // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context. + // But this link allows us to facilitate/handle a few edge cases better. + ImFontAtlas* atlas = g.IO.Fonts; + g.DrawListSharedData.Context = &g; + RegisterFontAtlas(atlas); + + g.Initialized = true; +} + +// This function is merely here to free heap allocations. +void ImGui::Shutdown() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?"); + IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?"); + for (ImGuiViewportP* viewport : g.Viewports) + { + IM_UNUSED(viewport); + IM_ASSERT_USER_ERROR(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL, "Backend or app forgot to call DestroyPlatformWindows()?"); + } + + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + for (ImFontAtlas* atlas : g.FontAtlases) + { + UnregisterFontAtlas(atlas); + if (atlas->RefCount == 0) + { + atlas->Locked = false; + IM_DELETE(atlas); + } + } + g.DrawListSharedData.TempBuffer.clear(); + + // Cleanup of other data are conditional on actually having initialized Dear ImGui. + if (!g.Initialized) + return; + + // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) + if (g.SettingsLoaded && g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + + // Shutdown extensions + DockContextShutdown(&g); + + CallContextHooks(&g, ImGuiContextHookType_Shutdown); + + // Clear everything else + g.Windows.clear_delete(); + g.WindowsFocusOrder.clear(); + g.WindowsTempSortBuffer.clear(); + g.CurrentWindow = NULL; + g.CurrentWindowStack.clear(); + g.WindowsById.Clear(); + g.NavWindow = NULL; + g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL; + g.ActiveIdWindow = NULL; + g.MovingWindow = NULL; + + g.KeysRoutingTable.Clear(); + + g.ColorStack.clear(); + g.StyleVarStack.clear(); + g.FontStack.clear(); + g.OpenPopupStack.clear(); + g.BeginPopupStack.clear(); + g.TreeNodeStack.clear(); + + g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL; + g.Viewports.clear_delete(); + + g.TabBars.Clear(); + g.CurrentTabBarStack.clear(); + g.ShrinkWidthBuffer.clear(); + + g.ClipperTempData.clear_destruct(); + + g.Tables.Clear(); + g.TablesTempData.clear_destruct(); + g.DrawChannelsTempMergeBuffer.clear(); + + g.MultiSelectStorage.Clear(); + g.MultiSelectTempData.clear_destruct(); + + g.ClipboardHandlerData.clear(); + g.MenusIdSubmittedThisFrame.clear(); + g.InputTextState.ClearFreeMemory(); + g.InputTextLineIndex.clear(); + g.InputTextDeactivatedState.ClearFreeMemory(); + + g.SettingsWindows.clear(); + g.SettingsHandlers.clear(); + + if (g.LogFile) + { +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + if (g.LogFile != stdout) +#endif + ImFileClose(g.LogFile); + g.LogFile = NULL; + } + g.LogBuffer.clear(); + g.DebugLogBuf.clear(); + g.DebugLogIndex.clear(); + + g.Initialized = false; +} + +// When using multiple context it can be helpful to give name a name. +// (A) Will be visible in debugger, (B) Will be included in all IMGUI_DEBUG_LOG() calls, (C) Should be <= 15 characters long. +void ImGui::SetContextName(ImGuiContext* ctx, const char* name) +{ + ImStrncpy(ctx->ContextName, name, IM_COUNTOF(ctx->ContextName)); +} + +// No specific ordering/dependency support, will see as needed +ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook) +{ + ImGuiContext& g = *ctx; + IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_); + g.Hooks.push_back(*hook); + g.Hooks.back().HookId = ++g.HookIdNext; + return g.HookIdNext; +} + +// Deferred removal, avoiding issue with changing vector while iterating it +void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id) +{ + ImGuiContext& g = *ctx; + IM_ASSERT(hook_id != 0); + for (ImGuiContextHook& hook : g.Hooks) + if (hook.HookId == hook_id) + hook.Type = ImGuiContextHookType_PendingRemoval_; +} + +// Call context hooks (used by e.g. test engine) +// We assume a small number of hooks so all stored in same array +void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) +{ + ImGuiContext& g = *ctx; + for (ImGuiContextHook& hook : g.Hooks) + if (hook.Type == hook_type) + hook.Callback(&g, &hook); +} + +//----------------------------------------------------------------------------- +// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +//----------------------------------------------------------------------------- + +// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods +ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL) +{ + memset(this, 0, sizeof(*this)); + Ctx = ctx; + Name = ImStrdup(name); + NameBufLen = (int)ImStrlen(name) + 1; + ID = ImHashStr(name); + IDStack.push_back(ID); + ViewportAllowPlatformMonitorExtend = -1; + ViewportPos = ImVec2(FLT_MAX, FLT_MAX); + MoveId = GetID("#MOVE"); + TabId = GetID("#TAB"); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + AutoPosLastDirection = ImGuiDir_None; + AutoFitFramesX = AutoFitFramesY = -1; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0; + SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); + LastFrameActive = -1; + LastFrameJustFocused = -1; + LastTimeActive = -1.0f; + FontRefSize = 0.0f; + FontWindowScale = FontWindowScaleParents = 1.0f; + SettingsOffset = -1; + DockOrder = -1; + DrawList = &DrawListInst; + DrawList->_OwnerName = Name; + DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData); + NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX); + IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass(); +} + +ImGuiWindow::~ImGuiWindow() +{ + IM_ASSERT(DrawList == &DrawListInst); + IM_DELETE(Name); + ColumnsStorage.clear_destruct(); +} + +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL; + g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL; + if (window) + { + bool backup_skip_items = window->SkipItems; + window->SkipItems = false; + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + { + ImGuiViewport* viewport = window->Viewport; + g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() + } + ImGui::UpdateCurrentFontSize(0.0f); + window->SkipItems = backup_skip_items; + ImGui::NavUpdateCurrentWindowIsScrollPushableX(); + } +} + +void ImGui::GcCompactTransientMiscBuffers() +{ + ImGuiContext& g = *GImGui; + g.ItemFlagsStack.clear(); + g.GroupStack.clear(); + g.InputTextLineIndex.clear(); + g.MultiSelectTempDataStacked = 0; + g.MultiSelectTempData.clear_destruct(); + TableGcCompactSettings(); + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->CompactCache(); +} + +// Free up/compact internal window buffers, we can use this when a window becomes unused. +// Not freed: +// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) +// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) +{ + window->MemoryCompacted = true; + window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; + window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; + window->IDStack.clear(); + window->DrawList->_ClearFreeMemory(); + window->DC.ChildWindows.clear(); + window->DC.ItemWidthStack.clear(); + window->DC.TextWrapPosStack.clear(); +} + +void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window) +{ + // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + // The other buffers tends to amortize much faster. + window->MemoryCompacted = false; + window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity); + window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity); + window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + // Clear previous active id + if (g.ActiveId != 0) + { + // Store deactivate data + ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData; + deactivated_data->ID = g.ActiveId; + deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData? + deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; + deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId); + + // This could be written in a more general way (e.g associate a hook to ActiveId), + // but since this is currently quite an exception we'll leave it as is. + // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID() + if (g.InputTextState.ID == g.ActiveId) + InputTextDeactivateHook(g.ActiveId); + + // While most behaved code would make an effort to not steal active id during window move/drag operations, + // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch + // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that. + if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId) + { + IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n"); + StopMouseMovingWindow(); + } + } + + // Set active id + g.ActiveIdIsJustActivated = (g.ActiveId != id); + if (g.ActiveIdIsJustActivated) + { + IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : ""); + g.ActiveIdTimer = 0.0f; + g.ActiveIdHasBeenPressedBefore = false; + g.ActiveIdHasBeenEditedBefore = false; + g.ActiveIdMouseButton = -1; + if (id != 0) + { + g.LastActiveId = id; + g.LastActiveIdTimer = 0.0f; + } + } + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; + g.ActiveIdWindow = window; + g.ActiveIdHasBeenEditedThisFrame = false; + g.ActiveIdFromShortcut = false; + g.ActiveIdDisabledId = 0; + if (id) + { + g.ActiveIdIsAlive = id; + g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None); + } + + // Clear declaration of inputs claimed by the widget + // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) + g.ActiveIdUsingNavDirMask = 0x00; + g.ActiveIdUsingAllKeyboardKeys = false; +} + +void ImGui::ClearActiveID() +{ + SetActiveID(0, NULL); // g.ActiveId = 0; +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; + if (id != 0 && g.HoveredIdPreviousFrame != id) + g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; +} + +ImGuiID ImGui::GetHoveredID() +{ + ImGuiContext& g = *GImGui; + return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; +} + +void ImGui::MarkItemEdited(ImGuiID id) +{ + // This marking is to be able to provide info for IsItemDeactivatedAfterEdit(). + // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data. + ImGuiContext& g = *GImGui; + if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited) + return; + if (g.ActiveId == id || g.ActiveId == 0) + { + // FIXME: Can't we fully rely on LastItemData yet? + g.ActiveIdHasBeenEditedThisFrame = true; + g.ActiveIdHasBeenEditedBefore = true; + if (g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.HasBeenEditedBefore = true; + } + + // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343) + // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714) + // FIXME: This assert is getting a bit meaningless over time. It helped detect some unusual use cases but eventually it is becoming an unnecessary restriction. + IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || g.NavJustMovedToId || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive)); + + //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; +} + +bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags) +{ + // An active popup disable hovering on other windows (apart from its own children) + // FIXME-OPT: This could be cached/stored within the window. + ImGuiContext& g = *GImGui; + if (g.NavWindow) + if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree) + if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree) + { + // For the purpose of those flags we differentiate "standard popup" from "modal popup" + // NB: The 'else' is important because Modal windows are also Popups. + bool want_inhibit = false; + if (focused_root_window->Flags & ImGuiWindowFlags_Modal) + want_inhibit = true; + else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + want_inhibit = true; + + // Inhibit hover unless the window is within the stack of our modal/popup + if (want_inhibit) + if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window)) + return false; + } + + // Filter by viewport + if (window->Viewport != g.MouseViewport) + if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree) + return false; + + return true; +} + +static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags) +{ + ImGuiContext& g = *GImGui; + if (flags & ImGuiHoveredFlags_DelayNormal) + return g.Style.HoverDelayNormal; + if (flags & ImGuiHoveredFlags_DelayShort) + return g.Style.HoverDelayShort; + return 0.0f; +} + +static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags) +{ + // Allow instance flags to override shared flags + if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal)) + shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal); + return user_flags | shared_flags; +} + +// This is roughly matching the behavior of internal-facing ItemHoverable() +// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId +bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!"); + + if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride)) + { + if (!IsItemFocused()) + return false; + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) + return false; + + if (flags & ImGuiHoveredFlags_ForTooltip) + flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav); + } + else + { + // Test for bounding box overlap, as updated as ItemAdd() + ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags; + if (!(status_flags & ImGuiItemStatusFlags_HoveredRect)) + return false; + + if (flags & ImGuiHoveredFlags_ForTooltip) + flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse); + + // Done with rectangle culling so we can perform heavier checks now + // Test if we are hovering the right window (our window could be behind another window) + // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851) + // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable + // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was + // the test that has been running for a long while. + if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0) + if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0) + return false; + + // Test if another item is active (e.g. being dragged) + const ImGuiID id = g.LastItemData.ID; + if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap && !g.ActiveIdFromShortcut) + { + // When ActiveId == MoveId it means that either: + // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag) + // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed. + // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId. + bool cancel_is_hovered = true; + if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id)) + cancel_is_hovered = false; + // When ActiveId == TabId it means user clicked docking tab for the window. + if (g.ActiveId == window->TabId) + cancel_is_hovered = false; + if (cancel_is_hovered) + return false; + } + + // Test if interactions on this window are blocked by an active popup or modal. + // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. + if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck)) + return false; + + // Test if the item is disabled + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) + return false; + + // Special handling for calling after Begin() which represent the title bar or tab. + // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin) + // will never be overwritten so we need to detect the case. + if (id == window->MoveId && window->WriteAccessed) + return false; + + // Test if using AllowOverlap and overlapped + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0) + if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0) + if (g.HoveredIdPreviousFrame != g.LastItemData.ID) + return false; + } + + // Handle hover delay + // (some ideas: https://www.nngroup.com/articles/timing-exposing-content) + const float delay = CalcDelayFromHoveredFlags(flags); + if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary)) + { + ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min); + if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id)) + g.HoverItemDelayTimer = 0.0f; + g.HoverItemDelayId = hover_delay_id; + + // When changing hovered item we requires a bit of stationary delay before activating hover timer, + // but once unlocked on a given item we also moving. + //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); } + if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id) + return false; + + if (g.HoverItemDelayTimer < delay) + return false; + } + + return true; +} + +// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK. +// Returns whether the item was hovered, logic differs slightly from IsItemHovered(). +// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call) +// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28. +// If you used this in your legacy/custom widgets code: +// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'. +// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable. +bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Detect ID conflicts + // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever) +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0) + { + g.HoveredIdPreviousFrameItemCount++; + if (g.DebugDrawIdConflictsId == id) + window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); + } +#endif + + if (g.HoveredWindow != window) + return false; + if (!IsMouseHoveringRect(bb.Min, bb.Max)) + return false; + + if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) + return false; + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) + if (!g.ActiveIdFromShortcut) + return false; + + // We are done with rectangle culling so we can perform heavier checks now. + if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) + { + g.HoveredIdIsDisabled = true; + return false; + } + + // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + // hover test in widgets code. We could also decide to split this function is two. + if (id != 0) + { + // Drag source doesn't report as hovered + if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover)) + return false; + + SetHoveredID(id); + + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. + // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test. + if (item_flags & ImGuiItemFlags_AllowOverlap) + { + g.HoveredIdAllowOverlap = true; + if (g.HoveredIdPreviousFrame != id) + return false; + } + + // Display shortcut (only works with mouse) + // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip) + if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id) + if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal)) + SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut)); + } + + // When disabled we'll return false but still set HoveredId + if (item_flags & ImGuiItemFlags_Disabled) + { + // Release active id if turning disabled + if (g.ActiveId == id && id != 0) + ClearActiveID(); + g.HoveredIdIsDisabled = true; + return false; + } + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (id != 0) + { + // [DEBUG] Item Picker tool! + // We perform the check here because reaching is path is rare (1~ time a frame), + // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered + // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost. + if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) + GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); + if (g.DebugItemPickerBreakId == id) + IM_DEBUG_BREAK(); + } +#endif + + if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0) + return false; + + return true; +} + +// FIXME: This is inlined/duplicated in ItemAdd() +// FIXME: The id != 0 path is not used by our codebase, may get rid of it? +bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!bb.Overlaps(window->ClipRect)) + if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId)) + if (!g.ItemUnclipByLog) + return true; + return false; +} + +// This is also inlined in ItemAdd() +// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect. +void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect) +{ + ImGuiContext& g = *GImGui; + g.LastItemData.ID = item_id; + g.LastItemData.ItemFlags = item_flags; + g.LastItemData.StatusFlags = status_flags; + g.LastItemData.Rect = g.LastItemData.NavRect = item_rect; +} + +static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + if (window->DockIsActive) + SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.DockTabItemStatusFlags, window->DC.DockTabItemRect); + else + SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect); +} + +static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect); +} + +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (wrap_pos_x == 0.0f) + { + // We could decide to setup a default wrapping max point for auto-resizing windows, + // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x); + //else + wrap_pos_x = window->WorkRect.Max.x; + } + else if (wrap_pos_x > 0.0f) + { + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + } + + return ImMax(wrap_pos_x - pos.x, 1.0f); +} + +// IM_ALLOC() == ImGui::MemAlloc() +void* ImGui::MemAlloc(size_t size) +{ + void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (ImGuiContext* ctx = GImGui) + DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size); +#endif + return ptr; +} + +// IM_FREE() == ImGui::MemFree() +void ImGui::MemFree(void* ptr) +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (ptr != NULL) + if (ImGuiContext* ctx = GImGui) + DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1); +#endif + return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData); +} + +// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames" +void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size) +{ + ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx]; + IM_UNUSED(ptr); + if (entry->FrameCount != frame_count) + { + info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_COUNTOF(info->LastEntriesBuf); + entry = &info->LastEntriesBuf[info->LastEntriesIdx]; + entry->FrameCount = frame_count; + entry->AllocCount = entry->FreeCount = 0; + } + if (size != (size_t)-1) + { + //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr); + entry->AllocCount++; + info->TotalAllocCount++; + } + else + { + //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr); + entry->FreeCount++; + info->TotalFreeCount++; + } +} + +// A conformant backend should return NULL on failure (e.g. clipboard data is not text). +const char* ImGui::GetClipboardText() +{ + ImGuiContext& g = *GImGui; + return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : NULL; +} + +void ImGui::SetClipboardText(const char* text) +{ + ImGuiContext& g = *GImGui; + if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) + g.PlatformIO.Platform_SetClipboardTextFn(&g, text); +} + +const char* ImGui::GetVersion() +{ + return IMGUI_VERSION; +} + +ImGuiIO& ImGui::GetIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + return GImGui->IO; +} + +// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856) +ImGuiIO& ImGui::GetIO(ImGuiContext* ctx) +{ + IM_ASSERT(ctx != NULL); + return ctx->IO; +} + +ImGuiPlatformIO& ImGui::GetPlatformIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?"); + return GImGui->PlatformIO; +} + +// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856) +ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx) +{ + IM_ASSERT(ctx != NULL); + return ctx->PlatformIO; +} + +// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = g.Viewports[0]; + return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL; +} + +double ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + +static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name) +{ + // Create the draw list on demand, because they are not frequently used for all viewports + ImGuiContext& g = *GImGui; + IM_ASSERT(drawlist_no < IM_COUNTOF(viewport->BgFgDrawLists)); + ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no]; + if (draw_list == NULL) + { + draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData); + draw_list->_OwnerName = drawlist_name; + viewport->BgFgDrawLists[drawlist_no] = draw_list; + } + + // Our ImDrawList system requires that there is always a command + if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount) + { + draw_list->_ResetForNewFrame(); + draw_list->PushTexture(g.IO.Fonts->TexRef); + draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); + viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount; + } + return draw_list; +} + +ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport) +{ + if (viewport == NULL) + viewport = GImGui->CurrentWindow->Viewport; + return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background"); +} + +ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport) +{ + if (viewport == NULL) + viewport = GImGui->CurrentWindow->Viewport; + return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground"); +} + +ImDrawListSharedData* ImGui::GetDrawListSharedData() +{ + return &GImGui->DrawListSharedData; +} + +void ImGui::StartMouseMovingWindow(ImGuiWindow* window) +{ + // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. + // This is because we want ActiveId to be set even when the window is not permitted to move. + ImGuiContext& g = *GImGui; + FocusWindow(window); + SetActiveID(window->MoveId, window); + if (g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = false; + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos; + g.ActiveIdNoClearOnFocusLoss = true; + SetActiveIdUsingAllKeyboardKeys(); + + bool can_move_window = true; + if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; + if (ImGuiDockNode* node = window->DockNodeAsHost) + if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; + if (can_move_window) + g.MovingWindow = window; +} + +// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. +void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock) +{ + ImGuiContext& g = *GImGui; + bool can_undock_node = false; + if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0) + { + // Can undock if: + // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window) + // - part of a dockspace node hierarchy: so we can undock the last single visible node too. Undocking from a fixed/central node will create a new node and copy windows. + ImGuiDockNode* root_node = DockNodeGetRootNode(node); + if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that. + can_undock_node = true; + } + + const bool clicked = IsMouseClicked(0); + const bool dragging = IsMouseDragging(0); + if (can_undock_node && dragging) + DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame + else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) + StartMouseMovingWindow(window); +} + +// This is not 100% symetric with StartMouseMovingWindow(). +// We do NOT clear ActiveID, because: +// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired. +// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item). +void ImGui::StopMouseMovingWindow() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.MovingWindow; + + // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL. + if (window && window->Viewport) + { + // Try to merge the window back into the main viewport. + // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + UpdateTryMergeWindowIntoHostViewport(window->RootWindowDockTree, g.MouseViewport); + + // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button. + if (!IsDragDropPayloadBeingAccepted()) + g.MouseViewport = window->Viewport; + + // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport() + const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false; + if (window_can_use_inputs) + window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; + } + g.MovingWindow = NULL; +} + +// Handle mouse moving window +// Note: moving window with the navigation keys (Square + d-pad / Ctrl+Tab + Arrows) are processed in NavUpdateWindowing() +// FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId. +// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs, +// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. +void ImGui::UpdateMouseMovingWindowNewFrame() +{ + ImGuiContext& g = *GImGui; + if (g.MovingWindow != NULL) + { + // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. + KeepAliveID(g.ActiveId); + IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree); + ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree; + + // When a window stop being submitted while being dragged, it may will its viewport until next Begin() + const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active); + if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappeared) + { + ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; + if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) + { + SetWindowPos(moving_window, pos, ImGuiCond_Always); + if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window. + { + moving_window->Viewport->Pos = pos; + moving_window->Viewport->UpdateWorkRect(); + } + } + FocusWindow(g.MovingWindow); + } + else + { + StopMouseMovingWindow(); + ClearActiveID(); + } + } + else + { + // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. + if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) + { + KeepAliveID(g.ActiveId); + if (!g.IO.MouseDown[0]) + ClearActiveID(); + } + } +} + +// Initiate focusing and moving window when clicking on empty space or title bar. +// Initiate focusing window when clicking on a disabled item. +// Handle left-click and right-click focus. +void ImGui::UpdateMouseMovingWindowEndFrame() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled)) + return; + + // Unless we just made a window/popup appear + if (g.NavWindow && g.NavWindow->Appearing) + return; + + ImGuiWindow* hovered_window = g.HoveredWindow; + + // Click on empty space to focus window and start moving + // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) + if (g.IO.MouseClicked[0]) + { + // Handle the edge case of a popup being closed while clicking in its empty space. + // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. + ImGuiWindow* hovered_root = hovered_window ? hovered_window->RootWindow : NULL; + const bool is_closed_popup = hovered_root && (hovered_root->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(hovered_root->PopupId, ImGuiPopupFlags_AnyPopupLevel); + + if (hovered_window != NULL && !is_closed_popup) + { + StartMouseMovingWindow(hovered_window); //-V595 + + // FIXME: In principle we might be able to call StopMouseMovingWindow() below. + // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId. + + // Cancel moving if clicked outside of title bar + if ((hovered_window->BgClickFlags & ImGuiWindowBgClickFlags_Move) == 0) // set by io.ConfigWindowsMoveFromTitleBarOnly + if (!(hovered_root->Flags & ImGuiWindowFlags_NoTitleBar) || hovered_root->DockIsActive) + if (!hovered_root->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + g.MovingWindow = NULL; + + // Cancel moving if clicked over an item which was disabled or inhibited by popups + // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item) + if (g.HoveredIdIsDisabled) + { + g.MovingWindow = NULL; + g.ActiveIdDisabledId = g.HoveredId; + } + } + else if (hovered_window == NULL && g.NavWindow != NULL) + { + // Clicking on void disable focus + FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal); + } + } + + // With right mouse button we close popups without changing focus based on where the mouse is aimed + // Instead, focus will be restored to the window under the bottom-most closed popup. + // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) + if (g.IO.MouseClicked[1] && g.HoveredId == 0) + { + // Find the top-most window between HoveredWindow and the top-most Modal Window. + // This is where we can trim the popup stack. + ImGuiWindow* modal = GetTopMostPopupModal(); + bool hovered_window_above_modal = hovered_window && (modal == NULL || IsWindowAbove(hovered_window, modal)); + ClosePopupsOverWindow(hovered_window_above_modal ? hovered_window : modal, true); + } +} + +// This is called during NewFrame()->UpdateViewportsNewFrame() only. +// Need to keep in sync with SetWindowPos() +static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta) +{ + window->Pos += delta; + window->ClipRect.Translate(delta); + window->OuterRectClipped.Translate(delta); + window->InnerRect.Translate(delta); + window->DC.CursorPos += delta; + window->DC.CursorStartPos += delta; + window->DC.CursorMaxPos += delta; + window->DC.IdealMaxPos += delta; +} + +static void ScaleWindow(ImGuiWindow* window, float scale) +{ + ImVec2 origin = window->Viewport->Pos; + window->Pos = ImFloor((window->Pos - origin) * scale + origin); + window->Size = ImTrunc(window->Size * scale); + window->SizeFull = ImTrunc(window->SizeFull * scale); + window->ContentSize = ImTrunc(window->ContentSize * scale); +} + +static bool IsWindowActiveAndVisible(ImGuiWindow* window) +{ + return window->Active && !window->Hidden; +} + +// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) +void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING + // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow. + g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding); + + // Find the window hovered by mouse: + // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. + // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. + // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. + bool clear_hovered_windows = false; + FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); + IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport); + g.HoveredWindowBeforeClear = g.HoveredWindow; + + // Modal windows prevents mouse from hovering behind them. + ImGuiWindow* modal_window = GetTopMostPopupModal(); + if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ? + clear_hovered_windows = true; + + // Disabled mouse hovering (we don't currently clear MousePos, we could) + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) + clear_hovered_windows = true; + + // We track click ownership. When clicked outside of a window the click is owned by the application and + // won't report hovering nor request capture even while dragging over our windows afterward. + const bool has_open_popup = (g.OpenPopupStack.Size > 0); + const bool has_open_modal = (modal_window != NULL); + int mouse_earliest_down = -1; + bool mouse_any_down = false; + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) + { + if (io.MouseClicked[i]) + { + io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup; + io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal; + } + mouse_any_down |= io.MouseDown[i]; + if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392) + if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down]) + mouse_earliest_down = i; + } + const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down]; + const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down]; + + // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) + const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; + if (!mouse_avail && !mouse_dragging_extern_payload) + clear_hovered_windows = true; + + if (clear_hovered_windows) + g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL; + + // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app) + // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag + if (g.WantCaptureMouseNextFrame != -1) + { + io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0); + } + else + { + io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup; + io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal; + } + + // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app) + io.WantCaptureKeyboard = false; + if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0) + { + if ((g.ActiveId != 0) || (modal_window != NULL)) + io.WantCaptureKeyboard = true; + else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard) + io.WantCaptureKeyboard = true; + } + if (g.WantCaptureKeyboardNextFrame != -1) // Manual override + io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); + + // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible + io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; +} + +// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. +// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! +static void SetupDrawListSharedData() +{ + ImGuiContext& g = *GImGui; + ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + for (ImGuiViewportP* viewport : g.Viewports) + virtual_space.Add(viewport->GetMainRect()); + g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4(); + g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; + g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError); + g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; + if (g.Style.AntiAliasedLines) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; + if (g.Style.AntiAliasedFill) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments. +} + +void ImGui::NewFrame() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + ImGuiContext& g = *GImGui; + + // Remove pending delete hooks before frame start. + // This deferred removal avoid issues of removal while iterating the hook vector + for (int n = g.Hooks.Size - 1; n >= 0; n--) + if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_) + g.Hooks.erase(&g.Hooks[n]); + + CallContextHooks(&g, ImGuiContextHookType_NewFramePre); + + // Check and assert for various common IO and Configuration mistakes + g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; + ErrorCheckNewFrameSanityChecks(); + g.ConfigFlagsCurrFrame = g.IO.ConfigFlags; + + // Load settings on first frame, save settings when modified (after a delay) + UpdateSettings(); + + g.Time += g.IO.DeltaTime; + g.FrameCount += 1; + g.TooltipOverrideCount = 0; + g.WindowsActiveCount = 0; + g.MenusIdSubmittedThisFrame.resize(0); + + // Calculate frame-rate for the user, as a purely luxurious feature + g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; + g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_COUNTOF(g.FramerateSecPerFrame); + g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_COUNTOF(g.FramerateSecPerFrame)); + g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX; + + // Process input queue (trickle as many events as possible), turn events into writes to IO structure + g.InputEventsTrail.resize(0); + UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue); + + // Update viewports (after processing input queue, so io.MouseHoveredViewport is set) + UpdateViewportsNewFrame(); + + // Update texture list (collect destroyed textures, etc.) + UpdateTexturesNewFrame(); + + // Setup current font and draw list shared data + SetupDrawListSharedData(); + UpdateFontsNewFrame(); + + g.WithinFrameScope = true; + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. + for (ImGuiViewportP* viewport : g.Viewports) + { + viewport->DrawData = NULL; + viewport->DrawDataP.Valid = false; + } + + // Drag and drop keep the source ID alive so even if the source disappear our state is consistent + if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) + KeepAliveID(g.DragDropPayload.SourceId); + + // [DEBUG] + if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding Ctrl + g.DebugDrawIdConflictsId = 0; + if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1) + g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame; + + // Update HoveredId data + if (!g.HoveredIdPreviousFrame) + g.HoveredIdTimer = 0.0f; + if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId)) + g.HoveredIdNotActiveTimer = 0.0f; + if (g.HoveredId) + g.HoveredIdTimer += g.IO.DeltaTime; + if (g.HoveredId && g.ActiveId != g.HoveredId) + g.HoveredIdNotActiveTimer += g.IO.DeltaTime; + g.HoveredIdPreviousFrame = g.HoveredId; + g.HoveredIdPreviousFrameItemCount = 0; + g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; + g.HoveredIdIsDisabled = false; + + // Clear ActiveID if the item is not alive anymore. + // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd(). + // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves. + if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId) + { + IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n"); + ClearActiveID(); + } + + // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore) + if (g.ActiveId) + g.ActiveIdTimer += g.IO.DeltaTime; + g.LastActiveIdTimer += g.IO.DeltaTime; + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdIsAlive = 0; + g.ActiveIdHasBeenEditedThisFrame = false; + g.ActiveIdIsJustActivated = false; + if (g.TempInputId != 0 && g.ActiveId != g.TempInputId) + g.TempInputId = 0; + if (g.ActiveId == 0) + { + g.ActiveIdUsingNavDirMask = 0x00; + g.ActiveIdUsingAllKeyboardKeys = false; + } + if (g.DeactivatedItemData.ElapseFrame < g.FrameCount) + g.DeactivatedItemData.ID = 0; + g.DeactivatedItemData.IsAlive = false; + + // Record when we have been stationary as this state is preserved while over same item. + // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values. + // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function. + if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay) + g.HoverItemUnlockedStationaryId = g.HoverItemDelayId; + else if (g.HoverItemDelayId == 0) + g.HoverItemUnlockedStationaryId = 0; + if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay) + g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID; + else if (g.HoveredWindow == NULL) + g.HoverWindowUnlockedStationaryId = 0; + + // Update hover delay for IsItemHovered() with delays and tooltips + g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId; + if (g.HoverItemDelayId != 0) + { + g.HoverItemDelayTimer += g.IO.DeltaTime; + g.HoverItemDelayClearTimer = 0.0f; + g.HoverItemDelayId = 0; + } + else if (g.HoverItemDelayTimer > 0.0f) + { + // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps + // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle. + g.HoverItemDelayClearTimer += g.IO.DeltaTime; + if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate + g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer. + } + + // Close popups on focus lost (currently wip/opt-in) + //if (g.IO.AppFocusLost) + // ClosePopupsExceptModals(); + + // Update keyboard input state + UpdateKeyboardInputs(); + + //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + + // Drag and drop + g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; + g.DragDropAcceptIdCurr = 0; + g.DragDropAcceptFlagsPrev = g.DragDropAcceptFlagsCurr; + g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropWithinSource = false; + g.DragDropWithinTarget = false; + g.DragDropHoldJustPressedId = 0; + if (g.DragDropActive) + { + // Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + // You may disable this externally by hijacking the input route: + // 'if (GetDragDropPayload() != NULL) { Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive); } + // but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey_Escape) afterwards. + ImGuiID owner_id = g.ActiveId ? g.ActiveId : ImHashStr("##DragDropCancelHandler"); + if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal, owner_id)) + { + ClearActiveID(); + ClearDragDrop(); + } + } + g.TooltipPreviousWindow = NULL; + + // Update keyboard/gamepad navigation + NavUpdate(); + + // Update mouse input state + UpdateMouseInputs(); + + // Undocking + // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) + DockContextNewFrameUpdateUndocking(&g); + + // Mark all windows as not visible and compact unused memory. + IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size); + const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer; + for (ImGuiWindow* window : g.Windows) + { + window->WasActive = window->Active; + window->Active = false; + window->WriteAccessed = false; + window->BeginCountPreviousFrame = window->BeginCount; + window->BeginCount = 0; + + // Garbage collect transient buffers of recently unused windows + if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) + GcCompactTransientWindowBuffers(window); + } + + // Find hovered window + // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) + // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active) + UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos); + + // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) + UpdateMouseMovingWindowNewFrame(); + + // Background darkening/whitening + if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) + g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); + else + g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); + + g.MouseCursor = ImGuiMouseCursor_Arrow; + g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1; + + // Platform IME data: reset for the frame + g.PlatformImeDataPrev = g.PlatformImeData; + g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false; + + // Mouse wheel scrolling, scale + UpdateMouseWheel(); + + // Garbage collect transient buffers of recently unused tables + for (int i = 0; i < g.TablesLastTimeActive.Size; i++) + if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time) + TableGcCompactTransientBuffers(g.Tables.GetByIndex(i)); + for (ImGuiTableTempData& table_temp_data : g.TablesTempData) + if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time) + TableGcCompactTransientBuffers(&table_temp_data); + if (g.GcCompactAll) + GcCompactTransientMiscBuffers(); + g.GcCompactAll = false; + + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.NavWindow && !g.NavWindow->WasActive) + FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.resize(0); + g.BeginPopupStack.resize(0); + g.ItemFlagsStack.resize(0); + g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags + g.CurrentItemFlags = g.ItemFlagsStack.back(); + g.GroupStack.resize(0); + + // Docking + DockContextNewFrameUpdateDocking(&g); + + // [DEBUG] Update debug features +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + UpdateDebugToolItemPicker(); + UpdateDebugToolItemPathQuery(); + UpdateDebugToolFlashStyleColor(); + if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0) + { + g.DebugLocateId = 0; + g.DebugBreakInLocateId = false; + } + if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0) + { + DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n"); + g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags; + g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None; + } +#endif + + // Create implicit/fallback window - which we will only render it if the user has added something to it. + // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + // This fallback is particularly important as it prevents ImGui:: calls from crashing. + g.WithinFrameScopeWithImplicitWindow = true; + SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); + Begin("Debug##Default"); + IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); + + // Store stack sizes + g.ErrorCountCurrentFrame = 0; + ErrorRecoveryStoreState(&g.StackSizesInNewFrame); + + // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack, + // allowing to validate correct Begin/End behavior in user code. +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.IO.ConfigDebugBeginReturnValueLoop) + g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10); + else + g.DebugBeginReturnValueCullDepth = -1; +#endif + + CallContextHooks(&g, ImGuiContextHookType_NewFramePost); +} + +// FIXME: Add a more explicit sort order in the window structure. +static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) +{ + const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs; + const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs; + if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + return d; + return a->BeginOrderWithinParent - b->BeginOrderWithinParent; +} + +static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window) +{ + out_sorted_windows->push_back(window); + if (window->Active) + { + int count = window->DC.ChildWindows.Size; + ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (child->Active) + AddWindowToSortBuffer(out_sorted_windows, child); + } + } +} + +static void AddWindowToDrawData(ImGuiWindow* window, int layer) +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = window->Viewport; + IM_ASSERT(viewport != NULL); + g.IO.MetricsRenderWindows++; + if (window->DrawList->_Splitter._Count > 1) + window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows. + ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList); + for (ImGuiWindow* child : window->DC.ChildWindows) + if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active + AddWindowToDrawData(child, layer); +} + +static inline int GetWindowDisplayLayer(ImGuiWindow* window) +{ + return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0; +} + +// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) +static inline void AddRootWindowToDrawData(ImGuiWindow* window) +{ + AddWindowToDrawData(window, GetWindowDisplayLayer(window)); +} + +static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder) +{ + int n = builder->Layers[0]->Size; + int full_size = n; + for (int i = 1; i < IM_COUNTOF(builder->Layers); i++) + full_size += builder->Layers[i]->Size; + builder->Layers[0]->resize(full_size); + for (int layer_n = 1; layer_n < IM_COUNTOF(builder->Layers); layer_n++) + { + ImVector* layer = builder->Layers[layer_n]; + if (layer->empty()) + continue; + memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*)); + n += layer->Size; + layer->resize(0); + } +} + +static void InitViewportDrawData(ImGuiViewportP* viewport) +{ + ImGuiIO& io = ImGui::GetIO(); + ImDrawData* draw_data = &viewport->DrawDataP; + + viewport->DrawData = draw_data; // Make publicly accessible + viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists; + viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1; + viewport->DrawDataBuilder.Layers[0]->resize(0); + viewport->DrawDataBuilder.Layers[1]->resize(0); + + // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, + // and to allow applications/backends to easily skip rendering. + // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. + // This is because the work has been done already, and its wasted! We should fix that and add optimizations for + // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. + const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0; + + draw_data->Valid = true; + draw_data->CmdListsCount = 0; + draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; + draw_data->DisplayPos = viewport->Pos; + draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; + draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale; + draw_data->OwnerViewport = viewport; + draw_data->Textures = &ImGui::GetPlatformIO().Textures; +} + +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): +// some frequently called functions which to modify both channels and clipping simultaneously tend to use the +// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. +// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, +// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +void ImGui::PopClipRect() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window) +{ + for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--) + if (IsWindowActiveAndVisible(window->DC.ChildWindows[n])) + return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]); + return window; +} + +static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + ImGuiViewportP* viewport = window->Viewport; + ImRect viewport_rect = viewport->GetMainRect(); + + // Draw behind window by moving the draw command at the FRONT of the draw list + { + // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + // FIXME: This is a little bit complicated, solely to avoid creating/injecting an extra drawlist in drawdata. + ImDrawList* draw_list = window->RootWindowDockTree->DrawList; + draw_list->ChannelsMerge(); + if (draw_list->CmdBuffer.Size == 0) + draw_list->AddDrawCmd(); + draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that) + ImDrawCmd cmd = draw_list->CmdBuffer.back(); + IM_ASSERT(cmd.ElemCount == 0); + draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col); + cmd = draw_list->CmdBuffer.back(); + draw_list->CmdBuffer.pop_back(); + draw_list->CmdBuffer.push_front(cmd); + draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. + draw_list->PopClipRect(); + } + + // Draw over sibling docking nodes in a same docking tree + if (window->RootWindow->DockIsActive) + { + ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList; + draw_list->ChannelsMerge(); + if (draw_list->CmdBuffer.Size == 0) + draw_list->AddDrawCmd(); + draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false); + RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding); + draw_list->PopClipRect(); + } +} + +ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* bottom_most_visible_window = parent_window; + for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + if (!IsWindowWithinBeginStackOf(window, parent_window)) + break; + if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window)) + bottom_most_visible_window = window; + } + return bottom_most_visible_window; +} + +// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage. +// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds(). +static void ImGui::RenderDimmedBackgrounds() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal(); + if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) + return; + const bool dim_bg_for_modal = (modal_window != NULL); + const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active); + if (!dim_bg_for_modal && !dim_bg_for_window_list) + return; + + ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL }; + if (dim_bg_for_modal) + { + // Draw dimming behind modal or a begin stack child, whichever comes first in draw order. + ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window); + RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio)); + viewports_already_dimmed[0] = modal_window->Viewport; + } + else if (dim_bg_for_window_list) + { + // Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window + RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); + viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport; + if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Active && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport) + { + RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); + viewports_already_dimmed[1] = g.NavWindowingListWindow->Viewport; + } + + // Draw border around Ctrl+Tab target window + ImGuiWindow* window = g.NavWindowingTargetAnim; + ImGuiViewport* viewport = window->Viewport; + float distance = g.FontSize; + ImRect bb = window->Rect(); + bb.Expand(distance); + if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y) + bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward + window->DrawList->ChannelsMerge(); + if (window->DrawList->CmdBuffer.Size == 0) + window->DrawList->AddDrawCmd(); + window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI + window->DrawList->PopClipRect(); + } + + // Draw dimming background on _other_ viewports than the ones our windows are in + for (ImGuiViewportP* viewport : g.Viewports) + { + if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1]) + continue; + if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window)) + continue; + ImDrawList* draw_list = GetForegroundDrawList(viewport); + const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); + draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col); + } +} + +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + + // Don't process EndFrame() multiple times. + if (g.FrameCountEnded == g.FrameCount) + return; + IM_ASSERT_USER_ERROR_RET(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?"); + + CallContextHooks(&g, ImGuiContextHookType_EndFramePre); + + // [EXPERIMENTAL] Recover from errors + if (g.IO.ConfigErrorRecovery) + ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame); + ErrorCheckEndFrameSanityChecks(); + ErrorCheckEndFrameFinalizeErrorTooltip(); + + // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; + if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) + { + ImGuiViewport* viewport = FindViewportByID(ime_data->ViewportId); + if (viewport == NULL) + viewport = GetMainViewport(); + IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y, viewport->ID); + g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); + } + g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0; + + // Hide implicit/fallback "Debug" window if it hasn't been used + g.WithinFrameScopeWithImplicitWindow = false; + if (g.CurrentWindow && g.CurrentWindow->IsFallbackWindow && g.CurrentWindow->WriteAccessed == false) + g.CurrentWindow->Active = false; + End(); + + // Update navigation: Ctrl+Tab, wrap-around requests + NavEndFrame(); + + // Update docking + DockContextEndFrame(&g); + + SetCurrentViewport(NULL, NULL); + + // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) + if (g.DragDropActive) + { + bool is_delivered = g.DragDropPayload.Delivery; + bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton)); + if (is_delivered || is_elapsed) + ClearDragDrop(); + } + + // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing. + // If you want to handle source item disappearing: instead of submitting your description tooltip + // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot + // (e.g. end of your item loop, or before EndFrame) by reading payload data. + // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data. + if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + { + g.DragDropWithinSource = true; + SetTooltip("..."); + g.DragDropWithinSource = false; + } + + // End frame + g.WithinFrameScope = false; + g.FrameCountEnded = g.FrameCount; + UpdateFontsEndFrame(); + + // Initiate moving window + handle left-click and right-click focus + UpdateMouseMovingWindowEndFrame(); + + // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) + UpdateViewportsEndFrame(); + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because children may not exist yet + g.WindowsTempSortBuffer.resize(0); + g.WindowsTempSortBuffer.reserve(g.Windows.Size); + for (ImGuiWindow* window : g.Windows) + { + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window); + } + + // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. + IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size); + g.Windows.swap(g.WindowsTempSortBuffer); + g.IO.MetricsActiveWindows = g.WindowsActiveCount; + + UpdateTexturesEndFrame(); + + // Unlock font atlas + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = false; + + // Clear Input data for next frame + g.IO.MousePosPrev = g.IO.MousePos; + g.IO.AppFocusLost = false; + g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; + g.IO.InputQueueCharacters.resize(0); + + CallContextHooks(&g, ImGuiContextHookType_EndFramePost); +} + +// Prepare the data for rendering so you can call GetDrawData() +// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all: +// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend) +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + + if (g.FrameCountEnded != g.FrameCount) + EndFrame(); + if (g.FrameCountRendered == g.FrameCount) + return; + g.FrameCountRendered = g.FrameCount; + + g.IO.MetricsRenderWindows = 0; + CallContextHooks(&g, ImGuiContextHookType_RenderPre); + + // Add background ImDrawList (for each active viewport) + for (ImGuiViewportP* viewport : g.Viewports) + { + InitViewportDrawData(viewport); + if (viewport->BgFgDrawLists[0] != NULL) + AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport)); + } + + // Draw modal/window whitening backgrounds + RenderDimmedBackgrounds(); + + // Add ImDrawList to render + ImGuiWindow* windows_to_render_top_most[2]; + windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL; + windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL); + for (ImGuiWindow* window : g.Windows) + { + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1]) + AddRootWindowToDrawData(window); + } + for (int n = 0; n < IM_COUNTOF(windows_to_render_top_most); n++) + if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window + AddRootWindowToDrawData(windows_to_render_top_most[n]); + + // Draw software mouse cursor if requested by io.MouseDrawCursor flag + if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None) + RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)); + + // Setup ImDrawData structures for end-user + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0; + for (ImGuiViewportP* viewport : g.Viewports) + { + FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder); + + // Add foreground ImDrawList (for each active viewport) + if (viewport->BgFgDrawLists[1] != NULL) + AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport)); + + // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch). + ImDrawData* draw_data = &viewport->DrawDataP; + IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount); + for (ImDrawList* draw_list : draw_data->CmdLists) + draw_list->_PopUnusedDrawCmd(); + + g.IO.MetricsRenderVertices += draw_data->TotalVtxCount; + g.IO.MetricsRenderIndices += draw_data->TotalIdxCount; + } + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + for (ImFontAtlas* atlas : g.FontAtlases) + ImFontAtlasDebugLogTextureRequests(atlas); +#endif + + CallContextHooks(&g, ImGuiContextHookType_RenderPost); +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, g.FontSize) +ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiContext& g = *GImGui; + + const char* text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + ImFont* font = g.Font; + const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + + // Round + // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out. + // FIXME: Investigate using ceilf or e.g. + // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c + // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html + text_size.x = IM_TRUNC(text_size.x + 0.99999f); + + return text_size; +} + +// Find window given position, search front-to-back +// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow. +// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically +// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +// called, aka before the next Begin(). Moving window isn't affected. +// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here. +void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* hovered_window = NULL; + ImGuiWindow* hovered_window_under_moving_window = NULL; + + // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame) + ImGuiViewportP* backup_moving_window_viewport = NULL; + if (find_first_and_in_any_viewport == false && g.MovingWindow) + { + backup_moving_window_viewport = g.MovingWindow->Viewport; + g.MovingWindow->Viewport = g.MouseViewport; + if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) + hovered_window = g.MovingWindow; + } + + ImVec2 padding_regular = g.Style.TouchExtraPadding; + ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding)); + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow* window = g.Windows[i]; + IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer. + if (!window->WasActive || window->Hidden) + continue; + if (window->Flags & ImGuiWindowFlags_NoMouseInputs) + continue; + IM_ASSERT(window->Viewport); + if (window->Viewport != g.MouseViewport) + continue; + + // Using the clipped AABB, a child window will typically be clipped by its parent (not always) + ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize; + if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding)) + continue; + + // Support for one rectangular hole in any given window + // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) + if (window->HitTestHoleSize.x != 0) + { + ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y); + ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y); + if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos)) + continue; + } + + if (find_first_and_in_any_viewport) + { + hovered_window = window; + break; + } + else + { + if (hovered_window == NULL) + hovered_window = window; + IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer. + if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)) + hovered_window_under_moving_window = window; + if (hovered_window && hovered_window_under_moving_window) + break; + } + } + + *out_hovered_window = hovered_window; + if (out_hovered_window_under_moving_window != NULL) + *out_hovered_window_under_moving_window = hovered_window_under_moving_window; + if (find_first_and_in_any_viewport == false && g.MovingWindow) + g.MovingWindow->Viewport = backup_moving_window_viewport; +} + +bool ImGui::IsItemActive() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + return g.ActiveId == g.LastItemData.ID; + return false; +} + +bool ImGui::IsItemActivated() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID) + return true; + return false; +} + +bool ImGui::IsItemDeactivated() +{ + ImGuiContext& g = *GImGui; + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated) + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; + return g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount; +} + +bool ImGui::IsItemDeactivatedAfterEdit() +{ + ImGuiContext& g = *GImGui; + return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore; +} + +// == (GetItemID() == GetFocusID() && GetFocusID() != 0) +bool ImGui::IsItemFocused() +{ + ImGuiContext& g = *GImGui; + if (g.NavId != g.LastItemData.ID || g.NavId == 0) + return false; + + // Special handling for the dummy item after Begin() which represent the title bar or tab. + // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. + ImGuiWindow* window = g.CurrentWindow; + if (g.LastItemData.ID == window->ID && window->WriteAccessed) + return false; + + return true; +} + +// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()! +// Most widgets have specific reactions based on mouse-up/down state, mouse position etc. +bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); +} + +bool ImGui::IsItemToggledOpen() +{ + ImGuiContext& g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false; +} + +// Call after a Selectable() or TreeNode() involved in multi-selection. +// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose. +// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block. +// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets +// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.) +bool ImGui::IsItemToggledSelection() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect() + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; +} + +// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. +bool ImGui::IsAnyItemHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; +} + +bool ImGui::IsAnyItemActive() +{ + ImGuiContext& g = *GImGui; + return g.ActiveId != 0; +} + +bool ImGui::IsAnyItemFocused() +{ + ImGuiContext& g = *GImGui; + return g.NavId != 0 && g.NavCursorVisible; +} + +bool ImGui::IsItemVisible() +{ + ImGuiContext& g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0; +} + +bool ImGui::IsItemEdited() +{ + ImGuiContext& g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0; +} + +// Allow next item to be overlapped by subsequent items. +// This works by requiring HoveredId to match for two subsequent frames, +// so if a following items overwrite it our interactions will naturally be disabled. +void ImGui::SetNextItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +// Use SetNextItemAllowOverlap() *before* your item instead of calling this! +//void ImGui::SetItemAllowOverlap() +//{ +// ImGuiContext& g = *GImGui; +// ImGuiID id = g.LastItemData.ID; +// if (g.HoveredId == id) +// g.HoveredIdAllowOverlap = true; +// if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id. +// g.ActiveIdAllowOverlap = true; +//} +#endif + +// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations. +// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed? +void ImGui::SetActiveIdUsingAllKeyboardKeys() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.ActiveId != 0); + g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1; + g.ActiveIdUsingAllKeyboardKeys = true; + NavMoveRequestCancel(); +} + +ImGuiID ImGui::GetItemID() +{ + ImGuiContext& g = *GImGui; + return g.LastItemData.ID; +} + +ImVec2 ImGui::GetItemRectMin() +{ + ImGuiContext& g = *GImGui; + return g.LastItemData.Rect.Min; +} + +ImVec2 ImGui::GetItemRectMax() +{ + ImGuiContext& g = *GImGui; + return g.LastItemData.Rect.Max; +} + +ImVec2 ImGui::GetItemRectSize() +{ + ImGuiContext& g = *GImGui; + return g.LastItemData.Rect.GetSize(); +} + +ImGuiItemFlags ImGui::GetItemFlags() +{ + ImGuiContext& g = *GImGui; + return g.LastItemData.ItemFlags; +} + +// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. +// ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! +bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) +{ + ImGuiID id = GetCurrentWindow()->GetID(str_id); + return BeginChildEx(str_id, id, size_arg, child_flags, window_flags); +} + +bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) +{ + return BeginChildEx(NULL, id, size_arg, child_flags, window_flags); +} + +bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* parent_window = g.CurrentWindow; + IM_ASSERT(id != 0); + + // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. + const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened; + IM_UNUSED(ImGuiChildFlags_SupportedMask_); + IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?"); + IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!"); + if (child_flags & ImGuiChildFlags_AlwaysAutoResize) + { + IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!"); + IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!"); + } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) { child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; } + //if (window_flags & ImGuiWindowFlags_NavFlattened) { child_flags |= ImGuiChildFlags_NavFlattened; } +#endif + if (child_flags & ImGuiChildFlags_AutoResizeX) + child_flags &= ~ImGuiChildFlags_ResizeX; + if (child_flags & ImGuiChildFlags_AutoResizeY) + child_flags &= ~ImGuiChildFlags_ResizeY; + + // Set window flags + window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking; + window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag + if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize)) + window_flags |= ImGuiWindowFlags_AlwaysAutoResize; + if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0) + window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; + + // Special framed style + if (child_flags & ImGuiChildFlags_FrameStyle) + { + PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]); + PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding); + PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize); + PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding); + child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding; + window_flags |= ImGuiWindowFlags_NoMove; + } + + // Forward size + // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set. + // (the alternative would to store conditional flags per axis, which is possible but more code) + const ImVec2 size_avail = GetContentRegionAvail(); + const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y); + ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y); + + // A SetNextWindowSize() call always has priority (#8020) + // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now) + // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer. + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0) + { + if (g.NextWindowData.SizeVal.x > 0.0f) + { + size.x = g.NextWindowData.SizeVal.x; + child_flags &= ~ImGuiChildFlags_ResizeX; + } + if (g.NextWindowData.SizeVal.y > 0.0f) + { + size.y = g.NextWindowData.SizeVal.y; + child_flags &= ~ImGuiChildFlags_ResizeY; + } + } + SetNextWindowSize(size); + + // Forward child flags (we allow prior settings to merge but it'll only work for adding flags) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) + g.NextWindowData.ChildFlags |= child_flags; + else + g.NextWindowData.ChildFlags = child_flags; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags; + + // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. + // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround. + // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it. + const char* temp_window_name; + /*if (name && parent_window->IDStack.back() == parent_window->ID) + ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack + else*/ + if (name) + ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id); + else + ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id); + + // Set style + const float backup_border_size = g.Style.ChildBorderSize; + if ((child_flags & ImGuiChildFlags_Borders) == 0) + g.Style.ChildBorderSize = 0.0f; + + // Begin into window + const bool ret = Begin(temp_window_name, NULL, window_flags); + + // Restore style + g.Style.ChildBorderSize = backup_border_size; + if (child_flags & ImGuiChildFlags_FrameStyle) + { + PopStyleVar(3); + PopStyleColor(); + } + + ImGuiWindow* child_window = g.CurrentWindow; + child_window->ChildId = id; + + // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually. + // While this is not really documented/defined, it seems that the expected thing to do. + if (child_window->BeginCount == 1) + parent_window->DC.CursorPos = child_window->Pos; + + // Process navigation-in immediately so NavInit can run on first frame + // Can enter a child if (A) it has navigable items or (B) it can be scrolled. + const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id); + if (g.ActiveId == temp_id_for_activation) + ClearActiveID(); + if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY)) + { + FocusWindow(child_window); + NavInitWindow(child_window, false); + SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item + g.ActiveIdSource = g.NavInputSource; + } + return ret; +} + +void ImGui::EndChild() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* child_window = g.CurrentWindow; + + const ImGuiID backup_within_end_child_id = g.WithinEndChildID; + IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls + + g.WithinEndChildID = child_window->ID; + ImVec2 child_size = child_window->Size; + End(); + if (child_window->BeginCount == 1) + { + ImGuiWindow* parent_window = g.CurrentWindow; + ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size); + ItemSize(child_size); + const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0; + if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened) + { + ItemAdd(bb, child_window->ChildId); + RenderNavCursor(bb, child_window->ChildId); + + // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying) + if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow) + RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact); + } + else + { + // Not navigable into + // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs. + // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set. + ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav); + + // But when flattened we directly reach items, adjust active layer mask accordingly + if (nav_flattened) + parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext; + } + if (g.HoveredWindow == child_window) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags; + //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd() + } + else + { + SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); + } + + g.WithinEndChildID = backup_within_end_child_id; + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return +} + +static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled) +{ + window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); + window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); + window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); + window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags); +} + +ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); +} + +ImGuiWindow* ImGui::FindWindowByName(const char* name) +{ + ImGuiID id = ImHashStr(name); + return FindWindowByID(id); +} + +static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) +{ + const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + window->ViewportPos = main_viewport->Pos; + if (settings->ViewportId) + { + window->ViewportId = settings->ViewportId; + window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y); + } + window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y)); + if (settings->Size.x > 0 && settings->Size.y > 0) + window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y)); + window->Collapsed = settings->Collapsed; + window->DockId = settings->DockId; + window->DockOrder = settings->DockOrder; +} + +static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) +{ + // Initial window state with e.g. default/arbitrary window position + // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. + const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + window->Pos = main_viewport->Pos + ImVec2(60, 60); + window->Size = window->SizeFull = ImVec2(0, 0); + window->ViewportPos = main_viewport->Pos; + window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; + + if (settings != NULL) + { + SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); + ApplyWindowSettings(window, settings); + } + window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values + + if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + window->AutoFitFramesX = window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } + else + { + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); + } +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) +{ + // Create window the first time + //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); + window->Flags = flags; + g.WindowsById.SetVoidPtr(window->ID, window); + + ImGuiWindowSettings* settings = NULL; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0) + window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); + + InitOrLoadWindowSettings(window, settings); + + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.push_front(window); // Quite slow but rare and only once + else + g.Windows.push_back(window); + + return window; +} + +static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window) +{ + return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window; +} + +static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window) +{ + return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window; +} + +static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window) +{ + // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller. + // Perhaps should tend further a neater test for this. + ImGuiContext& g = *GImGui; + ImVec2 size_min; + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) + { + size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE; + size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE; + } + else + { + size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE; + size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE; + } + + // Reduce artifacts with very small windows + ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window); + size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); + return size_min; +} + +static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired) +{ + ImGuiContext& g = *GImGui; + ImVec2 new_size = size_desired; + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint) + { + // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max. + ImRect cr = g.NextWindowData.SizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.NextWindowData.SizeCallback) + { + ImGuiSizeCallbackData data; + data.UserData = g.NextWindowData.SizeCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.NextWindowData.SizeCallback(&data); + new_size = data.DesiredSize; + } + new_size.x = IM_TRUNC(new_size.x); + new_size.y = IM_TRUNC(new_size.y); + } + + // Minimum size + ImVec2 size_min = CalcWindowMinSize(window); + return ImMax(new_size, size_min); +} + +static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal) +{ + bool preserve_old_content_sizes = false; + if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + preserve_old_content_sizes = true; + else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) + preserve_old_content_sizes = true; + if (preserve_old_content_sizes) + { + *content_size_current = window->ContentSize; + *content_size_ideal = window->ContentSizeIdeal; + return; + } + + content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); + content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); +} + +static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents, int axis_mask) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x; + const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y; + ImVec2 size_pad = window->WindowPadding * 2.0f; + ImVec2 size_desired; + size_desired[ImGuiAxis_X] = (axis_mask & 1) ? size_contents.x + size_pad.x + decoration_w_without_scrollbars : window->Size.x; + size_desired[ImGuiAxis_Y] = (axis_mask & 2) ? size_contents.y + size_pad.y + decoration_h_without_scrollbars : window->Size.y; + + // Determine maximum window size + // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction + ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX); + if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0) + { + if (!window->ViewportOwned) + size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; + const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; + if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) + size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f; + } + + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Tooltip always resize (up to maximum size) + return ImMin(size_desired, size_max); + } + else + { + ImVec2 size_min = CalcWindowMinSize(window); + ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max); + + // When the window cannot fit all contents (either because of constraints, either because screen is too small), + // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. + ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); + bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); + bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); + if (will_have_scrollbar_x) + size_auto_fit.y += style.ScrollbarSize; + if (will_have_scrollbar_y) + size_auto_fit.x += style.ScrollbarSize; + return size_auto_fit; + } +} + +ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window) +{ + ImVec2 size_contents_current; + ImVec2 size_contents_ideal; + CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal); + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal, ~0); + ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); + return size_final; +} + +static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window) +{ + if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + return ImGuiCol_PopupBg; + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive) + return ImGuiCol_ChildBg; + return ImGuiCol_WindowBg; +} + +static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target_arg, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) +{ + ImVec2 corner_target = corner_target_arg; + if (window->Flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent + { + ImGuiWindow* parent_window = window->ParentWindow; + ImGuiWindowFlags parent_flags = parent_window->Flags; + ImRect limit_rect = parent_window->InnerRect; + limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); + if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)) + corner_target.x = ImClamp(corner_target.x, limit_rect.Min.x, limit_rect.Max.x); + if (parent_flags & ImGuiWindowFlags_NoScrollbar) + corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y); + } + ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left + ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right + ImVec2 size_expected = pos_max - pos_min; + ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected); + *out_pos = pos_min; + if (corner_norm.x == 0.0f) + out_pos->x -= (size_constrained.x - size_expected.x); + if (corner_norm.y == 0.0f) + out_pos->y -= (size_constrained.y - size_expected.y); + *out_size = size_constrained; +} + +// Data for resizing from resize grip / corner +struct ImGuiResizeGripDef +{ + ImVec2 CornerPosN; + ImVec2 InnerDir; + int AngleMin12, AngleMax12; +}; +static const ImGuiResizeGripDef resize_grip_def[4] = +{ + { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right + { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left + { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused) + { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused) +}; + +// Data for resizing from borders +struct ImGuiResizeBorderDef +{ + ImVec2 InnerDir; // Normal toward inside + ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left) + float OuterAngle; // Angle toward outside +}; +static const ImGuiResizeBorderDef resize_border_def[4] = +{ + { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left + { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right + { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up + { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down +}; + +static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) +{ + ImRect rect = window->Rect(); + if (thickness == 0.0f) + rect.Max -= ImVec2(1, 1); + if (border_n == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } + if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } + if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } + if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } + IM_ASSERT(0); + return ImRect(); +} + +// 0..3: corners (Lower-right, Lower-left, Unused, Unused) +ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n) +{ + IM_ASSERT(n >= 0 && n < 4); + ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +} + +// Borders (Left, Right, Up, Down) +ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir) +{ + IM_ASSERT(dir >= 0 && dir < 4); + int n = (int)dir + 4; + ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +} + +// Handle resize for: Resize Grips, Borders, Gamepad +// Return true when using auto-fit (double-click on resize grip) +static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) +{ + ImGuiContext& g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + + if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + return false; + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0) + return false; + if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. + return false; + + int ret_auto_fit_mask = 0x00; + const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); + const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f; + const float grip_hover_outer_size = g.WindowsBorderHoverPadding; + + ImRect clamp_rect = visibility_rect; + const bool window_move_from_title_bar = !(window->BgClickFlags & ImGuiWindowBgClickFlags_Move) && !(window->Flags & ImGuiWindowFlags_NoTitleBar); + if (window_move_from_title_bar) + clamp_rect.Min.y -= window->TitleBarHeight; + + ImVec2 pos_target(FLT_MAX, FLT_MAX); + ImVec2 size_target(FLT_MAX, FLT_MAX); + + // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time). + // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits. + // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. + // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. + // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). + // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. + const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); + if (clip_with_viewport_rect) + window->ClipRect = window->Viewport->GetMainRect(); + + // Resize grips and borders are on layer 1 + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + + // Manual resize grips + PushID("#RESIZE"); + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN); + + // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window + bool hovered, held; + ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size); + if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x); + if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); + ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID() + ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav); + ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); + //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); + if (hovered || held) + SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE); + + if (held && g.IO.MouseDoubleClicked[0]) + { + // Auto-fit when double-clicking + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); + size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); + ret_auto_fit_mask = 0x03; // Both axes + ClearActiveID(); + } + else if (held) + { + // Resize from any of the four corners + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX); + ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip + corner_target = ImClamp(corner_target, clamp_min, clamp_max); + CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target); + } + + // Only lower-left grip is visible before hovering/activating + const bool resize_grip_visible = held || hovered || (resize_grip_n == 0 && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0); + if (resize_grip_visible) + resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + } + + int resize_border_mask = 0x00; + if (window->Flags & ImGuiWindowFlags_ChildWindow) + resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0); + else + resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00; + for (int border_n = 0; border_n < 4; border_n++) + { + if ((resize_border_mask & (1 << border_n)) == 0) + continue; + const ImGuiResizeBorderDef& def = resize_border_def[border_n]; + const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + + bool hovered, held; + ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding); + ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID() + ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav); + ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); + //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); + if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) + hovered = false; + if (hovered || held) + SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS); + if (held && g.IO.MouseDoubleClicked[0]) + { + // Double-clicking bottom or right border auto-fit on this axis + // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases. + if (border_n == 1 || border_n == 3) // Right and bottom border + { + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, 1 << axis); + size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis]; + ret_auto_fit_mask |= (1 << axis); + hovered = held = false; // So border doesn't show highlighted at new position + } + ClearActiveID(); + } + else if (held) + { + // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop. + // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually. + // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! + const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true)); + if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing) + { + g.WindowResizeBorderExpectedRect = border_rect; + g.WindowResizeRelativeMode = false; + } + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0) + g.WindowResizeRelativeMode = true; + + const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size); + const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis]; + const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above. + + // Use absolute mode position + ImVec2 border_target = window->Pos; + border_target[axis] = border_target_abs_mode_for_axis; + + // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position. + bool ignore_resize = false; + if (g.WindowResizeRelativeMode) + { + //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode"); + border_target[axis] = border_target_rel_mode_for_axis; + if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis)) + ignore_resize = true; + } + + // Clamp, apply + ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX); + border_target = ImClamp(border_target, clamp_min, clamp_max); + if (!ignore_resize) + CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target); + } + if (hovered) + *border_hovered = border_n; + if (held) + *border_held = border_n; + } + PopID(); + + // Restore nav layer + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + + // Navigation resize (keyboard/gamepad) + // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user. + // Not even sure the callback works here. + if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window) + { + ImVec2 nav_resize_dir; + if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift) + nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow); + if (g.NavInputSource == ImGuiInputSource_Gamepad) + nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown); + if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f) + { + const float NAV_RESIZE_SPEED = 600.0f; + const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * GetScale(); + g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step; + g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size + g.NavWindowingToggleLayer = false; + g.NavHighlightItemUnderNav = true; + resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); + ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize); + if (accum_floored.x != 0.0f || accum_floored.y != 0.0f) + { + // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. + size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored); + g.NavWindowingAccumDeltaSize -= accum_floored; + } + } + } + + // Apply back modified position/size to window + const ImVec2 old_pos = window->Pos; + const ImVec2 old_size = window->SizeFull; + if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x)) + window->Size.x = window->SizeFull.x = size_target.x; + if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y)) + window->Size.y = window->SizeFull.y = size_target.y; + if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x)) + window->Pos.x = ImTrunc(pos_target.x); + if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y)) + window->Pos.y = ImTrunc(pos_target.y); + if (old_pos.x != window->Pos.x || old_pos.y != window->Pos.y || old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) + MarkIniSettingsDirty(window); + + // Recalculate next expected border expected coordinates + if (*border_held != -1) + g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding); + + return ret_auto_fit_mask; +} + +static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect) +{ + ImVec2 size_for_clamping = window->Size; + const bool move_from_title_bar_only = (window->BgClickFlags & ImGuiWindowBgClickFlags_Move) == 0; + if (move_from_title_bar_only && window->DockNodeAsHost) + size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here. + else if (move_from_title_bar_only && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + size_for_clamping.y = window->TitleBarHeight; + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); +} + +static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size) +{ + const ImGuiResizeBorderDef& def = resize_border_def[border_n]; + const float rounding = window->WindowRounding; + const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); + window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size); +} + +static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + const float border_size = window->WindowBorderSize; + const ImU32 border_col = GetColorU32(ImGuiCol_Border); + if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0) + window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize); + else if (border_size > 0.0f) + { + if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border. + RenderWindowOuterSingleBorder(window, 1, border_col, border_size); + if (window->ChildFlags & ImGuiChildFlags_ResizeY) + RenderWindowOuterSingleBorder(window, 3, border_col, border_size); + } + if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1) + { + const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered; + const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered); + RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual + } + if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + float y = window->Pos.y + window->TitleBarHeight - 1; + window->DrawList->AddLine(ImVec2(window->Pos.x + border_size * 0.5f, y), ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), border_col, g.Style.FrameBorderSize); + } +} + +// Draw background and borders +// Draw and handle scrollbars +void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + // Ensure that Scrollbar() doesn't read last frame's SkipItems + IM_ASSERT(window->BeginCount == 0); + window->SkipItems = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + + // Draw window + handle manual resize + // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame. + const float window_rounding = window->WindowRounding; + const float window_border_size = window->WindowBorderSize; + if (window->Collapsed) + { + // Title bar only + const float backup_border_size = style.FrameBorderSize; + g.Style.FrameBorderSize = window->WindowBorderSize; + ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); + if (window->ViewportOwned) + title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse) + RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); + g.Style.FrameBorderSize = backup_border_size; + } + else + { + // Window background + if (!(flags & ImGuiWindowFlags_NoBackground)) + { + bool is_docking_transparent_payload = false; + if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload) + if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window) + is_docking_transparent_payload = true; + + ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window)); + if (window->ViewportOwned) + { + bg_col |= IM_COL32_A_MASK; // No alpha + if (is_docking_transparent_payload) + window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; + } + else + { + // Adjust alpha. For docking + bool override_alpha = false; + float alpha = 1.0f; + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha) + { + alpha = g.NextWindowData.BgAlphaVal; + override_alpha = true; + } + if (is_docking_transparent_payload) + { + alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override? + override_alpha = true; + } + if (override_alpha) + bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); + } + + // Render, for docked windows and host windows we ensure BG goes before decorations + if (window->DockIsActive) + window->DockNode->LastBgColor = bg_col; + if (flags & ImGuiWindowFlags_DockNodeHost) + bg_col = 0; + if (bg_col & IM_COL32_A_MASK) + { + ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size); + ImDrawFlags bg_rounding_flags; + if (window->DockIsActive) + bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, window->DockNode->HostWindow->Rect(), 0.0f); + else + bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom; + ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList; + if (window->DockIsActive) + bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); + bg_draw_list->AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags); + if (window->DockIsActive) + bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); + } + } + if (window->DockIsActive) + window->DockNode->IsBgDrawnThisFrame = true; + + // Title bar + // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, + // in order for their pos/size to be matching their undocking state.) + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); + if (window->ViewportOwned) + title_bar_col |= IM_COL32_A_MASK; // No alpha + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop); + } + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + ImRect menu_bar_rect = window->MenuBarRect(); + menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. + window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); + if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) + window->DrawList->AddLine(menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + + // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock + ImGuiDockNode* node = window->DockNode; + if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar()) + { + float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f); + float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f); + ImVec2 p = node->Pos; + ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit)); + ImGuiID unhide_id = window->GetID("#UNHIDE"); + KeepAliveID(unhide_id); + bool hovered, held; + if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren)) + node->WantHiddenTabBarToggle = true; + else if (held && IsMouseDragging(0)) + StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button + + // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. + ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(ImGuiAxis_X); + if (window->ScrollbarY) + Scrollbar(ImGuiAxis_Y); + + // Render resize grips (after their input handling so we don't have a frame of latency) + if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize)) + { + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImU32 col = resize_grip_col[resize_grip_n]; + if ((col & IM_COL32_A_MASK) == 0) + continue; + const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); + const float border_inner = IM_ROUND(window_border_size * 0.5f); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner))); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size))); + window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12); + window->DrawList->PathFillConvex(col); + } + } + + // Borders (for dock node host they will be rendered over after the tab bar) + if (handle_borders_and_resize_grips && !window->DockNodeAsHost) + RenderWindowOuterBorders(window); + } + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; +} + +// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. +// Render title text, collapse button, close button +void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + const bool has_close_button = (p_open != NULL); + const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None); + + // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref? + const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + + // Layout buttons + // FIXME: Would be nice to generalize the subtleties expressed here into reusable code. + float pad_l = style.FramePadding.x; + float pad_r = style.FramePadding.x; + float button_sz = g.FontSize; + ImVec2 close_button_pos; + ImVec2 collapse_button_pos; + if (has_close_button) + { + close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y); + pad_r += button_sz + style.ItemInnerSpacing.x; + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right) + { + collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y); + pad_r += button_sz + style.ItemInnerSpacing.x; + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left) + { + collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y); + pad_l += button_sz + style.ItemInnerSpacing.x; + } + + // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) + if (has_collapse_button) + if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL)) + window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function + + // Close button + if (has_close_button) + { + ImGuiItemFlags backup_item_flags = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_NoFocus; + if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) + *p_open = false; + g.CurrentItemFlags = backup_item_flags; + } + + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + g.CurrentItemFlags = item_flags_backup; + + // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. + const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f; + const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); + + // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + // while uncentered title text will still reach edges correctly. + if (pad_l > style.FramePadding.x) + pad_l += g.Style.ItemInnerSpacing.x; + if (pad_r > style.FramePadding.x) + pad_r += g.Style.ItemInnerSpacing.x; + if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f) + { + float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center + float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x); + pad_l = ImMax(pad_l, pad_extend * centerness); + pad_r = ImMax(pad_r, pad_extend * centerness); + } + + ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); + ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y); + if (flags & ImGuiWindowFlags_UnsavedDocument) + { + ImVec2 marker_pos; + marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x); + marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f; + if (marker_pos.x > layout_r.Min.x) + { + RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_UnsavedMarker)); + clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f)); + } + } + //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] + //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] + RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r); +} + +void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) +{ + window->ParentWindow = parent_window; + window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; + if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + { + window->RootWindowDockTree = parent_window->RootWindowDockTree; + if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost)) + window->RootWindow = parent_window->RootWindow; + } + if (parent_window && (flags & ImGuiWindowFlags_Popup)) + window->RootWindowPopupTree = parent_window->RootWindowPopupTree; + if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip))) // FIXME: simply use _NoTitleBar ? + window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; + while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened) + { + IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL); + window->RootWindowForNav = window->RootWindowForNav->ParentWindow; + } +} + +// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point. +// This is designed as a toy/test-bed for +void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + window->SkipRefresh = false; + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0) + return; + if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh) + { + // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused. + if (window->Appearing) // If currently appearing + return; + if (window->Hidden) // If was hidden (previous frame) + return; + if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow) + if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window)) + return; + if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow) + if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window)) + return; + window->DrawList = NULL; + window->SkipRefresh = true; + } +} + +static void SetWindowActiveForSkipRefresh(ImGuiWindow* window) +{ + window->Active = true; + for (ImGuiWindow* child : window->DC.ChildWindows) + if (!child->Hidden) + { + child->Active = child->SkipRefresh = true; + SetWindowActiveForSkipRefresh(child); + } +} + +// Push a new Dear ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required + IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + // Find or create + ImGuiWindow* window = FindWindowByName(name); + const bool window_just_created = (window == NULL); + if (window_just_created) + window = CreateNewWindow(name, flags); + + // [DEBUG] Debug break requested by user + if (g.DebugBreakInWindow == window->ID) + IM_DEBUG_BREAK(); + + // Automatically disable manual moving/resizing when NoInputs is set + if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; + + const int current_frame = g.FrameCount; + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow); + + // Update the Appearing flag (note: the BeginDocked() path may also set this to true later) + bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed + window_just_activated_by_user |= (window != popup_ref.Window); + } + + // Update Flags, LastFrameActive, BeginOrderXXX fields + const bool window_was_appearing = window->Appearing; + if (first_begin_of_the_frame) + { + UpdateWindowInFocusOrderList(window, window_just_created, flags); + window->Appearing = window_just_activated_by_user; + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + window->FlagsPreviousFrame = window->Flags; + window->Flags = (ImGuiWindowFlags)flags; + window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0; + window->LastFrameActive = current_frame; + window->LastTimeActive = (float)g.Time; + window->BeginOrderWithinParent = 0; + window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++); + } + else + { + flags = window->Flags; + } + + // Docking + // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1) + IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock) + SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond); + if (first_begin_of_the_frame) + { + const bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL); + const bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window); + const bool dock_node_was_visible = window->DockNodeIsVisible; + const bool dock_tab_was_visible = window->DockTabIsVisible; + window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false; + + if (has_dock_node || new_auto_dock_node) + { + BeginDocked(window, p_open); + flags = window->Flags; + if (window->DockIsActive) + { + IM_ASSERT(window->DockNode != NULL); + g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints + } + + // Amend the Appearing flag + if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing) + { + window->Appearing = true; + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + } + } + } + + // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack + ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window; + ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) ? parent_window_in_stack : NULL) : window->ParentWindow; + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + // We allow window memory to be compacted so recreate the base stack when needed. + if (window->IDStack.Size == 0) + window->IDStack.push_back(window->ID); + + // Add to stack + g.CurrentWindow = window; + g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1); + ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back(); + window_stack_data.Window = window; + window_stack_data.ParentLastItemDataBackup = g.LastItemData; + window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled); + window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f; + ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin); + g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin; + if (flags & ImGuiWindowFlags_ChildMenu) + g.BeginMenuDepth++; + + // Update ->RootWindow and others pointers (before any possible call to FocusWindow) + if (first_begin_of_the_frame) + { + UpdateWindowParentAndRootLinks(window, flags, parent_window); + window->ParentWindowInBeginStack = parent_window_in_stack; + + // Focus route + // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, + // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) + window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL; + if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL) + if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute) + window->ParentWindowForFocusRoute = window->DockNode->HostWindow; + + // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute() + if (window->WindowClass.FocusRouteParentWindowId != 0) + { + window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId); + IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId. + } + + // Inherit SetWindowFontScale() from parent until we fix this system... + window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f; + } + + // Add to focus scope stack + PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID); + window->NavRootFocusScopeId = g.CurrentFocusScopeId; + + // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[] + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + popup_ref.Window = window; + popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent; + g.BeginPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + // Process SetNextWindow***() calls + // (FIXME: Consider splitting the HasXXX flags into X/Y components) + bool window_pos_set_by_api = false; + bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) + { + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) + { + // May be processed on the next frame if this is our first frame and we are measuring size + // FIXME: Look into removing the branch so everything can go through this same code path for consistency. + window->SetWindowPosVal = g.NextWindowData.PosVal; + window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + } + else + { + SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); + } + } + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) + { + window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); + window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); + if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild() + g.NextWindowData.SizeVal.x = window->SizeFull.x; + if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) + g.NextWindowData.SizeVal.y = window->SizeFull.y; + SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); + } + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) + { + if (g.NextWindowData.ScrollVal.x >= 0.0f) + { + window->ScrollTarget.x = g.NextWindowData.ScrollVal.x; + window->ScrollTargetCenterRatio.x = 0.0f; + } + if (g.NextWindowData.ScrollVal.y >= 0.0f) + { + window->ScrollTarget.y = g.NextWindowData.ScrollVal.y; + window->ScrollTargetCenterRatio.y = 0.0f; + } + } + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize) + window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; + else if (first_begin_of_the_frame) + window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass) + window->WindowClass = g.NextWindowData.WindowClass; + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed) + SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus) + FocusWindow(window); + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); + + // [EXPERIMENTAL] Skip Refresh mode + UpdateWindowSkipRefresh(window); + + // Nested root windows (typically tooltips) override disabled state + if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window) + BeginDisabledOverrideReenable(); + + // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() + g.CurrentWindow = NULL; + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + if (first_begin_of_the_frame && !window->SkipRefresh) + { + // Initialize + const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) + const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); + window->Active = true; + window->HasCloseButton = (p_open != NULL); + window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); + window->IDStack.resize(1); + window->DrawList->_ResetForNewFrame(); + window->DC.CurrentTableIdx = -1; + if (flags & ImGuiWindowFlags_DockNodeHost) + { + window->DrawList->ChannelsSplit(2); + window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later + } + + // Restore buffer capacity when woken from a compacted state, to avoid + if (window->MemoryCompacted) + GcAwakeTransientWindowBuffers(window); + + // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). + // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. + bool window_title_visible_elsewhere = false; + if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive)) + window_title_visible_elsewhere = true; + else if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->WasActive && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using Ctrl+Tab + window_title_visible_elsewhere = true; + else if (flags & ImGuiWindowFlags_ChildMenu) + window_title_visible_elsewhere = true; + if ((window_title_visible_elsewhere || window_just_activated_by_user) && !window_just_created && strcmp(name, window->Name) != 0) + { + size_t buf_len = (size_t)window->NameBufLen; + window->Name = ImStrdupcpy(window->Name, &buf_len, name); + window->NameBufLen = (int)buf_len; + } + + // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + + // Update contents size from last frame for auto-fitting (or use explicit size) + CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal); + + // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors + // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because + // it has a single usage before this code block and may be set below before it is finally checked. + if (window->HiddenFramesCanSkipItems > 0) + window->HiddenFramesCanSkipItems--; + if (window->HiddenFramesCannotSkipItems > 0) + window->HiddenFramesCannotSkipItems--; + if (window->HiddenFramesForRenderOnly > 0) + window->HiddenFramesForRenderOnly--; + + // Hide new windows for one frame until they calculate their size + if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) + window->HiddenFramesCannotSkipItems = 1; + + // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) + // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. + if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) + { + window->HiddenFramesCannotSkipItems = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_x_set_by_api) + window->Size.x = window->SizeFull.x = 0.f; + if (!window_size_y_set_by_api) + window->Size.y = window->SizeFull.y = 0.f; + window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f); + } + } + + // SELECT VIEWPORT + // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + + WindowSelectViewport(window); + SetCurrentViewport(window, window->Viewport); + SetCurrentWindow(window); + flags = window->Flags; + + // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + + if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow)) + window->WindowBorderSize = style.ChildBorderSize; + else + window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; + window->WindowPadding = style.WindowPadding; + if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f) + window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + + // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. + window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); + window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; + window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f; + window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f; + window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window. + + // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible. + // Those flags will be altered further down in the function depending on more conditions. + bool use_current_size_for_scrollbar_x = window_just_created; + bool use_current_size_for_scrollbar_y = window_just_created; + if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f) + use_current_size_for_scrollbar_x = true; + if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252 + use_current_size_for_scrollbar_y = true; + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive) + { + // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), + // so verify that we don't have items over the title bar. + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max)) + if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner) + window->WantCollapseToggle = true; + if (window->WantCollapseToggle) + { + window->Collapsed = !window->Collapsed; + if (!window->Collapsed) + use_current_size_for_scrollbar_y = true; + MarkIniSettingsDirty(window); + } + } + else + { + window->Collapsed = false; + } + window->WantCollapseToggle = false; + + // SIZE + + // Outer Decoration Sizes + // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations). + const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes; + window->DecoOuterSizeX1 = 0.0f; + window->DecoOuterSizeX2 = 0.0f; + window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight; + window->DecoOuterSizeY2 = 0.0f; + window->ScrollbarSizes = ImVec2(0.0f, 0.0f); + + // Calculate auto-fit size, handle automatic resize + // - Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. + // - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + // - Auto-fit may only grow window during the first few frames. + { + const bool size_auto_fit_x_always = !window_size_x_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0); + const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0); + int size_auto_fit_mask = 0; + if (size_auto_fit_x_always || size_auto_fit_x_current) + size_auto_fit_mask |= (1 << ImGuiAxis_X); + if (size_auto_fit_y_always || size_auto_fit_y_current) + size_auto_fit_mask |= (1 << ImGuiAxis_Y); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, size_auto_fit_mask); + + const ImVec2 old_size = window->SizeFull; + if (size_auto_fit_x_always || size_auto_fit_x_current) + { + if (size_auto_fit_x_always) + window->SizeFull.x = size_auto_fit.x; + else + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } + if (size_auto_fit_y_always || size_auto_fit_y_current) + { + if (size_auto_fit_y_always) + window->SizeFull.y = size_auto_fit.y; + else + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } + if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) + MarkIniSettingsDirty(window); + } + + // Apply minimum/maximum window size constraints and final size + window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); + window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; + + // POSITION + + // Popup latch its initial position, will position itself when it appears next frame + if (window_just_activated_by_user) + { + window->AutoPosLastDirection = ImGuiDir_None; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() + window->Pos = g.BeginPopupStack.back().OpenPopupPos; + } + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + IM_ASSERT(parent_window && parent_window->Active); + window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = parent_window->DC.CursorPos; + } + + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); + if (window_pos_with_pivot) + SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) + else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = FindBestWindowPosForPopup(window); + + // Late create viewport if we don't fit within our current host viewport. + if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized)) + if (!window->Viewport->GetMainRect().Contains(window->Rect())) + { + // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport) + //ImGuiViewport* old_viewport = window->Viewport; + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + + // FIXME-DPI + //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong + SetCurrentViewport(window, window->Viewport); + SetCurrentWindow(window); + } + + if (window->ViewportOwned) + WindowSyncOwnedViewport(window, parent_window_in_stack); + + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(window->Viewport->GetMainRect()); + ImRect viewport_work_rect(window->Viewport->GetWorkRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding); + + // Clamp position/size so window stays visible within its viewport or monitor + // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + // FIXME: Similar to code in GetWindowAllowedExtentRect() + if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow)) + { + if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) + { + ClampWindowPos(window, visibility_rect); + } + else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) + { + if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree) + { + // While moving windows we allow them to straddle monitors (#7299, #3071) + visibility_rect = g.PlatformMonitorsFullWorkRect; + } + else + { + // When not moving ensure visible in its monitor + // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport. + const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport); + visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize); + } + visibility_rect.Expand(-visibility_padding); + ClampWindowPos(window, visibility_rect); + } + } + window->Pos = ImTrunc(window->Pos); + + // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + // Large values tend to lead to variety of artifacts and are not recommended. + if ((flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive) + window->WindowRounding = style.ChildRounding; + else if (window->RootWindowDockTree->ViewportOwned) + window->WindowRounding = 0.0f; + else + window->WindowRounding = ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; + + // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. + //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f); + + // Apply window focus (new and reactivated windows are moved to front) + bool want_focus = false; + if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + { + if (flags & ImGuiWindowFlags_Popup) + want_focus = true; + else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip)) + want_focus = true; + } + + // [Test Engine] Register whole window in the item system (before submitting further decorations) +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (g.TestEngineHookItems) + { + IM_ASSERT(window->IDStack.Size == 1); + window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself. + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL); + IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0); + window->IDStack.Size = 1; + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + + } +#endif + + // Decide if we are going to handle borders and resize grips + // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815) + // Whenever we add support for full decorated child windows we will likely make this logic more general. + bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive); + if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems) + handle_borders_and_resize_grips = false; + + // Handle manual resize: Resize Grips, Borders, Gamepad + // Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. + int border_hovered = -1, border_held = -1; + ImU32 resize_grip_col[4] = {}; + int resize_grip_count; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + resize_grip_count = ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) ? 1 : 0; + else + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + + const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); + if (handle_borders_and_resize_grips && !window->Collapsed) + if (int auto_fit_mask = UpdateWindowManualResize(window, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) + { + if (auto_fit_mask & (1 << ImGuiAxis_X)) + use_current_size_for_scrollbar_x = true; + if (auto_fit_mask & (1 << ImGuiAxis_Y)) + use_current_size_for_scrollbar_y = true; + } + window->ResizeBorderHovered = (signed char)border_hovered; + window->ResizeBorderHeld = (signed char)border_held; + + // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either) + if (window->ViewportOwned) + { + if (!window->Viewport->PlatformRequestMove) + window->Viewport->Pos = window->Pos; + if (!window->Viewport->PlatformRequestResize) + window->Viewport->Size = window->Size; + window->Viewport->UpdateWorkRect(); + viewport_rect = window->Viewport->GetMainRect(); + } + + // Save last known viewport position within the window itself (so it can be saved in .ini file and restored) + window->ViewportPos = window->Viewport->Pos; + + // SCROLLBAR VISIBILITY + + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). + if (!window->Collapsed) + { + // When reading the current size we need to read it after size constraints have been applied. + // Intentionally use previous frame values for InnerRect and ScrollbarSizes. + // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet. + ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)); + ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame; + ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; + float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; + float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + bool scrollbar_x_prev = window->ScrollbarX; + //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + + // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488) + // (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause. + // The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it) + window->ScrollbarXStabilizeToggledHistory <<= 1; + window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00; + const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history. + if (scrollbar_x_stabilize) + window->ScrollbarX = true; + //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled) + // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name); + window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize; + + if (window->ScrollbarX && !window->ScrollbarY) + window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + + // Amend the partially filled window->DecorationXXX values. + window->DecoOuterSizeX2 += window->ScrollbarSizes.x; + window->DecoOuterSizeY2 += window->ScrollbarSizes.y; + } + + // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + // Update various regions. Variables they depend on should be set above in this function. + // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. + + // Outer rectangle + // Not affected by window border size. Used by: + // - FindHoveredWindow() (w/ extra padding when border resize is enabled) + // - Begin() initial clipping rect for drawing window background and borders. + // - Begin() clipping whole child + const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; + const ImRect outer_rect = window->Rect(); + const ImRect title_bar_rect = window->TitleBarRect(); + window->OuterRectClipped = outer_rect; + if (window->DockIsActive) + window->OuterRectClipped.Min.y += window->TitleBarHeight; + window->OuterRectClipped.ClipWith(host_rect); + + // Inner rectangle + // Not affected by window border size. Used by: + // - InnerClipRect + // - ScrollToRectEx() + // - NavUpdatePageUpPageDown() + // - Scrollbar() + window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1; + window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1; + window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2; + window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2; + + // Inner clipping rectangle. + // - Extend a outside of normal work region up to borders. + // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + // - It also makes clipped items be more noticeable. + // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312 + // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + // Affected by window/frame border size. Used by: + // - Begin() initial clip rect + float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + + // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner. + // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize, + // see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5f here). + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f); + window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f); + window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f); + window->InnerClipRect.ClipWithFull(host_rect); + + // SCROLLING + + // Lock down maximum scrolling + // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate + // for right/bottom aligned items without creating a scrollbar. + window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); + window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); + + // Apply scrolling + window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); + window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f; + + // DRAWING + + // Setup draw list and outer clipping rectangle + IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); + window->DrawList->PushTexture(g.Font->OwnerAtlas->TexRef); + PushClipRect(host_rect.Min, host_rect.Max, false); + + // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) + // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) + const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible; + if (is_undocked_or_docked_visible) + { + bool render_decorations_in_parent = false; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) + { + // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here) + // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs + ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL; + bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false; + bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0); + if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping) + render_decorations_in_parent = true; + } + if (render_decorations_in_parent) + window->DrawList = parent_window->DrawList; + + // Handle title bar, scrollbar, resize grips and resize borders + const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; + const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); + RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); + + if (render_decorations_in_parent) + window->DrawList = &window->DrawListInst; + } + + // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + // Work rectangle. + // Affected by window padding and border size. Used by: + // - Columns() for right-most edge + // - TreeNode(), CollapsingHeader() for right-most edge + // - BeginTabBar() for right-most edge + const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); + const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); + const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2))); + const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2))); + window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); + window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); + window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; + window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y; + window->ParentWorkRect = window->WorkRect; + + // [LEGACY] Content Region + // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling. + // Used by: + // - Mouse wheel scrolling + many other things + window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1; + window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1; + window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2))); + window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2))); + + // Setup drawing context + // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffset.x = 0.0f; + window->DC.ColumnsOffset.x = 0.0f; + + // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount. + // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64. + double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x; + double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1; + window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y); + window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y)); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CursorMaxPos = window->DC.CursorStartPos; + window->DC.IdealMaxPos = window->DC.CursorStartPos; + window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.IsSameLine = window->DC.IsSetPos = false; + + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext; + window->DC.NavLayersActiveMaskNext = 0x00; + window->DC.NavIsScrollPushableX = true; + window->DC.NavHideHighlightOneFrame = false; + window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f); + + window->DC.MenuBarAppending = false; + window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user); + window->DC.TreeDepth = 0; + window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00; + window->DC.ChildWindows.resize(0); + window->DC.StateStorage = &window->StateStorage; + window->DC.CurrentColumns = NULL; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + + // Default item width. Make it proportional to window size if window manually resizes + const bool is_resizable_window = (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)); + if (is_resizable_window) + window->DC.ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); + else + window->DC.ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); + window->DC.ItemWidth = window->DC.ItemWidthDefault; + window->DC.ItemWidthStack.resize(0); + window->DC.TextWrapPos = -1.0f; // Disabled + window->DC.TextWrapPosStack.resize(0); + if (flags & ImGuiWindowFlags_Modal) + window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg)); + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + + // Clear SetNextWindowXXX data (can aim to move this higher in the function) + g.NextWindowData.ClearFlags(); + + // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + // We ImGuiFocusRequestFlags_UnlessBelowModal to: + // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed. + // - Position window behind the modal that is not a begin-parent of this window. + if (want_focus) + FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal); + if (want_focus && window == g.NavWindow) + NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls + + // Close requested by platform window (apply to all windows in this viewport) + // FIXME: Investigate removing the 'window->Viewport != GetMainViewport()' test, which seems superfluous. + if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport()) + if (window->DockNode == NULL || (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0) + { + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name); + *p_open = false; + g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on Alt-F4 so we disable Alt for menu toggle. False positive not an issue. // FIXME-NAV: Try removing. + } + + // Pressing Ctrl+C copy window content into the clipboard + // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope. + // [EXPERIMENTAL] Text outputs has many issues. + if (g.IO.ConfigWindowsCopyContentsWithCtrlC) + if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C)) + LogToClipboard(0); + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open); + else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive) + LogText("%.*s\n", (int)(FindRenderedTextEnd(window->Name) - window->Name), window->Name); + + // Clear hit test shape every frame + window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; + + if (flags & ImGuiWindowFlags_Tooltip) + g.TooltipPreviousWindow = window; + + if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. + // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. + if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0) + BeginDockableDragDropSource(window); + + // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead. + if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking)) + if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window) + if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost)) + BeginDockableDragDropTarget(window); + } + + // Set default BgClickFlags + // This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. + // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. + window->BgClickFlags = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->BgClickFlags : (g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move); + + // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). + // This is useful to allow creating context menus on title bar only, etc. + window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None; + window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; + SetLastItemDataForWindow(window, title_bar_rect); + + // [DEBUG] +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId)) + DebugLocateItemResolveWithLastItem(); +#endif + + // [Test Engine] Register title bar / tab with MoveId. +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + { + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData); + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + } +#endif + } + else + { + // Skip refresh always mark active + if (window->SkipRefresh) + SetWindowActiveForSkipRefresh(window); + + // Append + SetCurrentViewport(window, window->Viewport); + SetCurrentWindow(window); + g.NextWindowData.ClearFlags(); + SetLastItemDataForWindow(window, window->TitleBarRect()); + } + + if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); + + // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) + window->WriteAccessed = false; + window->BeginCount++; + + // Update visibility + if (first_begin_of_the_frame && !window->SkipRefresh) + { + // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + // This is analogous to regular windows being hidden from one frame. + // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. + if (window->DockIsActive && !window->DockTabIsVisible) + { + if (window->LastFrameJustFocused == g.FrameCount) + window->HiddenFramesCannotSkipItems = 1; + else + window->HiddenFramesCanSkipItems = 1; + } + + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu)) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive); + const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + if (!g.LogEnabled && !nav_request) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + { + if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + window->HiddenFramesCannotSkipItems = 1; + else + window->HiddenFramesCanSkipItems = 1; + } + + // Hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) + window->HiddenFramesCanSkipItems = 1; + if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0) + window->HiddenFramesCannotSkipItems = 1; + } + + // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) + if (style.Alpha <= 0.0f) + window->HiddenFramesCanSkipItems = 1; + + // Update the Hidden flag + bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); + window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0); + + // Disable inputs for requested number of frames + if (window->DisableInputsFrames > 0) + { + window->DisableInputsFrames--; + window->Flags |= ImGuiWindowFlags_NoInputs; + } + + // Update the SkipItems flag, used to early out of all items functions (no layout required) + bool skip_items = false; + if (window->Collapsed || !window->Active || hidden_regular) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; + + // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value. + if (window->SkipItems) + window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask; + + // Sanity check: there are two spots which can set Appearing = true + // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false + // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert. + if (window->SkipItems && !window->Appearing) + IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177 + } + else if (first_begin_of_the_frame) + { + // Skip refresh mode + window->SkipItems = true; + } + + // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors. + // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing) +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (!window->IsFallbackWindow) + if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)) + { + if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; } + if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; } + return false; + } +#endif + + return !window->SkipItems; +} + +void ImGui::End() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Error checking: verify that user hasn't called End() too many times! + if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow) + { + IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!"); + return; + } + ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back(); + + // Error checking: verify that user doesn't directly call End() on a child window. + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive) + IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!"); + + // Close anything that is open + if (window->DC.CurrentColumns) + EndColumns(); + if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle + PopClipRect(); + PopFocusScope(); + if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window) + EndDisabledOverrideReenable(); + + if (window->SkipRefresh) + { + IM_ASSERT(window->DrawList == NULL); + window->DrawList = &window->DrawListInst; + } + + // Stop logging + if (g.LogWindow == window) // FIXME: add more options for scope of logging + LogFinish(); + + if (window->DC.IsSetPos) + ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); + + // Docking: report contents sizes to parent to allow for auto-resize + if (window->DockNode && window->DockTabIsVisible) + if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK + host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding; + + // Pop from window stack + g.LastItemData = window_stack_data.ParentLastItemDataBackup; + if (window->Flags & ImGuiWindowFlags_ChildMenu) + g.BeginMenuDepth--; + if (window->Flags & ImGuiWindowFlags_Popup) + g.BeginPopupStack.pop_back(); + + // Error handling, state recovery + if (g.IO.ConfigErrorRecovery) + ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin); + + g.CurrentWindowStack.pop_back(); + SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window); + if (g.CurrentWindow) + SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport); +} + +void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) +{ + ImGuiContext& g = *GImGui; + ImGuiItemFlags item_flags = g.CurrentItemFlags; + IM_ASSERT(item_flags == g.ItemFlagsStack.back()); + if (enabled) + item_flags |= option; + else + item_flags &= ~option; + g.CurrentItemFlags = item_flags; + g.ItemFlagsStack.push_back(item_flags); +} + +void ImGui::PopItemFlag() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR_RET(g.ItemFlagsStack.Size > 1, "Calling PopItemFlag() too many times!"); + g.ItemFlagsStack.pop_back(); + g.CurrentItemFlags = g.ItemFlagsStack.back(); +} + +// BeginDisabled()/EndDisabled() +// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) +// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently. +// - Feedback welcome at https://github.com/ocornut/imgui/issues/211 +// - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions. +// (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) +// - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED. +void ImGui::BeginDisabled(bool disabled) +{ + ImGuiContext& g = *GImGui; + bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + if (!was_disabled && disabled) + { + g.DisabledAlphaBackup = g.Style.Alpha; + g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha); + } + if (was_disabled || disabled) + g.CurrentItemFlags |= ImGuiItemFlags_Disabled; + g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize? + g.DisabledStackSize++; +} + +void ImGui::EndDisabled() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!"); + g.DisabledStackSize--; + bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + //PopItemFlag(); + g.ItemFlagsStack.pop_back(); + g.CurrentItemFlags = g.ItemFlagsStack.back(); + if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0) + g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar(); +} + +// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name. +// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal. +// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled(). +void ImGui::BeginDisabledOverrideReenable() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled); + g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha; + g.Style.Alpha = g.DisabledAlphaBackup; + g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled; + g.ItemFlagsStack.push_back(g.CurrentItemFlags); + g.DisabledStackSize++; +} + +void ImGui::EndDisabledOverrideReenable() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.DisabledStackSize > 0); + g.DisabledStackSize--; + g.ItemFlagsStack.pop_back(); + g.CurrentItemFlags = g.ItemFlagsStack.back(); + g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup; +} + +// ATTENTION THIS IS IN LEGACY LOCAL SPACE. +void ImGui::PushTextWrapPos(float wrap_local_pos_x) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos); + window->DC.TextWrapPos = wrap_local_pos_x; +} + +void ImGui::PopTextWrapPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR_RET(window->DC.TextWrapPosStack.Size > 0, "Calling PopTextWrapPos() too many times!"); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.back(); + window->DC.TextWrapPosStack.pop_back(); +} + +static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy) +{ + ImGuiWindow* last_window = NULL; + while (last_window != window) + { + last_window = window; + window = window->RootWindow; + if (popup_hierarchy) + window = window->RootWindowPopupTree; + if (dock_hierarchy) + window = window->RootWindowDockTree; + } + return window; +} + +bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy) +{ + ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy); + if (window_root == potential_parent) + return true; + while (window != NULL) + { + if (window == potential_parent) + return true; + if (window == window_root) // end of chain + return false; + window = window->ParentWindow; + } + return false; +} + +bool ImGui::IsWindowInBeginStack(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + for (int n = g.CurrentWindowStack.Size - 1; n >= 0; n--) + if (g.CurrentWindowStack[n].Window == window) + return true; + return false; +} + +bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent) +{ + if (window->RootWindow == potential_parent) + return true; + while (window != NULL) + { + if (window == potential_parent) + return true; + window = window->ParentWindowInBeginStack; + } + return false; +} + +bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below) +{ + ImGuiContext& g = *GImGui; + + // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array + const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below); + if (display_layer_delta != 0) + return display_layer_delta > 0; + + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow* candidate_window = g.Windows[i]; + if (candidate_window == potential_above) + return true; + if (candidate_window == potential_below) + return false; + } + return false; +} + +// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. +// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. +bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!"); + + ImGuiWindow* ref_window = g.HoveredWindow; + ImGuiWindow* cur_window = g.CurrentWindow; + if (ref_window == NULL) + return false; + + if ((flags & ImGuiHoveredFlags_AnyWindow) == 0) + { + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0; + const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0; + if (flags & ImGuiHoveredFlags_RootWindow) + cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + bool result; + if (flags & ImGuiHoveredFlags_ChildWindows) + result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + result = (ref_window == cur_window); + if (!result) + return false; + } + + if (!IsWindowContentHoverable(ref_window, flags)) + return false; + if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId) + return false; + + // When changing hovered window we requires a bit of stationary delay before activating hover timer. + // FIXME: We don't support delay other than stationary one for now, other delay would need a way + // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true + // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache. + // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow. + if (flags & ImGuiHoveredFlags_ForTooltip) + flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse); + if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID) + return false; + + return true; +} + +ImGuiID ImGui::GetWindowDockID() +{ + ImGuiContext& g = *GImGui; + return g.CurrentWindow->DockId; +} + +bool ImGui::IsWindowDocked() +{ + ImGuiContext& g = *GImGui; + return g.CurrentWindow->DockIsActive; +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.x; +} + +float ImGui::GetWindowHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->Pos; +} + +void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowPosAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); + + // Set + const ImVec2 old_pos = window->Pos; + window->Pos = ImTrunc(pos); + ImVec2 offset = window->Pos - old_pos; + if (offset.x == 0.0f && offset.y == 0.0f) + return; + MarkIniSettingsDirty(window); + // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. + window->DC.IdealMaxPos += offset; + window->DC.CursorStartPos += offset; +} + +void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + SetWindowPos(window, pos, cond); +} + +void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowPos(window, pos, cond); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Size; +} + +void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize) + if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0) + window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0; + if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0) + window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0; + + // Set + ImVec2 old_size = window->SizeFull; + if (size.x <= 0.0f) + window->AutoFitOnlyGrows = false; + else + window->SizeFull.x = IM_TRUNC(size.x); + if (size.y <= 0.0f) + window->AutoFitOnlyGrows = false; + else + window->SizeFull.y = IM_TRUNC(size.y); + if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) + MarkIniSettingsDirty(window); +} + +void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) +{ + SetWindowSize(GImGui->CurrentWindow, size, cond); +} + +void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowSize(window, size, cond); +} + +void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) + return; + window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Queue applying in Begin() + if (window->WantCollapseToggle) + window->Collapsed ^= 1; + window->WantCollapseToggle = (window->Collapsed != collapsed); +} + +void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) +{ + IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters + window->HitTestHoleSize = ImVec2ih(size); + window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); +} + +void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window) +{ + window->Hidden = window->SkipItems = true; + window->HiddenFramesCanSkipItems = 1; +} + +void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); +} + +bool ImGui::IsWindowCollapsed() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Collapsed; +} + +bool ImGui::IsWindowAppearing() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Appearing; +} + +void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowCollapsed(window, collapsed, cond); +} + +void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos; + g.NextWindowData.PosVal = pos; + g.NextWindowData.PosPivotVal = pivot; + g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; + g.NextWindowData.PosUndock = true; +} + +void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize; + g.NextWindowData.SizeVal = size; + g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; +} + +// For each axis: +// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width. +// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint. +// - See "Demo->Examples->Constrained-resizing window" for examples. +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint; + g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); + g.NextWindowData.SizeCallback = custom_callback; + g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; +} + +// Content size = inner scrollable rectangle, padded with WindowPadding. +// SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize; + g.NextWindowData.ContentSizeVal = ImTrunc(size); +} + +void ImGui::SetNextWindowScroll(const ImVec2& scroll) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll; + g.NextWindowData.ScrollVal = scroll; +} + +void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed; + g.NextWindowData.CollapsedVal = collapsed; + g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowBgAlpha(float alpha) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha; + g.NextWindowData.BgAlphaVal = alpha; +} + +void ImGui::SetNextWindowViewport(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport; + g.NextWindowData.ViewportId = id; +} + +void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock; + g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always; + g.NextWindowData.DockId = id; +} + +void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass; + g.NextWindowData.WindowClass = *window_class; +} + +// This is experimental and meant to be a toy for exploring a future/wider range of features. +void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy; + g.NextWindowData.RefreshFlagsVal = flags; +} + +ImDrawList* ImGui::GetWindowDrawList() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DrawList; +} + +float ImGui::GetWindowDpiScale() +{ + ImGuiContext& g = *GImGui; + return g.CurrentDpiScale; +} + +ImGuiViewport* ImGui::GetWindowViewport() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport); + return g.CurrentViewport; +} + +ImFont* ImGui::GetFont() +{ + return GImGui->Font; +} + +ImFontBaked* ImGui::GetFontBaked() +{ + return GImGui->FontBaked; +} + +// Get current font size (= height in pixels) of current font, with global scale factors applied. +// - Use style.FontSizeBase to get value before global scale factors. +// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors) +float ImGui::GetFontSize() +{ + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->DrawListSharedData.TexUvWhitePixel; +} + +// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +void ImGui::SetWindowFontScale(float scale) +{ + IM_ASSERT(scale > 0.0f); + ImGuiWindow* window = GetCurrentWindow(); + window->FontWindowScale = scale; + UpdateCurrentFontSize(0.0f); +} +#endif + +void ImGui::PushFocusScope(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiFocusScopeData data; + data.ID = id; + data.WindowID = g.CurrentWindow->ID; + g.FocusScopeStack.push_back(data); + g.CurrentFocusScopeId = id; +} + +void ImGui::PopFocusScope() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR_RET(g.FocusScopeStack.Size > g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack, "Calling PopFocusScope() too many times!"); + g.FocusScopeStack.pop_back(); + g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0; +} + +void ImGui::SetNavFocusScope(ImGuiID focus_scope_id) +{ + ImGuiContext& g = *GImGui; + g.NavFocusScopeId = focus_scope_id; + g.NavFocusRoute.resize(0); // Invalidate + if (focus_scope_id == 0) + return; + IM_ASSERT(g.NavWindow != NULL); + + // Store current path (in reverse order) + if (focus_scope_id == g.CurrentFocusScopeId) + { + // Top of focus stack contains local focus scopes inside current window + for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--) + g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]); + } + else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId) + g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID }); + else + return; + + // Then follow on manually set ParentWindowForFocusRoute field (#6798) + for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute) + g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID }); + IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3 +} + +// Focus = move navigation cursor, set scrolling, set focus window. +void ImGui::FocusItem() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name); + if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this? + { + IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n"); + return; + } + + ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect; + ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY; + SetNavWindow(window); + NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags); + NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal); +} + +void ImGui::ActivateItemByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.NavNextActivateId = id; + g.NavNextActivateFlags = ImGuiActivateFlags_None; +} + +// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system! +// But ActivateItem() should function without altering scroll/focus? +void ImGui::SetKeyboardFocusHere(int offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(offset >= -1); // -1 is allowed but not below + IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name); + + // It makes sense in the vast majority of cases to never interrupt a drag and drop. + // When we refactor this function into ActivateItem() we may want to make this an option. + // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but + // is also automatically dropped in the event g.ActiveId is stolen. + if (g.DragDropActive || g.MovingWindow != NULL) + { + IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n"); + return; + } + + SetNavWindow(window); + + ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible; + ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY; + NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. + if (offset == -1) + { + NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal); + } + else + { + g.NavTabbingDir = 1; + g.NavTabbingCounter = offset + 1; + } +} + +void ImGui::SetItemDefaultFocus() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!window->Appearing) + return; + if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent) + return; + + g.NavInitRequest = false; + NavApplyItemToResult(&g.NavInitResult); + NavUpdateAnyRequestFlag(); + + // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll) + if (!window->ClipRect.Contains(g.LastItemData.Rect)) + ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None); +} + +void ImGui::SetStateStorage(ImGuiStorage* tree) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage* ImGui::GetStateStorage() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->DC.StateStorage; +} + +bool ImGui::IsRectVisible(const ImVec2& size) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); +} + +bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); +} + +//----------------------------------------------------------------------------- +// [SECTION] FONTS, TEXTURES +//----------------------------------------------------------------------------- +// Most of the relevant font logic is in imgui_draw.cpp. +// Those are high-level support functions. +//----------------------------------------------------------------------------- +// - UpdateTexturesNewFrame() [Internal] +// - UpdateTexturesEndFrame() [Internal] +// - UpdateFontsNewFrame() [Internal] +// - UpdateFontsEndFrame() [Internal] +// - GetDefaultFont() [Internal] +// - RegisterUserTexture() [Internal] +// - UnregisterUserTexture() [Internal] +// - RegisterFontAtlas() [Internal] +// - UnregisterFontAtlas() [Internal] +// - SetCurrentFont() [Internal] +// - UpdateCurrentFontSize() [Internal] +// - SetFontRasterizerDensity() [Internal] +// - PushFont() +// - PopFont() +//----------------------------------------------------------------------------- + +static void ImGui::UpdateTexturesNewFrame() +{ + // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count. + ImGuiContext& g = *GImGui; + const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + for (ImFontAtlas* atlas : g.FontAtlases) + { + if (atlas->OwnerContext == &g) + { + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures); + } + else + { + // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it. + // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context. + // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that. + // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures. + IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1); + IM_ASSERT(atlas->RendererHasTextures == has_textures); + } + } +} + +// Build a single texture list +static void ImGui::UpdateTexturesEndFrame() +{ + ImGuiContext& g = *GImGui; + g.PlatformIO.Textures.resize(0); + for (ImFontAtlas* atlas : g.FontAtlases) + for (ImTextureData* tex : atlas->TexList) + { + // We provide this information so backends can decide whether to destroy textures. + // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. + tex->RefCount = (unsigned short)atlas->RefCount; + g.PlatformIO.Textures.push_back(tex); + } + for (ImTextureData* tex : g.UserTextures) + g.PlatformIO.Textures.push_back(tex); +} + +void ImGui::UpdateFontsNewFrame() +{ + ImGuiContext& g = *GImGui; + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = true; + + if (g.Style._NextFrameFontSizeBase != 0.0f) + { + g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase; + g.Style._NextFrameFontSizeBase = 0.0f; + } + + // Apply default font size the first time + ImFont* font = ImGui::GetDefaultFont(); + if (g.Style.FontSizeBase <= 0.0f) + g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE_BASE); + + // Set initial font + g.Font = font; + g.FontSizeBase = g.Style.FontSizeBase; + g.FontSize = 0.0f; + ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize + SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale + g.FontStack.push_back(font_stack_data); + IM_ASSERT(g.Font->IsLoaded()); +} + +void ImGui::UpdateFontsEndFrame() +{ + PopFont(); +} + +ImFont* ImGui::GetDefaultFont() +{ + ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; + if (atlas->Builder == NULL || atlas->Fonts.Size == 0) + ImFontAtlasBuildMain(atlas); + return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0]; +} + +// EXPERIMENTAL: DO NOT USE YET. +void ImGui::RegisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + tex->RefCount++; + g.UserTextures.push_back(tex); +} + +void ImGui::UnregisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(tex->RefCount > 0); + tex->RefCount--; + g.UserTextures.find_erase(tex); +} + +void ImGui::RegisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + if (g.FontAtlases.Size == 0) + IM_ASSERT(atlas == g.IO.Fonts); + atlas->RefCount++; + g.FontAtlases.push_back(atlas); + ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData); + for (ImTextureData* tex : atlas->TexList) + tex->RefCount = (unsigned short)atlas->RefCount; +} + +void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(atlas->RefCount > 0); + ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); + g.FontAtlases.find_erase(atlas); + atlas->RefCount--; + for (ImTextureData* tex : atlas->TexList) + tex->RefCount = (unsigned short)atlas->RefCount; +} + +// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList. +// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls. +// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... +// - Some code paths never really fully worked with multiple atlas textures. +// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture() +// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem +// because we have a concrete need and a test bed for multiple atlas textures. +// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? +void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling) +{ + ImGuiContext& g = *GImGui; + g.Font = font; + g.FontSizeBase = font_size_before_scaling; + UpdateCurrentFontSize(font_size_after_scaling); + + if (font != NULL) + { + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + IM_ASSERT(font->Scale > 0.0f); +#endif + ImFontAtlas* atlas = font->OwnerAtlas; + g.DrawListSharedData.FontAtlas = atlas; + g.DrawListSharedData.Font = font; + ImFontAtlasUpdateDrawListsSharedData(atlas); + if (g.CurrentWindow != NULL) + g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef); + } +} + +void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + g.Style.FontSizeBase = g.FontSizeBase; + + // Early out to avoid hidden window keeping bakes referenced and out of GC reach. + // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. + // FIXME: perhaps g.FontSize should be updated? + if (window != NULL && window->SkipItems) + { + ImGuiTable* table = g.CurrentTable; + if (table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false)) // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data. + return; + } + + // Restoring is pretty much only used by PopFont() + float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; + if (final_size == 0.0f) + { + final_size = g.FontSizeBase; + + // Global scale factors + final_size *= g.Style.FontScaleMain; // Main global scale factor + final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled). + + // Window scale (mostly obsolete now) + if (window != NULL) + final_size *= window->FontWindowScale; + + // Legacy scale factors +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead! + if (g.Font != NULL) + final_size *= g.Font->Scale; // Was never really useful. +#endif + } + + // Round font size + // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. + // - We may support it better later and remove this rounding. + final_size = GetRoundedFontSize(final_size); + final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX); + if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) + g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; + g.FontSize = final_size; + g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; + g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; + g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontBakedScale; +} + +// Exposed in case user may want to override setting density. +// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it. +void ImGui::SetFontRasterizerDensity(float rasterizer_density) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures); + if (g.FontRasterizerDensity == rasterizer_density) + return; + g.FontRasterizerDensity = rasterizer_density; + UpdateCurrentFontSize(0.0f); +} + +// If you want to scale an existing font size! Read comments in imgui.h! +void ImGui::PushFont(ImFont* font, float font_size_base) +{ + ImGuiContext& g = *GImGui; + if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) + font = g.Font; + IM_ASSERT(font != NULL); + IM_ASSERT(font_size_base >= 0.0f); + + g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); + if (font_size_base == 0.0f) + font_size_base = g.FontSizeBase; // Keep current font size + SetCurrentFont(font, font_size_base, 0.0f); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR_RET(g.FontStack.Size > 0, "Calling PopFont() too many times!"); + ImFontStackData* font_stack_data = &g.FontStack.back(); + SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling); + g.FontStack.pop_back(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ID STACK +//----------------------------------------------------------------------------- + +// This is one of the very rare legacy case where we use ImGuiWindow methods, +// it should ideally be flattened at some point but it's been used a lots by widgets. +IM_MSVC_RUNTIME_CHECKS_OFF +ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *Ctx; + if (g.DebugHookIdInfoId == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); +#endif + return id; +} + +ImGuiID ImGuiWindow::GetID(const void* ptr) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *Ctx; + if (g.DebugHookIdInfoId == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL); +#endif + return id; +} + +ImGuiID ImGuiWindow::GetID(int n) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashData(&n, sizeof(n), seed); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *Ctx; + if (g.DebugHookIdInfoId == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL); +#endif + return id; +} + +// This is only used in rare/specific situations to manufacture an ID out of nowhere. +// FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those? +ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs) +{ + ImGuiID seed = IDStack.back(); + ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs); + ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed); + return id; +} + +// " +ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) +{ + ImGuiID seed = IDStack.back(); + ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs); + ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed); + return id; +} + +void ImGui::PushID(const char* str_id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + window->IDStack.push_back(id); +} + +void ImGui::PushID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id_begin, str_id_end); + window->IDStack.push_back(id); +} + +void ImGui::PushID(const void* ptr_id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(ptr_id); + window->IDStack.push_back(id); +} + +void ImGui::PushID(int int_id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(int_id); + window->IDStack.push_back(id); +} + +// Push a given id value ignoring the ID stack as a seed. +void ImGui::PushOverrideID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.DebugHookIdInfoId == id) + DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL); +#endif + window->IDStack.push_back(id); +} + +// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. +// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) +ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) +{ + ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *GImGui; + if (g.DebugHookIdInfoId == id) + DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); +#endif + return id; +} + +ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed) +{ + ImGuiID id = ImHashData(&n, sizeof(n), seed); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *GImGui; + if (g.DebugHookIdInfoId == id) + DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL); +#endif + return id; +} + +void ImGui::PopID() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + IM_ASSERT_USER_ERROR_RET(window->IDStack.Size > 1, "Calling PopID() too many times!"); + window->IDStack.pop_back(); +} + +ImGuiID ImGui::GetID(const char* str_id) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(str_id_begin, str_id_end); +} + +ImGuiID ImGui::GetID(const void* ptr_id) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(ptr_id); +} + +ImGuiID ImGui::GetID(int int_id) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(int_id); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] INPUTS +//----------------------------------------------------------------------------- +// - GetModForLRModKey() [Internal] +// - FixupKeyChord() [Internal] +// - GetKeyData() [Internal] +// - GetKeyIndex() [Internal] +// - GetKeyName() +// - GetKeyChordName() [Internal] +// - CalcTypematicRepeatAmount() [Internal] +// - GetTypematicRepeatRate() [Internal] +// - GetKeyPressedAmount() [Internal] +// - GetKeyMagnitude2d() [Internal] +//----------------------------------------------------------------------------- +// - UpdateKeyRoutingTable() [Internal] +// - GetRoutingIdFromOwnerId() [Internal] +// - GetShortcutRoutingData() [Internal] +// - CalcRoutingScore() [Internal] +// - SetShortcutRouting() [Internal] +// - TestShortcutRouting() [Internal] +//----------------------------------------------------------------------------- +// - IsKeyDown() +// - IsKeyPressed() +// - IsKeyReleased() +//----------------------------------------------------------------------------- +// - IsMouseDown() +// - IsMouseClicked() +// - IsMouseReleased() +// - IsMouseDoubleClicked() +// - GetMouseClickedCount() +// - IsMouseHoveringRect() [Internal] +// - IsMouseDragPastThreshold() [Internal] +// - IsMouseDragging() +// - GetMousePos() +// - SetMousePos() [Internal] +// - GetMousePosOnOpeningCurrentPopup() +// - IsMousePosValid() +// - IsAnyMouseDown() +// - GetMouseDragDelta() +// - ResetMouseDragDelta() +// - GetMouseCursor() +// - SetMouseCursor() +//----------------------------------------------------------------------------- +// - UpdateAliasKey() +// - GetMergedModsFromKeys() +// - UpdateKeyboardInputs() +// - UpdateMouseInputs() +//----------------------------------------------------------------------------- +// - LockWheelingWindow [Internal] +// - FindBestWheelingWindow [Internal] +// - UpdateMouseWheel() [Internal] +//----------------------------------------------------------------------------- +// - SetNextFrameWantCaptureKeyboard() +// - SetNextFrameWantCaptureMouse() +//----------------------------------------------------------------------------- +// - GetInputSourceName() [Internal] +// - DebugPrintInputEvent() [Internal] +// - UpdateInputEvents() [Internal] +//----------------------------------------------------------------------------- +// - GetKeyOwner() [Internal] +// - TestKeyOwner() [Internal] +// - SetKeyOwner() [Internal] +// - SetItemKeyOwner() [Internal] +// - Shortcut() [Internal] +//----------------------------------------------------------------------------- + +static ImGuiKeyChord GetModForLRModKey(ImGuiKey key) +{ + if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl) + return ImGuiMod_Ctrl; + if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift) + return ImGuiMod_Shift; + if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt) + return ImGuiMod_Alt; + if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper) + return ImGuiMod_Super; + return ImGuiMod_None; +} + +ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord) +{ + // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified. + ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (IsLRModKey(key)) + key_chord |= GetModForLRModKey(key); + return key_chord; +} + +ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key) +{ + ImGuiContext& g = *ctx; + + // Special storage location for mods + if (key & ImGuiMod_Mask_) + key = ConvertSingleModFlagToKey(key); + + IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code."); + return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN]; +} + +// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. +static const char* const GKeyNames[] = +{ + "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", + "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape", + "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", + "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", + "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", + "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket", + "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen", + "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", + "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply", + "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", + "AppBack", "AppForward", "Oem102", + "GamepadStart", "GamepadBack", + "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown", + "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown", + "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3", + "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown", + "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown", + "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY", + "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names. +}; +IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_COUNTOF(GKeyNames)); + +const char* ImGui::GetKeyName(ImGuiKey key) +{ + if (key == ImGuiKey_None) + return "None"; + IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code."); + if (key & ImGuiMod_Mask_) + key = ConvertSingleModFlagToKey(key); + if (!IsNamedKey(key)) + return "Unknown"; + + return GKeyNames[key - ImGuiKey_NamedKey_BEGIN]; +} + +// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super. +// Lifetime of return value: valid until next call to same function. +const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord) +{ + ImGuiContext& g = *GImGui; + + const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (IsLRModKey(key)) + key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift" + ImFormatString(g.TempKeychordName, IM_COUNTOF(g.TempKeychordName), "%s%s%s%s%s", + (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "", + (key_chord & ImGuiMod_Shift) ? "Shift+" : "", + (key_chord & ImGuiMod_Alt) ? "Alt+" : "", + (key_chord & ImGuiMod_Super) ? "Super+" : "", + (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : ""); + size_t len; + if (key == ImGuiKey_None && key_chord != 0) + if ((len = ImStrlen(g.TempKeychordName)) != 0) // Remove trailing '+' + g.TempKeychordName[len - 1] = 0; + return g.TempKeychordName; +} + +// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) +// t1 = current time (e.g.: g.Time) +// An event is triggered at: +// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N +int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate) +{ + if (t1 == 0.0f) + return 1; + if (t0 >= t1) + return 0; + if (repeat_rate <= 0.0f) + return t0 < repeat_delay && t1 >= repeat_delay; + const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate); + const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate); + const int count = count_t1 - count_t0; + return count; +} + +void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate) +{ + ImGuiContext& g = *GImGui; + switch (flags & ImGuiInputFlags_RepeatRateMask_) + { + case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return; + case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return; + case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return; + } +} + +// Return value representing the number of presses in the last time period, for the given repeat rate +// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate) +int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate) +{ + ImGuiContext& g = *GImGui; + const ImGuiKeyData* key_data = GetKeyData(key); + if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) + return 0; + const float t = key_data->DownDuration; + return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate); +} + +// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values). +ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down) +{ + return ImVec2( + GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue, + GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue); +} + +// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data. +// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D +// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6 +// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation. +static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt) +{ + ImGuiContext& g = *GImGui; + rt->EntriesNext.resize(0); + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) + { + const int new_routing_start_idx = rt->EntriesNext.Size; + ImGuiKeyRoutingData* routing_entry; + for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex) + { + routing_entry = &rt->Entries[old_routing_idx]; + routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore; + routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry + routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner; + routing_entry->RoutingNextScore = 0; + if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner) + continue; + rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer + + // Apply routing to owner if there's no owner already (RoutingCurr == None at this point) + // This is the result of previous frame's SetShortcutRouting() call. + if (routing_entry->Mods == g.IO.KeyMods) + { + ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); + if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner) + { + owner_data->OwnerCurr = routing_entry->RoutingCurr; + //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr); + } + } + } + + // Rewrite linked-list + rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1); + for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++) + rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1); + } + rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes +} + +// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope(). +static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId; +} + +ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord) +{ + // Majority of shortcuts will be Key + any number of Mods + // We accept _Single_ mod with ImGuiKey_None. + // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal + // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal + // - Shortcut(ImGuiMod_Ctrl); // Legal + // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal + ImGuiContext& g = *GImGui; + ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable; + ImGuiKeyRoutingData* routing_data; + ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_); + if (key == ImGuiKey_None) + key = ConvertSingleModFlagToKey(mods); + IM_ASSERT(IsNamedKey(key)); + + // Get (in the majority of case, the linked list will have one element so this should be 2 reads. + // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame). + for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex) + { + routing_data = &rt->Entries[idx]; + if (routing_data->Mods == mods) + return routing_data; + } + + // Add to linked-list + ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size; + rt->Entries.push_back(ImGuiKeyRoutingData()); + routing_data = &rt->Entries[routing_data_idx]; + routing_data->Mods = (ImU16)mods; + routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list + rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx; + return routing_data; +} + +// Current score encoding +// - 0: Never route +// - 1: ImGuiInputFlags_RouteGlobal (lower priority) +// - 100..199: ImGuiInputFlags_RouteFocused (if window in focus-stack) +// 200: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused +// 300: ImGuiInputFlags_RouteActive or ImGuiInputFlags_RouteFocused (if item active) +// 400: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive +// - 500..599: ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteOverActive (if window in focus-stack) (higher priority) +// 'flags' should include an explicit routing policy +static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags) +{ + ImGuiContext& g = *GImGui; + if (flags & ImGuiInputFlags_RouteFocused) + { + // ActiveID gets high priority + // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it) + if (owner_id != 0 && g.ActiveId == owner_id) + return 300; + + // Score based on distance to focused window (lower is better) + // Assuming both windows are submitting a routing request, + // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match) + // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best) + // Assuming only WindowA is submitting a routing request, + // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. + // This essentially follow the window->ParentWindowForFocusRoute chain. + if (focus_scope_id == 0) + return 0; + for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++) + if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id) + { + if (flags & ImGuiInputFlags_RouteOverActive) // && g.ActiveId != 0 && g.ActiveId != owner_id) + return 599 - index_in_focus_path; + else + return 199 - index_in_focus_path; + } + return 0; + } + else if (flags & ImGuiInputFlags_RouteActive) + { + if (owner_id != 0 && g.ActiveId == owner_id) + return 300; + return 0; + } + else if (flags & ImGuiInputFlags_RouteGlobal) + { + if (flags & ImGuiInputFlags_RouteOverActive) + return 400; + if (owner_id != 0 && g.ActiveId == owner_id) + return 300; + if (flags & ImGuiInputFlags_RouteOverFocused) + return 200; + return 1; + } + IM_ASSERT(0); + return 0; +} + +// - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active +// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be. +// - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey_G also emitting a G character. +static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord) +{ + // Mimic 'ignore_char_inputs' logic in InputText() + ImGuiContext& g = *GImGui; + + // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out. + ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_); + const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl)); + if (ignore_char_inputs) + return false; + + // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered. + ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (key == ImGuiKey_None) + return false; + return g.KeysMayBeCharInput.TestBit(key); +} + +// Request a desired route for an input chord (key + mods). +// Return true if the route is available this frame. +// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state. +// (Conceptually this does a "Submit for next frame" + "Test for current frame". +// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.) +bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0) + flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut() + else + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used + IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner); + if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteUnlessBgFocused)) + IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal); + if (flags & ImGuiInputFlags_RouteOverActive) + IM_ASSERT(flags & (ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteFocused)); + + // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified. + key_chord = FixupKeyChord(key_chord); + + // [DEBUG] Debug break requested by user + if (g.DebugBreakInShortcutRouting == key_chord) + IM_DEBUG_BREAK(); + + if (flags & ImGuiInputFlags_RouteUnlessBgFocused) + if (g.NavWindow == NULL) + return false; + + // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this? + if (flags & ImGuiInputFlags_RouteAlways) + { + IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id); + return true; + } + + // Specific culling when there's an active item. + if (g.ActiveId != 0 && g.ActiveId != owner_id) + { + if (flags & ImGuiInputFlags_RouteActive) + return false; + + // Cull shortcuts with no modifiers when it could generate a character. + // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active. + // but Shortcut(Ctrl+G) should generally trigger when InputText() is active. + // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active. + // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined) + if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord)) + { + IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id); + return false; + } + + // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId + if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys) + { + ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (key == ImGuiKey_None) + key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_)); + if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END) + return false; + } + } + + // Where do we evaluate route for? + ImGuiID focus_scope_id = g.CurrentFocusScopeId; + if (flags & ImGuiInputFlags_RouteFromRootWindow) + focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin() + + const int score = CalcRoutingScore(focus_scope_id, owner_id, flags); + IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score); + if (score == 0) + return false; + + // Submit routing for NEXT frame (assuming score is sufficient) + // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >). + ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); + //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore); + if (score > routing_data->RoutingNextScore) + { + routing_data->RoutingNext = owner_id; + routing_data->RoutingNextScore = (ImU16)score; + } + + // Return routing state for CURRENT frame + if (routing_data->RoutingCurr == owner_id) + IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n"); + return routing_data->RoutingCurr == owner_id; +} + +// Currently unused by core (but used by tests) +// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading. +bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id) +{ + const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id); + key_chord = FixupKeyChord(key_chord); + ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry. + return routing_data->RoutingCurr == routing_id; +} + +// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes. +// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87) +bool ImGui::IsKeyDown(ImGuiKey key) +{ + return IsKeyDown(key, ImGuiKeyOwner_Any); +} + +bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id) +{ + const ImGuiKeyData* key_data = GetKeyData(key); + if (!key_data->Down) + return false; + if (!TestKeyOwner(key, owner_id)) + return false; + return true; +} + +bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat) +{ + return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any); +} + +// Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat. +bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id) +{ + const ImGuiKeyData* key_data = GetKeyData(key); + if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) + return false; + const float t = key_data->DownDuration; + if (t < 0.0f) + return false; + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function! + if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat + flags |= ImGuiInputFlags_Repeat; + + bool pressed = (t == 0.0f); + if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0) + { + float repeat_delay, repeat_rate; + GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate); + pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0; + if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_)) + { + // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value. + // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code. + ImGuiContext& g = *GImGui; + double key_pressed_time = g.Time - t + 0.00001f; + if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time)) + pressed = false; + if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time)) + pressed = false; + if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time)) + pressed = false; + } + } + if (!pressed) + return false; + if (!TestKeyOwner(key, owner_id)) + return false; + return true; +} + +bool ImGui::IsKeyReleased(ImGuiKey key) +{ + return IsKeyReleased(key, ImGuiKeyOwner_Any); +} + +bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id) +{ + const ImGuiKeyData* key_data = GetKeyData(key); + if (key_data->DownDurationPrev < 0.0f || key_data->Down) + return false; + if (!TestKeyOwner(key, owner_id)) + return false; + return true; +} + +bool ImGui::IsMouseDown(ImGuiMouseButton button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array. +} + +bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array. +} + +bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat) +{ + return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any); +} + +bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) + return false; + const float t = g.IO.MouseDownDuration[button]; + if (t < 0.0f) + return false; + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here. + + const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0; + const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0); + if (!pressed) + return false; + + if (!TestKeyOwner(MouseButtonToKey(button), owner_id)) + return false; + + return true; +} + +bool ImGui::IsMouseReleased(ImGuiMouseButton button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any) +} + +bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) +} + +// Use if you absolutely need to distinguish single-click from double-click by introducing a delay. +// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test. +// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename. +bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]); + return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay); +} + +bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); +} + +bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id); +} + +int ImGui::GetMouseClickedCount(ImGuiMouseButton button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + return g.IO.MouseClickedCount[button]; +} + +// Test if mouse cursor is hovering given rectangle +// NB- Rectangle is clipped by our current clip setting +// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) +{ + ImGuiContext& g = *GImGui; + + // Clip + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.ClipWith(g.CurrentWindow->ClipRect); + + // Hit testing, expanded for touch input + if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding)) + return false; + if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped)) + return false; + return true; +} + +// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. +// [Internal] This doesn't test if the button is pressed +bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; +} + +bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + return IsMouseDragPastThreshold(button, lock_threshold); +} + +ImVec2 ImGui::GetMousePos() +{ + ImGuiContext& g = *GImGui; + return g.IO.MousePos; +} + +// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well. +// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend. +void ImGui::TeleportMousePos(const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + g.IO.MousePos = g.IO.MousePosPrev = pos; + g.IO.MouseDelta = ImVec2(0.0f, 0.0f); + g.IO.WantSetMousePos = true; + //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y); +} + +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.BeginPopupStack.Size > 0) + return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; + return g.IO.MousePos; +} + +// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. +bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) +{ + // The assert is only to silence a false-positive in XCode Static Analysis. + // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions). + IM_ASSERT(GImGui != NULL); + const float MOUSE_INVALID = -256000.0f; + ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos; + return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; +} + +// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. +bool ImGui::IsAnyMouseDown() +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < IM_COUNTOF(g.IO.MouseDown); n++) + if (g.IO.MouseDown[n]) + return true; + return false; +} + +// Return the delta from the initial clicking position while the mouse button is clicked or was just released. +// This is locked and return 0.0f until the mouse moves past a distance threshold at least once. +// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. +ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) + if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) + if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button])) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; + return ImVec2(0.0f, 0.0f); +} + +void ImGui::ResetMouseDragDelta(ImGuiMouseButton button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + +// Get desired mouse cursor shape. +// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(), +// updated during the frame, and locked in EndFrame()/Render(). +// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you +ImGuiMouseCursor ImGui::GetMouseCursor() +{ + ImGuiContext& g = *GImGui; + return g.MouseCursor; +} + +// We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value. +// Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may +// handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call. +void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) +{ + ImGuiContext& g = *GImGui; + g.MouseCursor = cursor_type; +} + +static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value) +{ + IM_ASSERT(ImGui::IsAliasKey(key)); + ImGuiKeyData* key_data = ImGui::GetKeyData(key); + key_data->Down = v; + key_data->AnalogValue = analog_value; +} + +// [Internal] Do not use directly +static ImGuiKeyChord GetMergedModsFromKeys() +{ + ImGuiKeyChord mods = 0; + if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; } + if (ImGui::IsKeyDown(ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; } + if (ImGui::IsKeyDown(ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; } + if (ImGui::IsKeyDown(ImGuiMod_Super)) { mods |= ImGuiMod_Super; } + return mods; +} + +static void ImGui::UpdateKeyboardInputs() +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + io.ClearInputKeys(); + + // Update aliases + for (int n = 0; n < ImGuiMouseButton_COUNT; n++) + UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f); + UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH); + UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel); + + // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values. + // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array. + // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array. + // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing. + const ImGuiKeyChord prev_key_mods = io.KeyMods; + io.KeyMods = GetMergedModsFromKeys(); + io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0; + io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0; + io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0; + io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0; + if (prev_key_mods != io.KeyMods) + g.LastKeyModsChangeTime = g.Time; + if (prev_key_mods != io.KeyMods && prev_key_mods == 0) + g.LastKeyModsChangeFromNoneTime = g.Time; + + // Clear gamepad data if disabled + if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0) + for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++) + { + io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false; + io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f; + } + + // Update keys + for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++) + { + ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN]; + key_data->DownDurationPrev = key_data->DownDuration; + key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f; + if (key_data->DownDuration == 0.0f) + { + if (IsKeyboardKey((ImGuiKey)key)) + g.LastKeyboardKeyPressTime = g.Time; + else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper) + g.LastKeyboardKeyPressTime = g.Time; + } + } + + // Update keys/input owner (named keys only): one entry per key + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) + { + ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN]; + ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN]; + owner_data->OwnerCurr = owner_data->OwnerNext; + if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp. + owner_data->OwnerNext = ImGuiKeyOwner_NoOwner; + owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore + } + + // Update key routing (for e.g. shortcuts) + UpdateKeyRoutingTable(&g.KeysRoutingTable); +} + +static void ImGui::UpdateMouseInputs() +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + // Mouse Wheel swapping flag + // As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead + // - We avoid doing it on OSX as it the OS input layer handles this already. + // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature. + // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source. + io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors; + + // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) + if (IsMousePosValid(&io.MousePos)) + io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos); + + // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta + if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev)) + io.MouseDelta = io.MousePos - io.MousePosPrev; + else + io.MouseDelta = ImVec2(0.0f, 0.0f); + + // Update stationary timer. + // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates. + const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework. + const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold); + g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f; + //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer); + + // If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true. + if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f) + g.NavHighlightItemUnderNav = false; + + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) + { + io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f; + io.MouseClickedCount[i] = 0; // Will be filled below + io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f; + if (io.MouseReleased[i]) + io.MouseReleasedTime[i] = g.Time; + io.MouseDownDurationPrev[i] = io.MouseDownDuration[i]; + io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f; + if (io.MouseClicked[i]) + { + bool is_repeated_click = false; + if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime) + { + ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist) + is_repeated_click = true; + } + if (is_repeated_click) + io.MouseClickedLastCount[i]++; + else + io.MouseClickedLastCount[i] = 1; + io.MouseClickedTime[i] = g.Time; + io.MouseClickedPos[i] = io.MousePos; + io.MouseClickedCount[i] = io.MouseClickedLastCount[i]; + io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); + io.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (io.MouseDown[i]) + { + // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold + ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); + io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); + io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); + } + + // We provide io.MouseDoubleClicked[] as a legacy service + io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2); + + // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation + if (io.MouseClicked[i]) + g.NavHighlightItemUnderNav = false; + } +} + +static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount) +{ + ImGuiContext& g = *GImGui; + if (window) + g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER); + else + g.WheelingWindowReleaseTimer = 0.0f; + if (g.WheelingWindow == window) + return; + IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL"); + g.WheelingWindow = window; + g.WheelingWindowRefMousePos = g.IO.MousePos; + if (window == NULL) + { + g.WheelingWindowStartFrame = -1; + g.WheelingAxisAvg = ImVec2(0.0f, 0.0f); + } +} + +static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel) +{ + // For each axis, find window in the hierarchy that may want to use scrolling + ImGuiContext& g = *GImGui; + ImGuiWindow* windows[2] = { NULL, NULL }; + for (int axis = 0; axis < 2; axis++) + if (wheel[axis] != 0.0f) + for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow) + { + // Bubble up into parent window if: + // - a child window doesn't allow any scrolling. + // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag. + //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP) + const bool has_scrolling = (window->ScrollMax[axis] != 0.0f); + const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs); + //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]); + if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits) + break; // select this window + } + if (windows[0] == NULL && windows[1] == NULL) + return NULL; + + // If there's only one window or only one axis then there's no ambiguity + if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL) + return windows[1] ? windows[1] : windows[0]; + + // If candidate are different windows we need to decide which one to prioritize + // - First frame: only find a winner if one axis is zero. + // - Subsequent frames: only find a winner when one is more than the other. + if (g.WheelingWindowStartFrame == -1) + g.WheelingWindowStartFrame = g.FrameCount; + if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y)) + { + g.WheelingWindowWheelRemainder = wheel; + return NULL; + } + return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1]; +} + +// Called by NewFrame() +void ImGui::UpdateMouseWheel() +{ + // Reset the locked window if we move the mouse or after the timer elapses. + // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795) + ImGuiContext& g = *GImGui; + if (g.WheelingWindow != NULL) + { + g.WheelingWindowReleaseTimer -= g.IO.DeltaTime; + if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold) + g.WheelingWindowReleaseTimer = 0.0f; + if (g.WheelingWindowReleaseTimer <= 0.0f) + LockWheelingWindow(NULL, 0.0f); + } + + ImVec2 wheel; + wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f; + wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f; + + //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y); + ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow; + if (!mouse_window || mouse_window->Collapsed) + return; + + // Zoom / Scale window + // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. + if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) + { + LockWheelingWindow(mouse_window, wheel.y); + ImGuiWindow* window = mouse_window; + const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + const float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + if (window == window->RootWindow) + { + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + SetWindowPos(window, window->Pos + offset, 0); + window->Size = ImTrunc(window->Size * scale); // FIXME: Legacy-ish code, call SetWindowSize()? + window->SizeFull = ImTrunc(window->SizeFull * scale); + MarkIniSettingsDirty(window); + } + return; + } + if (g.IO.KeyCtrl) + return; + + // Mouse wheel scrolling + // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs() + if (g.IO.MouseWheelRequestAxisSwap) + wheel = ImVec2(wheel.y, 0.0f); + + // Maintain a rough average of moving magnitude on both axes + // FIXME: should by based on wall clock time rather than frame-counter + g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30); + g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30); + + // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now. + wheel += g.WheelingWindowWheelRemainder; + g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f); + if (wheel.x == 0.0f && wheel.y == 0.0f) + return; + + // Mouse wheel scrolling: find target and apply + // - don't renew lock if axis doesn't apply on the window. + // - select a main axis when both axes are being moved. + if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel))) + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) + { + bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f }; + if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y]) + do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false; + if (do_scroll[ImGuiAxis_X]) + { + LockWheelingWindow(window, wheel.x); + float max_step = window->InnerRect.GetWidth() * 0.67f; + float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step)); + SetScrollX(window, window->Scroll.x - wheel.x * scroll_step); + g.WheelingWindowScrolledFrame = g.FrameCount; + } + if (do_scroll[ImGuiAxis_Y]) + { + LockWheelingWindow(window, wheel.y); + float max_step = window->InnerRect.GetHeight() * 0.67f; + float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step)); + SetScrollY(window, window->Scroll.y - wheel.y * scroll_step); + g.WheelingWindowScrolledFrame = g.FrameCount; + } + } +} + +void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard) +{ + ImGuiContext& g = *GImGui; + g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0; +} + +void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse) +{ + ImGuiContext& g = *GImGui; + g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0; +} + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +static const char* GetInputSourceName(ImGuiInputSource source) +{ + const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" }; + IM_ASSERT(IM_COUNTOF(input_source_names) == ImGuiInputSource_COUNT); + if (source < 0 || source >= ImGuiInputSource_COUNT) + return "Unknown"; + return input_source_names[source]; +} +static const char* GetMouseSourceName(ImGuiMouseSource source) +{ + const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" }; + IM_ASSERT(IM_COUNTOF(mouse_source_names) == ImGuiMouseSource_COUNT); + if (source < 0 || source >= ImGuiMouseSource_COUNT) + return "Unknown"; + return mouse_source_names[source]; +} +static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e) +{ + ImGuiContext& g = *GImGui; + char buf[5]; + if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; } + if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; } + if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; } + if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; } + if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; } + if (e->Type == ImGuiInputEventType_Text) { ImTextCharToUtf8(buf, e->Text.Char); IMGUI_DEBUG_LOG_IO("[io] %s: Text: '%s' (U+%08X)\n", prefix, buf, e->Text.Char); return; } + if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; } +} +#endif + +// Process input queue +// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'. +// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost) +// - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87) +void ImGui::UpdateInputEvents(bool trickle_fast_inputs) +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + // Only trickle chars<>key when working with InputText() + // FIXME: InputText() could parse event trail? + // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) + const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1); + + bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false; + int mouse_button_changed = 0x00; + ImBitArray key_changed_mask; + + int event_n = 0; + for (; event_n < g.InputEventsQueue.Size; event_n++) + { + ImGuiInputEvent* e = &g.InputEventsQueue[event_n]; + if (e->Type == ImGuiInputEventType_MousePos) + { + if (g.IO.WantSetMousePos) + continue; + // Trickling Rule: Stop processing queued events if we already handled a mouse button change + ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY); + if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted)) + break; + io.MousePos = event_pos; + io.MouseSource = e->MousePos.MouseSource; + mouse_moved = true; + } + else if (e->Type == ImGuiInputEventType_MouseButton) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the same button + const ImGuiMouseButton button = e->MouseButton.Button; + IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT); + if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled)) + break; + if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover. + break; + io.MouseDown[button] = e->MouseButton.Down; + io.MouseSource = e->MouseButton.MouseSource; + mouse_button_changed |= (1 << button); + } + else if (e->Type == ImGuiInputEventType_MouseWheel) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the event + if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0)) + break; + io.MouseWheelH += e->MouseWheel.WheelX; + io.MouseWheel += e->MouseWheel.WheelY; + io.MouseSource = e->MouseWheel.MouseSource; + mouse_wheeled = true; + } + else if (e->Type == ImGuiInputEventType_MouseViewport) + { + io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID; + } + else if (e->Type == ImGuiInputEventType_Key) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the same button + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + continue; + ImGuiKey key = e->Key.Key; + IM_ASSERT(key != ImGuiKey_None); + ImGuiKeyData* key_data = GetKeyData(key); + const int key_data_index = (int)(key_data - g.IO.KeysData); + if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0)) + break; + + const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key); + if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input)) + break; + + if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed. + { + key_changed = true; + key_changed_mask.SetBit(key_data_index); + if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) + key_changed_nonchar = true; + } + + key_data->Down = e->Key.Down; + key_data->AnalogValue = e->Key.AnalogValue; + } + else if (e->Type == ImGuiInputEventType_Text) + { + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + continue; + // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with + if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled)) + break; + if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar) + break; + unsigned int c = e->Text.Char; + io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); + if (trickle_interleaved_nonchar_keys_and_text) + text_inputted = true; + } + else if (e->Type == ImGuiInputEventType_Focus) + { + // We intentionally overwrite this and process in NewFrame(), in order to give a chance + // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame. + const bool focus_lost = !e->AppFocused.Focused; + io.AppFocusLost = focus_lost; + } + else + { + IM_ASSERT(0 && "Unknown event!"); + } + } + + // Record trail (for domain-specific applications wanting to access a precise trail) + //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n); + for (int n = 0; n < event_n; n++) + g.InputEventsTrail.push_back(g.InputEventsQueue[n]); + + // [DEBUG] +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO)) + for (int n = 0; n < g.InputEventsQueue.Size; n++) + DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]); +#endif + + // Remaining events will be processed on the next frame + // FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this + // queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772) + if (event_n == g.InputEventsQueue.Size) + g.InputEventsQueue.resize(0); + else + g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n); + + // Clear buttons state when focus is lost + // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle. + // - we clear in EndFrame() and not now in order allow application/user code polling this flag + // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event). + if (g.IO.AppFocusLost) + { + g.IO.ClearInputKeys(); + g.IO.ClearInputMouse(); + } +} + +ImGuiID ImGui::GetKeyOwner(ImGuiKey key) +{ + if (!IsNamedKeyOrMod(key)) + return ImGuiKeyOwner_NoOwner; + + ImGuiContext& g = *GImGui; + ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); + ImGuiID owner_id = owner_data->OwnerCurr; + + if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any) + if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END) + return ImGuiKeyOwner_NoOwner; + + return owner_id; +} + +// TestKeyOwner(..., ID) : (owner == None || owner == ID) +// TestKeyOwner(..., None) : (owner == None) +// TestKeyOwner(..., Any) : no owner test +// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags. +bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id) +{ + if (!IsNamedKeyOrMod(key)) + return true; + + ImGuiContext& g = *GImGui; + if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any) + if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END) + return false; + + ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); + if (owner_id == ImGuiKeyOwner_Any) + return owner_data->LockThisFrame == false; + + // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId + // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things. + // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions. + if (owner_data->OwnerCurr != owner_id) + { + if (owner_data->LockThisFrame) + return false; + if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner) + return false; + } + + return true; +} + +// _LockXXX flags are useful to lock keys away from code which is not input-owner aware. +// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone. +// - SetKeyOwner(..., None) : clears owner +// - SetKeyOwner(..., Any, !Lock) : illegal (assert) +// - SetKeyOwner(..., Any or None, Lock) : set lock +void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it) + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function! + //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags); + + ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); + owner_data->OwnerCurr = owner_data->OwnerNext = owner_id; + + // We cannot lock by default as it would likely break lots of legacy code. + // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test) + owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0; + owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease); +} + +// Rarely used helper +void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags) +{ + if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); } + if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); } + if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); } + if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); } + if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); } +} + +// This is more or less equivalent to: +// if (IsItemHovered() || IsItemActive()) +// SetKeyOwner(key, GetItemID()); +// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times. +// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition. +// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority. +void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = g.LastItemData.ID; + if (id == 0 || (g.HoveredId != id && g.ActiveId != id)) + return; + if ((flags & ImGuiInputFlags_CondMask_) == 0) + flags |= ImGuiInputFlags_CondDefault_; + if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive))) + { + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function! + SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_); + } +} + +void ImGui::SetItemKeyOwner(ImGuiKey key) +{ + SetItemKeyOwner(key, ImGuiInputFlags_None); +} + +// This is the only public API until we expose owner_id versions of the API as replacements. +bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord) +{ + return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any); +} + +// This is equivalent to comparing KeyMods + doing a IsKeyPressed() +bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + key_chord = FixupKeyChord(key_chord); + ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_); + if (g.IO.KeyMods != mods) + return false; + + // Special storage location for mods + ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (key == ImGuiKey_None) + key = ConvertSingleModFlagToKey(mods); + if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id)) + return false; + return true; +} + +void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags) +{ + ImGuiContext& g = *GImGui; + g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut; + g.NextItemData.Shortcut = key_chord; + g.NextItemData.ShortcutFlags = flags; +} + +// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData +void ImGui::ItemHandleShortcut(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiInputFlags flags = g.NextItemData.ShortcutFlags; + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()! + + if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) + return; + if (flags & ImGuiInputFlags_Tooltip) + { + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut; + g.LastItemData.Shortcut = g.NextItemData.Shortcut; + } + if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0) + return; + + // FIXME: Generalize Activation queue? + g.NavActivateId = id; // Will effectively disable clipping. + g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut; + //if (g.ActiveId == 0 || g.ActiveId == id) + g.NavActivateDownId = g.NavActivatePressedId = id; + NavHighlightActivated(id); +} + +bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags) +{ + return Shortcut(key_chord, flags, ImGuiKeyOwner_Any); +} + +bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id) +{ + ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id); + + // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any. + if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0) + flags |= ImGuiInputFlags_RouteFocused; + + // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default) + // Effectively makes Shortcut() always input-owner aware. + if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner) + owner_id = GetRoutingIdFromOwnerId(owner_id); + + if (g.CurrentItemFlags & ImGuiItemFlags_Disabled) + return false; + + // Submit route + if (!SetShortcutRouting(key_chord, flags, owner_id)) + return false; + + // Default repeat behavior for Shortcut() + // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut. + if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0) + flags |= ImGuiInputFlags_RepeatUntilKeyModsChange; + + if (!IsKeyChordPressed(key_chord, flags, owner_id)) + return false; + + // Claim mods during the press + SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id); + + IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function! + return true; +} + +//----------------------------------------------------------------------------- +// [SECTION] ERROR CHECKING, STATE RECOVERY +//----------------------------------------------------------------------------- +// - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros) +// - ErrorCheckUsingSetCursorPosToExtendParentBoundaries() +// - ErrorCheckNewFrameSanityChecks() +// - ErrorCheckEndFrameSanityChecks() +// - ErrorRecoveryStoreState() +// - ErrorRecoveryTryToRecoverState() +// - ErrorRecoveryTryToRecoverWindowState() +// - ErrorLog() +//----------------------------------------------------------------------------- + +// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues. +// Called by IMGUI_CHECKVERSION(). +// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit +// If this triggers you have mismatched headers and compiled code versions. +// - It could be because of a build issue (using new headers with old compiled code) +// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc. +// THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI. +// Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h). +// Otherwise it is possible that different compilation units would see different structure layout. +// If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename. +bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) +{ + bool error = false; + if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); } + if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); } + if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); } + if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } + if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); } + if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); } + if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); } + return !error; +} + +// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos() +// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing +// windows, table column contents size used for auto-resizing columns, group size). +// This was causing issues and ambiguities and we needed to retire that. +// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED. +// +// Previously this would make the window content size ~200x200: +// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE +// Instead, please submit an item: +// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK +// Alternative: +// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK +// +// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item, +// and with a position that would grow the parent contents size. +// +// Advanced: +// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos()) +// had a side-effect on layout! In particular this caused problem to compute group boundaries. +// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the +// group to be taller because auto-sizing generally adds padding on bottom and right side. +// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. +// Using vertical alignment patterns would frequently trigger this sorts of issue. +// - See https://github.com/ocornut/imgui/issues/5548 for more details. +void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window->DC.IsSetPos); + window->DC.IsSetPos = false; + if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y) + return; + if (window->SkipItems) + return; + IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries."); + + // For reference, the old behavior was essentially: + //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +static void ImGui::ErrorCheckNewFrameSanityChecks() +{ + ImGuiContext& g = *GImGui; + + // Check user IM_ASSERT macro + // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined! + // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block. + // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.) + // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong! + // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! + if (true) IM_ASSERT(1); else IM_ASSERT(0); + + // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644) + // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it. +#ifdef __EMSCRIPTEN__ + if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0) + g.IO.DeltaTime = 0.00001f; +#endif + + // Check user data + // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) + IM_ASSERT(g.Initialized); + IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); + IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations + IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders. + IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); + IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right); + IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes); + + // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way. + if (g.IO.ConfigErrorRecovery) + IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.IO.FontGlobalScale > 1.0f) + IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!"); + + // Remap legacy names + if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) + { + g.IO.ConfigNavMoveSetMousePos = true; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos; + } + if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) + { + g.IO.ConfigNavCaptureKeyboard = false; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard; + } + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) + { + g.IO.ConfigDpiScaleFonts = true; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts; + } + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + { + g.IO.ConfigDpiScaleViewports = true; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports; + } + + // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024) + if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; + if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; +#endif + + // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) + IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) + IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + + // Perform simple checks: multi-viewport and platform windows support + if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports)) + { + IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference."); + IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?"); + IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport."); + if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!"); + } + else + { + // Disable feature, our backends do not support it + g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; + } + + // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs + for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors) + { + IM_UNUSED(mon); + IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); + IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); + IM_ASSERT(mon.DpiScale > 0.0f && mon.DpiScale < 99.0f && "Monitor DpiScale is invalid."); // Typical correct values would be between 1.0f and 4.0f + } + } +} + +static void ImGui::ErrorCheckEndFrameSanityChecks() +{ + // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() + // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame(). + // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will + // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs. + // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0), + // while still correctly asserting on mid-frame key press events. + ImGuiContext& g = *GImGui; + const ImGuiKeyChord key_mods = GetMergedModsFromKeys(); + IM_UNUSED(g); + IM_UNUSED(key_mods); + IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); + IM_UNUSED(key_mods); + + IM_ASSERT(g.CurrentWindowStack.Size == 1); + IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow); +} + +// Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery. +void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out) +{ + ImGuiContext& g = *GImGui; + state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size; + state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size; + state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack! + state_out->SizeOfColorStack = (short)g.ColorStack.Size; + state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size; + state_out->SizeOfFontStack = (short)g.FontStack.Size; + state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size; + state_out->SizeOfGroupStack = (short)g.GroupStack.Size; + state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size; + state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size; + state_out->SizeOfDisabledStack = (short)g.DisabledStackSize; +} + +// Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery. +// Called by e.g. EndFrame() but may be called for manual recovery. +// Attempt to recover full window stack. +void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in) +{ + // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations" + ImGuiContext& g = *GImGui; + while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044 + { + // Recap: + // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped. + // - Always call a matching End() for each Begin() call, regardless of its return value! + // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS. + // - We will fix that in a future major update. + ImGuiWindow* window = g.CurrentWindow; + if (window->Flags & ImGuiWindowFlags_ChildWindow) + { + if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) + { + IM_ASSERT_USER_ERROR(0, "Missing EndTable()"); + EndTable(); + } + else + { + IM_ASSERT_USER_ERROR(0, "Missing EndChild()"); + EndChild(); + } + } + else + { + IM_ASSERT_USER_ERROR(0, "Missing End()"); + End(); + } + } + if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack) + ErrorRecoveryTryToRecoverWindowState(state_in); +} + +// Called by e.g. End() but may be called for manual recovery. +// Read '// Error Handling [BETA]' block in imgui_internal.h for details. +// Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. +void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in) +{ + ImGuiContext& g = *GImGui; + + while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndTable()"); + EndTable(); + } + + ImGuiWindow* window = g.CurrentWindow; + + // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet. + while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()"); + EndTabBar(); + } + while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()"); + EndMultiSelect(); + } + if (window->DC.MenuBarAppending) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()"); + EndMenuBar(); + } + while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing TreePop()"); + TreePop(); + } + while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndGroup()"); + EndGroup(); + } + IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack); + while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopID()"); + PopID(); + } + while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()"); + if (g.CurrentItemFlags & ImGuiItemFlags_Disabled) + EndDisabled(); + else + { + EndDisabledOverrideReenable(); + g.CurrentWindowStack.back().DisabledOverrideReenable = false; + } + } + IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack); + while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()"); + PopStyleColor(); + } + while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()"); + PopItemFlag(); + } + while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()"); + PopStyleVar(); + } + while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopFont()"); + PopFont(); + } + while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()"); + PopFocusScope(); + } + //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack); +} + +bool ImGui::ErrorLog(const char* msg) +{ + ImGuiContext& g = *GImGui; + + // Output to debug log +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiWindow* window = g.CurrentWindow; + + if (g.IO.ConfigErrorRecoveryEnableDebugLog) + { + if (g.ErrorFirst) + IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n", + g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip); + IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg); + } + g.ErrorFirst = false; + + // Output to tooltip + if (g.IO.ConfigErrorRecoveryEnableTooltip) + { + if (g.WithinFrameScope && BeginErrorTooltip()) + { + if (g.ErrorCountCurrentFrame < 20) + { + Text("In window '%s': %s", window ? window->Name : "NULL", msg); + if (window && (!window->IsFallbackWindow || window->WasActive)) + GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255)); + } + if (g.ErrorCountCurrentFrame == 20) + Text("(and more errors)"); + // EndFrame() will amend debug buttons to this window, after all errors have been submitted. + EndErrorTooltip(); + } + g.ErrorCountCurrentFrame++; + } +#endif + + // Output to callback + if (g.ErrorCallback != NULL) + g.ErrorCallback(&g, g.ErrorCallbackUserData, msg); + + // Return whether we should assert + return g.IO.ConfigErrorRecoveryEnableAssert; +} + +void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *GImGui; + if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false) + g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount; + if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip()) + { + Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount); + BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!"); + BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!"); + //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused. + BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds."); + Separator(); + if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker) + { + Text("(Hold Ctrl to: use "); + SameLine(0.0f, 0.0f); + if (SmallButton("Item Picker")) + DebugStartItemPicker(); + SameLine(0.0f, 0.0f); + Text(" to break in item call-stack, or "); + } + else + { + Text("(Hold Ctrl to: "); + } + SameLine(0.0f, 0.0f); + TextLinkOpenURL("read FAQ \"About ID Stack System\"", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); + SameLine(0.0f, 0.0f); + Text(")"); + EndErrorTooltip(); + } + + if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame + { + Separator(); + Text("(Hold Ctrl to: "); + SameLine(0.0f, 0.0f); + if (SmallButton("Enable Asserts")) + g.IO.ConfigErrorRecoveryEnableAssert = true; + //SameLine(); + //if (SmallButton("Hide Error Tooltips")) + // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous + SameLine(0, 0); + Text(")"); + EndErrorTooltip(); + } +#endif +} + +// Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it. +bool ImGui::BeginErrorTooltip() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = FindWindowByName("##Tooltip_Error"); + const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive); + PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f)); + if (use_locked_pos) + SetNextWindowPos(g.ErrorTooltipLockedPos); + bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize); + PopStyleColor(); + if (is_visible && g.CurrentWindow->BeginCount == 1) + { + SeparatorText("MESSAGE FROM DEAR IMGUI"); + BringWindowToDisplayFront(g.CurrentWindow); + BringWindowToFocusFront(g.CurrentWindow); + g.ErrorTooltipLockedPos = GetWindowPos(); + } + else if (!is_visible) + { + End(); + } + return is_visible; +} + +void ImGui::EndErrorTooltip() +{ + End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ITEM SUBMISSION +//----------------------------------------------------------------------------- +// - KeepAliveID() +// - ItemAdd() +//----------------------------------------------------------------------------- + +// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID(). +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = id; + if (g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.IsAlive = true; +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. +// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN) +IM_MSVC_RUNTIME_CHECKS_OFF +bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Set item data + // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set) + g.LastItemData.ID = id; + g.LastItemData.Rect = bb; + g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb; + g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags; + g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None; + // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared. + + if (id != 0) + { + KeepAliveID(id); + + // Directional navigation processing + // Runs prior to clipping early-out + // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null. + // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. + if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav)) + { + // FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. + window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent); + if (g.NavId == id || g.NavAnyRequest) + if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) + if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened)) + NavProcessItem(); + } + + if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut) + ItemHandleShortcut(id); + } + + // Lightweight clear of SetNextItemXXX data. + g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None; + g.NextItemData.ItemFlags = ImGuiItemFlags_None; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (id != 0) + IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData); +#endif + + // Clipping test + // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false') + // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts) + const bool is_rect_visible = bb.Overlaps(window->ClipRect); + if (!is_rect_visible) + if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId)) + if (!g.ItemUnclipByLog) + return false; + + // [DEBUG] +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (id != 0) + { + if (id == g.DebugLocateId) + DebugLocateItemResolveWithLastItem(); + + // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something". + // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something". + // READ THE FAQ: https://dearimgui.com/faq + IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!"); + + // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED. + // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd(). +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0) + { + int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast. + int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1); + if (*p_alive == g.FrameCount) + *p_highlight = g.FrameCount; + *p_alive = g.FrameCount; + if (*p_highlight >= g.FrameCount - 1) + window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); + } +#endif + } + //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] + //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0) + // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG] +#endif + + if (id != 0 && g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.ElapseFrame = g.FrameCount; + + // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) + if (is_rect_visible) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible; + if (IsMouseHoveringRect(bb.Min, bb.Max)) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; + return true; +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] LAYOUT +//----------------------------------------------------------------------------- +// - ItemSize() +// - SameLine() +// - GetCursorScreenPos() +// - SetCursorScreenPos() +// - GetCursorPos(), GetCursorPosX(), GetCursorPosY() +// - SetCursorPos(), SetCursorPosX(), SetCursorPosY() +// - GetCursorStartPos() +// - Indent() +// - Unindent() +// - SetNextItemWidth() +// - PushItemWidth() +// - PushMultiItemsWidths() +// - PopItemWidth() +// - CalcItemWidth() +// - CalcItemSize() +// - GetTextLineHeight() +// - GetTextLineHeightWithSpacing() +// - GetFrameHeight() +// - GetFrameHeightWithSpacing() +// - GetContentRegionMax() +// - GetContentRegionAvail(), +// - BeginGroup() +// - EndGroup() +// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. +//----------------------------------------------------------------------------- + +// Advance cursor given item size for layout. +// Register minimum needed size so it can extend the bounding box used for auto-fit calculation. +// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. +// THIS IS IN THE PERFORMANCE CRITICAL PATH. +IM_MSVC_RUNTIME_CHECKS_OFF +void ImGui::ItemSize(const ImVec2& size, float text_baseline_y) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + // We increase the height in this function to accommodate for baseline offset. + // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor, + // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. + const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f; + + const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y; + const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y); + + // Always align ourselves on pixel boundaries + //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] + window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x; + window->DC.CursorPosPrevLine.y = line_y1; + window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line + window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y); + //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG] + + window->DC.PrevLineSize.y = line_height; + window->DC.CurrLineSize.y = 0.0f; + window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y); + window->DC.CurrLineTextBaseOffset = 0.0f; + window->DC.IsSameLine = window->DC.IsSetPos = false; + + // Horizontal layout mode + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + SameLine(); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Gets back to previous line and continue with horizontal layout +// offset_from_start_x == 0 : follow right after previous item +// offset_from_start_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float offset_from_start_x, float spacing_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + if (offset_from_start_x != 0.0f) + { + if (spacing_w < 0.0f) + spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0.0f) + spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrLineSize = window->DC.PrevLineSize; + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; + window->DC.IsSameLine = true; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos; +} + +void ImGui::SetCursorScreenPos(const ImVec2& pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = pos; + //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); + window->DC.IsSetPos = true; +} + +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; +} + +float ImGui::GetCursorPosX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; +} + +float ImGui::GetCursorPosY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; +} + +void ImGui::SetCursorPos(const ImVec2& local_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; + //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); + window->DC.IsSetPos = true; +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; + //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); + window->DC.IsSetPos = true; +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; + //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); + window->DC.IsSetPos = true; +} + +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + +void ImGui::Indent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +void ImGui::Unindent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +// Affect large frame+labels widgets only. +void ImGui::SetNextItemWidth(float item_width) +{ + ImGuiContext& g = *GImGui; + g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth; + g.NextItemData.Width = item_width; +} + +// FIXME: Remove the == 0.0f behavior? +void ImGui::PushItemWidth(float item_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width + window->DC.ItemWidth = (item_width == 0.0f ? window->DC.ItemWidthDefault : item_width); + g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth; +} + +void ImGui::PushMultiItemsWidths(int components, float w_full) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(components > 0); + const ImGuiStyle& style = g.Style; + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width + float w_items = w_full - style.ItemInnerSpacing.x * (components - 1); + float prev_split = w_items; + for (int i = components - 1; i > 0; i--) + { + float next_split = IM_TRUNC(w_items * i / components); + window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f)); + prev_split = next_split; + } + window->DC.ItemWidth = ImMax(prev_split, 1.0f); + g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth; +} + +void ImGui::PopItemWidth() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->DC.ItemWidthStack.Size <= 0) + { + IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!"); + return; + } + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); + window->DC.ItemWidthStack.pop_back(); +} + +// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() +float ImGui::CalcItemWidth() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float w; + if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth) + w = g.NextItemData.Width; + else + w = window->DC.ItemWidth; + if (w < 0.0f) + { + float region_avail_x = GetContentRegionAvail().x; + w = ImMax(1.0f, region_avail_x + w); + } + w = IM_TRUNC(w); + return w; +} + +// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +// Note that only CalcItemWidth() is publicly exposed. +// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) +{ + ImVec2 avail; + if (size.x < 0.0f || size.y < 0.0f) + avail = GetContentRegionAvail(); + + if (size.x == 0.0f) + size.x = default_w; + else if (size.x < 0.0f) + size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting + + if (size.y == 0.0f) + size.y = default_h; + else if (size.y < 0.0f) + size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting + + return size; +} + +float ImGui::GetTextLineHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize; +} + +float ImGui::GetTextLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.ItemSpacing.y; +} + +float ImGui::GetFrameHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f; +} + +float ImGui::GetFrameHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max; + return mx - window->DC.CursorPos; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! +// They are bizarre local-coordinates which don't play well with scrolling. +ImVec2 ImGui::GetContentRegionMax() +{ + return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos(); +} + +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ContentRegionRect.Min - window->Pos; +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ContentRegionRect.Max - window->Pos; +} +#endif + +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated. +// FIXME-OPT: Could we safely early out on ->SkipItems? +void ImGui::BeginGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + g.GroupStack.resize(g.GroupStack.Size + 1); + ImGuiGroupData& group_data = g.GroupStack.back(); + group_data.WindowID = window->ID; + group_data.BackupCursorPos = window->DC.CursorPos; + group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine; + group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; + group_data.BackupIndent = window->DC.Indent; + group_data.BackupGroupOffset = window->DC.GroupOffset; + group_data.BackupCurrLineSize = window->DC.CurrLineSize; + group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset; + group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; + group_data.BackupHoveredIdIsAlive = g.HoveredId != 0; + group_data.BackupIsSameLine = window->DC.IsSameLine; + group_data.BackupActiveIdHasBeenEditedThisFrame = g.ActiveIdHasBeenEditedThisFrame; + group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive; + group_data.EmitItem = true; + + window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; + window->DC.Indent = window->DC.GroupOffset; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return +} + +void ImGui::EndGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls + + ImGuiGroupData& group_data = g.GroupStack.back(); + IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window? + + if (window->DC.IsSetPos) + ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); + + // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543) + ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos)); + window->DC.CursorPos = group_data.BackupCursorPos; + window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine; + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max); + window->DC.Indent = group_data.BackupIndent; + window->DC.GroupOffset = group_data.BackupGroupOffset; + window->DC.CurrLineSize = group_data.BackupCurrLineSize; + window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset; + window->DC.IsSameLine = group_data.BackupIsSameLine; + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return + + if (!group_data.EmitItem) + { + g.GroupStack.pop_back(); + return; + } + + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize()); + ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop); + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. + // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. + // Also if you grep for LastItemId you'll notice it is only used in that context. + // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) + const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; + const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true); + if (group_contains_curr_active_id) + g.LastItemData.ID = g.ActiveId; + else if (group_contains_deactivated_id) + g.LastItemData.ID = g.DeactivatedItemData.ID; + g.LastItemData.Rect = group_bb; + + // Forward Hovered flag + const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0; + if (group_contains_curr_hovered_id) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + + // Forward Edited flag + if (g.ActiveIdHasBeenEditedThisFrame && !group_data.BackupActiveIdHasBeenEditedThisFrame) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; + + // Forward Deactivated flag + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated; + if (group_contains_deactivated_id) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated; + + g.GroupStack.pop_back(); + if (g.DebugShowGroupRects) + window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] +} + + +//----------------------------------------------------------------------------- +// [SECTION] SCROLLING +//----------------------------------------------------------------------------- + +// Helper to snap on edges when aiming at an item very close to the edge, +// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +// When we refactor the scrolling API this may be configurable with a flag? +// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. +static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) +{ + if (target <= snap_min + snap_threshold) + return ImLerp(snap_min, target, center_ratio); + if (target >= snap_max - snap_threshold) + return ImLerp(target, snap_max, center_ratio); + return target; +} + +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) +{ + ImVec2 scroll = window->Scroll; + ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2); + for (int axis = 0; axis < 2; axis++) + { + if (window->ScrollTarget[axis] < FLT_MAX) + { + float center_ratio = window->ScrollTargetCenterRatio[axis]; + float scroll_target = window->ScrollTarget[axis]; + if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f) + { + float snap_min = 0.0f; + float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis]; + scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio); + } + scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); + } + scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f)); + if (!window->Collapsed && !window->SkipItems) + scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); + } + return scroll; +} + +void ImGui::ScrollToItem(ImGuiScrollFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ScrollToRectEx(window, g.LastItemData.NavRect, flags); +} + +void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags) +{ + ScrollToRectEx(window, item_rect, flags); +} + +// Scroll to keep newly navigated item fully into view +ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags) +{ + ImGuiContext& g = *GImGui; + ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); + scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x); + scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y); + //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG] + //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG] + + // Check that only one behavior is selected per axis + IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_)); + IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_)); + + // Defaults + ImGuiScrollFlags in_flags = flags; + if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX) + flags |= ImGuiScrollFlags_KeepVisibleEdgeX; + if ((flags & ImGuiScrollFlags_MaskY_) == 0) + flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY; + + const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x; + const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y; + const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0; + const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0; + + if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x) + { + if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x) + SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f); + else if (item_rect.Max.x >= scroll_rect.Max.x) + SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f); + } + else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX)) + { + if (can_be_fully_visible_x) + SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f); + else + SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f); + } + + if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y) + { + if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y) + SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f); + else if (item_rect.Max.y >= scroll_rect.Max.y) + SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f); + } + else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY)) + { + if (can_be_fully_visible_y) + SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f); + else + SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f); + } + + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); + ImVec2 delta_scroll = next_scroll - window->Scroll; + + // Also scroll parent window to keep us into view if necessary + if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow)) + { + // FIXME-SCROLL: May be an option? + if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0) + in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX; + if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0) + in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY; + delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags); + } + + return delta_scroll; +} + +float ImGui::GetScrollX() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.x; +} + +float ImGui::GetScrollY() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.x; +} + +float ImGui::GetScrollMaxY() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.y; +} + +void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x) +{ + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; + window->ScrollTargetEdgeSnapDist.x = 0.0f; +} + +void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y) +{ + window->ScrollTarget.y = scroll_y; + window->ScrollTargetCenterRatio.y = 0.0f; + window->ScrollTargetEdgeSnapDist.y = 0.0f; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiContext& g = *GImGui; + SetScrollX(g.CurrentWindow, scroll_x); +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiContext& g = *GImGui; + SetScrollY(g.CurrentWindow, scroll_y); +} + +// Note that a local position will vary depending on initial scroll value, +// This is a little bit confusing so bear with us: +// - local_pos = (absolution_pos - window->Pos) +// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window, +// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +// - They mostly exist because of legacy API. +// Following the rules above, when trying to work with scrolling code, consider that: +// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect! +// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense +// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size +void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio) +{ + IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); + window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset + window->ScrollTargetCenterRatio.x = center_x_ratio; + window->ScrollTargetEdgeSnapDist.x = 0.0f; +} + +void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio) +{ + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset + window->ScrollTargetCenterRatio.y = center_y_ratio; + window->ScrollTargetEdgeSnapDist.y = 0.0f; +} + +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +{ + ImGuiContext& g = *GImGui; + SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio); +} + +void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +{ + ImGuiContext& g = *GImGui; + SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); +} + +// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. +void ImGui::SetScrollHereX(float center_x_ratio) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x); + float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio); + SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos + + // Tweak: snap on edges when aiming at an item very close to the edge + window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x); +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHereY(float center_y_ratio) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y); + float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos + + // Tweak: snap on edges when aiming at an item very close to the edge + window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y); +} + +//----------------------------------------------------------------------------- +// [SECTION] TOOLTIPS +//----------------------------------------------------------------------------- + +bool ImGui::BeginTooltip() +{ + return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None); +} + +bool ImGui::BeginItemTooltip() +{ + if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + return false; + return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None); +} + +bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags) +{ + ImGuiContext& g = *GImGui; + + const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget; + if (is_dragdrop_tooltip) + { + // Drag and Drop tooltips are positioning differently than other tooltips: + // - offset visibility to increase visibility around mouse. + // - never clamp within outer viewport boundary. + // We call SetNextWindowPos() to enforce position and disable clamping. + // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones). + //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; + const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen); + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) + { + ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale); + ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f); + SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot); + } + + SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); + //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :( + tooltip_flags |= ImGuiTooltipFlags_OverridePrevious; + } + + // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. + if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active && !IsWindowInBeginStack(g.TooltipPreviousWindow)) + { + //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name); + SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow); + g.TooltipOverrideCount++; + } + + const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d"; + char window_name[32]; + ImFormatString(window_name, IM_COUNTOF(window_name), window_name_template, g.TooltipOverrideCount); + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking; + Begin(window_name, NULL, flags | extra_window_flags); + // 2023-03-09: Added bool return value to the API, but currently always returning true. + // If this ever returns false we need to update BeginDragDropSource() accordingly. + //if (!ret) + // End(); + //return ret; + return true; +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls + End(); +} + +void ImGui::SetTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +void ImGui::SetTooltipV(const char* fmt, va_list args) +{ + if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None)) + return; + TextV(fmt, args); + EndTooltip(); +} + +// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'. +// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse. +void ImGui::SetItemTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + if (IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + SetTooltipV(fmt, args); + va_end(args); +} + +void ImGui::SetItemTooltipV(const char* fmt, va_list args) +{ + if (IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + SetTooltipV(fmt, args); +} + + +//----------------------------------------------------------------------------- +// [SECTION] POPUPS +//----------------------------------------------------------------------------- + +// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel +bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + if (popup_flags & ImGuiPopupFlags_AnyPopupId) + { + // Return true if any popup is open at the current BeginPopup() level of the popup stack + // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level. + IM_ASSERT(id == 0); + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + return g.OpenPopupStack.Size > 0; + else + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + } + else + { + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + { + // Return true if the popup is open anywhere in the popup stack + for (ImGuiPopupData& popup_data : g.OpenPopupStack) + if (popup_data.PopupId == id) + return true; + return false; + } + else + { + // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query) + return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; + } + } +} + +bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); + if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0) + IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally + return IsPopupOpen(id, popup_flags); +} + +// Also see FindBlockingModal(NULL) +ImGuiWindow* ImGui::GetTopMostPopupModal() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) + if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) + if (popup->Flags & ImGuiWindowFlags_Modal) + return popup; + return NULL; +} + +// See Demo->Stacked Modal to confirm what this is for. +ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) + if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) + if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup)) + return popup; + return NULL; +} + + +// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing) +// should be positioned behind that modal window, unless the window was created inside the modal begin-stack. +// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent. +// - WindowA // FindBlockingModal() returns Modal1 +// - WindowB // .. returns Modal1 +// - Modal1 // .. returns Modal2 +// - WindowC // .. returns Modal2 +// - WindowD // .. returns Modal2 +// - Modal2 // .. returns Modal2 +// - WindowE // .. returns NULL +// Notes: +// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL. +// Only difference is here we check for ->Active/WasActive but it may be unnecessary. +ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.Size <= 0) + return NULL; + + // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. + for (ImGuiPopupData& popup_data : g.OpenPopupStack) + { + ImGuiWindow* popup_window = popup_data.Window; + if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal)) + continue; + if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. + continue; + if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click. + return popup_window; + if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal + continue; + return popup_window; // Place window right below first block modal + } + return NULL; +} + +void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = g.CurrentWindow->GetID(str_id); + IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id); + OpenPopupEx(id, popup_flags); +} + +void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + OpenPopupEx(id, popup_flags); +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* parent_window = g.CurrentWindow; + const int current_stack_size = g.BeginPopupStack.Size; + + if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup) + if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId)) + return; + + ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. + popup_ref.PopupId = id; + popup_ref.Window = NULL; + popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type). + popup_ref.OpenFrameCount = g.FrameCount; + popup_ref.OpenParentId = parent_window->IDStack.back(); + popup_ref.OpenPopupPos = NavCalcPreferredRefPos(ImGuiWindowFlags_Popup); + popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; + + IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id); + if (g.OpenPopupStack.Size < current_stack_size + 1) + { + g.OpenPopupStack.push_back(popup_ref); + } + else + { + // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake! + // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be + // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer. + // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified. + bool keep_existing = false; + if (g.OpenPopupStack[current_stack_size].PopupId == id) + if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen)) + keep_existing = true; + if (keep_existing) + { + // No reopen + g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; + } + else + { + // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation) + ClosePopupToLevel(current_stack_size, true); + g.OpenPopupStack.push_back(popup_ref); + } + + // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). + // This is equivalent to what ClosePopupToLevel() does. + //if (g.OpenPopupStack[current_stack_size].PopupId == id) + // FocusWindow(parent_window); + } +} + +// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. +// This function closes any popups that are over 'ref_window'. +void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.Size == 0) + return; + + // Don't close our own child popup windows. + //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "", restore_focus_to_window_under_popup); + int popup_count_to_keep = 0; + if (ref_window) + { + // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) + for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++) + { + ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + + // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow) + // - Clicking/Focusing Window2 won't close Popup1: + // Window -> Popup1 -> Window2(Ref) + // - Clicking/focusing Popup1 will close Popup2 and Popup3: + // Window -> Popup1(Ref) -> Popup2 -> Popup3 + // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree! + // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child + // We step through every popup from bottom to top to validate their position relative to reference window. + bool ref_window_is_descendent_of_popup = false; + for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) + if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window) + //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE + if (IsWindowWithinBeginStackOf(ref_window, popup_window)) + { + ref_window_is_descendent_of_popup = true; + break; + } + if (!ref_window_is_descendent_of_popup) + break; + } + } + if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below + { + IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : ""); + ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); + } +} + +void ImGui::ClosePopupsExceptModals() +{ + ImGuiContext& g = *GImGui; + + int popup_count_to_keep; + for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--) + { + ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window; + if (!window || (window->Flags & ImGuiWindowFlags_Modal)) + break; + } + if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below + ClosePopupToLevel(popup_count_to_keep, true); +} + +void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) +{ + ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup); + IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) + for (int n = remaining; n < g.OpenPopupStack.Size; n++) + IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"\n", g.OpenPopupStack[n].PopupId, g.OpenPopupStack[n].Window ? g.OpenPopupStack[n].Window->Name : NULL); + + // Trim open popup stack + ImGuiPopupData prev_popup = g.OpenPopupStack[remaining]; + g.OpenPopupStack.resize(remaining); + + // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case) + if (restore_focus_to_window_under_popup && prev_popup.Window) + { + ImGuiWindow* popup_window = prev_popup.Window; + ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow; + if (focus_window && !focus_window->WasActive) + FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback + else + FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None); + } +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.BeginPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + + // Closing a menu closes its top-most parent popup (unless a modal) + while (popup_idx > 0) + { + ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window; + ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window; + bool close_parent = false; + if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu)) + if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar)) + close_parent = true; + if (!close_parent) + break; + popup_idx--; + } + IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); + ClosePopupToLevel(popup_idx, true); + + // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. + // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window. + // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic. + if (ImGuiWindow* window = g.NavWindow) + window->DC.NavHideHighlightOneFrame = true; +} + +// Attention! BeginPopup() adds default flags when calling BeginPopupEx()! +bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + char name[20]; + IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx() + ImFormatString(name, IM_COUNTOF(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame + + bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking); + if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) + EndPopup(); + //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack; + return is_open; +} + +bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + char name[128]; + IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu); + ImFormatString(name, IM_COUNTOF(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth + bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup); + if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) + EndPopup(); + //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack; + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; + ImGuiID id = g.CurrentWindow->GetID(str_id); + return BeginPopupEx(id, flags); +} + +// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. +// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup). +// - *p_open set back to false in BeginPopupModal() when popup is not open. +// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup. +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + if (p_open && *p_open) + *p_open = false; + return false; + } + + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) + // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) + { + const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); + } + + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; + const bool is_open = Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + EndPopup(); + if (is_open) + ClosePopupToLevel(g.BeginPopupStack.Size, true); + return false; + } + return is_open; +} + +void ImGui::EndPopup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR_RET((window->Flags & ImGuiWindowFlags_Popup) != 0 && g.BeginPopupStack.Size > 0, "Calling EndPopup() in wrong window!"); + + // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests) + if (g.NavWindow == window) + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); + + // Child-popups don't need to be laid out + const ImGuiID backup_within_end_child_id = g.WithinEndChildID; + if (window->Flags & ImGuiWindowFlags_ChildWindow) + g.WithinEndChildID = window->ID; + End(); + g.WithinEndChildID = backup_within_end_child_id; +} + +ImGuiMouseButton ImGui::GetMouseButtonFromPopupFlags(ImGuiPopupFlags flags) +{ +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if ((flags & ImGuiPopupFlags_InvalidMask_) != 0) // 1,2 --> ImGuiMouseButton_Right, ImGuiMouseButton_Middle + return (flags & ImGuiPopupFlags_InvalidMask_); +#else + IM_ASSERT((flags & ImGuiPopupFlags_InvalidMask_) == 0); +#endif + if (flags & ImGuiPopupFlags_MouseButtonMask_) + return ((flags & ImGuiPopupFlags_MouseButtonMask_) >> ImGuiPopupFlags_MouseButtonShift_) - 1; + return ImGuiMouseButton_Right; // Default == 1 +} + +// Helper to open a popup if mouse button is released over the item +// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() +void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + { + ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + OpenPopupEx(id, popup_flags); + } +} + +// This is a helper to handle the simplest case of associating one named popup to one given widget. +// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id. +// - To create a popup with a specific identifier, pass it in str_id. +// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. +// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +// This is essentially the same as: +// id = str_id ? GetID(str_id) : GetItemID(); +// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight); +// return BeginPopup(id); +// Which is essentially the same as: +// id = str_id ? GetID(str_id) : GetItemID(); +// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) +// OpenPopup(id); +// return BeginPopup(id); +// The main difference being that this is tweaked to avoid computing the ID twice. +bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!str_id) + str_id = "window_context"; + ImGuiID id = window->GetID(str_id); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); + if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!str_id) + str_id = "void_context"; + ImGuiID id = window->GetID(str_id); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); + if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) + if (GetTopMostPopupModal() == NULL) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor +// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport. +// this allows us to have tooltips/popups displayed out of the parent viewport.) +ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy) +{ + ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); + //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); + //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); + + // Combo Box policy (we want a connecting edge) + if (policy == ImGuiPopupPositionPolicy_ComboBox) + { + const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + ImVec2 pos; + if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) + if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right + if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left + if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left + if (!r_outer.Contains(ImRect(pos, pos + size))) + continue; + *last_dir = dir; + return pos; + } + } + + // Tooltip and Default popup policy + // (Always first try the direction we used on the last frame, if any) + if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default) + { + const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + + const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); + const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); + + // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width) + if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) + continue; + if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) + continue; + + ImVec2 pos; + pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; + pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; + + // Clamp top-left corner of popup + pos.x = ImMax(pos.x, r_outer.Min.x); + pos.y = ImMax(pos.y, r_outer.Min.y); + + *last_dir = dir; + return pos; + } + } + + // Fallback when not enough room: + *last_dir = ImGuiDir_None; + + // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + if (policy == ImGuiPopupPositionPolicy_Tooltip) + return ref_pos + ImVec2(2, 2); + + // Otherwise try to keep within display + ImVec2 pos = ref_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +// Note that this is used for popups, which can overlap the non work-area of individual viewports. +ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImRect r_screen; + if (window->ViewportAllowPlatformMonitorExtend >= 0) + { + // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here) + const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend]; + r_screen.Min = monitor.WorkPos; + r_screen.Max = monitor.WorkPos + monitor.WorkSize; + } + else + { + // Use the full viewport area (not work area) for popups + r_screen = window->Viewport->GetMainRect(); + } + ImVec2 padding = g.Style.DisplaySafeAreaPadding; + r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); + return r_screen; +} + +ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + ImRect r_outer = GetPopupAllowedExtentRect(window); + if (window->Flags & ImGuiWindowFlags_ChildMenu) + { + // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. + ImGuiWindow* parent_window = window->ParentWindow; + float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + ImRect r_avoid; + if (parent_window->DC.MenuBarAppending) + r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field + else + r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default); + } + if (window->Flags & ImGuiWindowFlags_Popup) + { + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here + } + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Position tooltip (always follows mouse + clamp within outer boundaries) + // FIXME: + // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default). + // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position. + // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling + // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin(). + IM_ASSERT(g.CurrentWindow == window); + const float scale = g.Style.MouseCursorScale; + const ImVec2 ref_pos = NavCalcPreferredRefPos(ImGuiWindowFlags_Tooltip); + + if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource(ImGuiWindowFlags_Tooltip) == ImGuiInputSource_Mouse) + { + ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size); + if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size))) + return tooltip_pos; + } + + ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale; + ImRect r_avoid; + if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos) + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); + else + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. + //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255)); + + return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip); + } + IM_ASSERT(0); + return window->Pos; +} + +//----------------------------------------------------------------------------- +// [SECTION] WINDOW FOCUS +//---------------------------------------------------------------------------- +// - SetWindowFocus() +// - SetNextWindowFocus() +// - IsWindowFocused() +// - UpdateWindowInFocusOrderList() [Internal] +// - BringWindowToFocusFront() [Internal] +// - BringWindowToDisplayFront() [Internal] +// - BringWindowToDisplayBack() [Internal] +// - BringWindowToDisplayBehind() [Internal] +// - FindWindowDisplayIndex() [Internal] +// - FocusWindow() [Internal] +// - FocusTopMostWindowUnderOne() [Internal] +//----------------------------------------------------------------------------- + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char* name) +{ + if (name) + { + if (ImGuiWindow* window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus; +} + +// Similar to IsWindowHovered() +bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* ref_window = g.NavWindow; + ImGuiWindow* cur_window = g.CurrentWindow; + + if (ref_window == NULL) + return false; + if (flags & ImGuiFocusedFlags_AnyWindow) + return true; + + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; + const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0; + if (flags & ImGuiFocusedFlags_RootWindow) + cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + if (flags & ImGuiFocusedFlags_ChildWindows) + return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + return ref_window == cur_window; +} + +static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + int order = window->FocusOrder; + IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking) + IM_ASSERT(g.WindowsFocusOrder[order] == window); + return order; +} + +static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags) +{ + ImGuiContext& g = *GImGui; + + const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0); + const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild; + if ((just_created || child_flag_changed) && !new_is_explicit_child) + { + IM_ASSERT(!g.WindowsFocusOrder.contains(window)); + g.WindowsFocusOrder.push_back(window); + window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1); + } + else if (!just_created && child_flag_changed && new_is_explicit_child) + { + IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window); + for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++) + g.WindowsFocusOrder[n]->FocusOrder--; + g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder); + window->FocusOrder = -1; + } + window->IsExplicitChild = new_is_explicit_child; +} + +void ImGui::BringWindowToFocusFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(window == window->RootWindow); + + const int cur_order = window->FocusOrder; + IM_ASSERT(g.WindowsFocusOrder[cur_order] == window); + if (g.WindowsFocusOrder.back() == window) + return; + + const int new_order = g.WindowsFocusOrder.Size - 1; + for (int n = cur_order; n < new_order; n++) + { + g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1]; + g.WindowsFocusOrder[n]->FocusOrder--; + IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n); + } + g.WindowsFocusOrder[new_order] = window; + window->FocusOrder = (short)new_order; +} + +// Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +// FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow(). +void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* current_front_window = g.Windows.back(); + if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better) + return; + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window + if (g.Windows[i] == window) + { + memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); + g.Windows[g.Windows.Size - 1] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.Windows[0] == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); + g.Windows[0] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window) +{ + IM_ASSERT(window != NULL && behind_window != NULL); + ImGuiContext& g = *GImGui; + window = window->RootWindow; + behind_window = behind_window->RootWindow; + int pos_wnd = FindWindowDisplayIndex(window); + int pos_beh = FindWindowDisplayIndex(behind_window); + if (pos_wnd < pos_beh) + { + size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*); + memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes); + g.Windows[pos_beh - 1] = window; + } + else + { + size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*); + memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes); + g.Windows[pos_beh] = window; + } +} + +int ImGui::FindWindowDisplayIndex(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + return g.Windows.index_from_ptr(g.Windows.find(window)); +} + +// Moving window to front of display and set focus (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Modal check? + if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case. + if (ImGuiWindow* blocking_modal = FindBlockingModal(window)) + { + // This block would typically be reached in two situations: + // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag. + // - User clicking on void or anything behind a modal while a modal is open (window == NULL) + IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "", blocking_modal->Name); + if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?) + ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals + return; + } + + // Find last focused child (if any) and focus it instead. + if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL) + window = NavRestoreLastChildNavWindow(window); + + // Apply focus + if (g.NavWindow != window) + { + SetNavWindow(window); + if (window && g.NavHighlightItemUnderNav) + g.NavMousePosDirty = true; + g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId + g.NavLayer = ImGuiNavLayer_Main; + SetNavFocusScope(window ? window->NavRootFocusScopeId : 0); + g.NavIdIsAlive = false; + g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + + // Close popups if any + ClosePopupsOverWindow(window, false); + } + + // Move the root window to the top of the pile + IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL); + ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; + ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL; + ImGuiDockNode* dock_node = window ? window->DockNode : NULL; + bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) + // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) + if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + window->LastFrameJustFocused = g.FrameCount; + + // Select in dock node + // For #2304 we avoid applying focus immediately before the tabbar is visible. + //if (dock_node && dock_node->TabBar) + // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId; + + // Bring to front + BringWindowToFocusFront(focus_front_window); + if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayFront(display_front_window); +} + +void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags) +{ + ImGuiContext& g = *GImGui; + int start_idx = g.WindowsFocusOrder.Size - 1; + if (under_this_window != NULL) + { + // Aim at root window behind us, if we are in a child window that's our own root (see #4640) + int offset = -1; + while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow) + { + under_this_window = under_this_window->ParentWindow; + offset = 0; + } + start_idx = FindWindowFocusIndex(under_this_window) + offset; + } + for (int i = start_idx; i >= 0; i--) + { + // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. + ImGuiWindow* window = g.WindowsFocusOrder[i]; + if (window == ignore_window || !window->WasActive) + continue; + if (filter_viewport != NULL && window->Viewport != filter_viewport) + continue; + if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) + { + // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set... + // This is failing (lagging by one frame) for docked windows. + // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B. + // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update) + // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself? + FocusWindow(window, flags); + return; + } + } + FocusWindow(NULL, flags); +} + +//----------------------------------------------------------------------------- +// [SECTION] KEYBOARD/GAMEPAD NAVIGATION +//----------------------------------------------------------------------------- + +// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked. +// In our terminology those should be interchangeable, yet right now this is super confusing. +// Those two functions are merely a legacy artifact, so at minimum naming should be clarified. + +void ImGui::SetNavCursorVisible(bool visible) +{ + ImGuiContext& g = *GImGui; + if (g.IO.ConfigNavCursorVisibleAlways) + visible = true; + g.NavCursorVisible = visible; +} + +// (was called NavRestoreHighlightAfterMove() before 1.91.4) +void ImGui::SetNavCursorVisibleAfterMove() +{ + ImGuiContext& g = *GImGui; + if (g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = true; + g.NavHighlightItemUnderNav = g.NavMousePosDirty = true; +} + +void ImGui::SetNavWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.NavWindow != window) + { + IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : ""); + g.NavWindow = window; + g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + } + g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavHighlightActivated(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.NavHighlightActivatedId = id; + g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER; +} + +void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX; +} + +void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindow != NULL); + IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu); + g.NavId = id; + g.NavLayer = nav_layer; + SetNavFocusScope(focus_scope_id); + g.NavWindow->NavLastIds[nav_layer] = id; + g.NavWindow->NavRectRel[nav_layer] = rect_rel; + + // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) + NavClearPreferredPosForAxis(ImGuiAxis_X); + NavClearPreferredPosForAxis(ImGuiAxis_Y); +} + +void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(id != 0); + + if (g.NavWindow != window) + SetNavWindow(window); + + // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid. + // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) + const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent; + g.NavId = id; + g.NavLayer = nav_layer; + SetNavFocusScope(g.CurrentFocusScopeId); + window->NavLastIds[nav_layer] = id; + if (g.LastItemData.ID == id) + window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect); + if (id == g.ActiveIdIsAlive) + g.NavIdIsAlive = true; + + if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) + g.NavHighlightItemUnderNav = true; + else if (g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = false; + + // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) + NavClearPreferredPosForAxis(ImGuiAxis_X); + NavClearPreferredPosForAxis(ImGuiAxis_Y); +} + +static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy) +{ + if (ImFabs(dx) > ImFabs(dy)) + return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; + return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; +} + +static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max) +{ + if (cand_max < curr_min) + return cand_max - curr_min; + if (curr_max < cand_min) + return cand_min - curr_max; + return 0.0f; +} + +// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057 +static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.NavLayer != window->DC.NavLayerCurrent) + return false; + + // FIXME: Those are not good variables names + ImRect cand = nav_bb; // Current item nav rectangle + const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) + g.NavScoringDebugCount++; + + // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring + if (window->ParentWindow == g.NavWindow) + { + IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened); + if (!window->ClipRect.Overlaps(cand)) + return false; + cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window + } + + // Compute distance between boxes + // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. + float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); + float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items + if (dby != 0.0f && dbx != 0.0f) + dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); + float dist_box = ImFabs(dbx) + ImFabs(dby); + + // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) + float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); + float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); + float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) + + // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance + ImGuiDir quadrant; + float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; + if (dbx != 0.0f || dby != 0.0f) + { + // For non-overlapping boxes, use distance between boxes + // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y + // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail. + // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty. + dax = dbx; + day = dby; + dist_axial = dist_box; + quadrant = ImGetDirQuadrantFromDelta(dbx, dby); + } + else if (dcx != 0.0f || dcy != 0.0f) + { + // For overlapping boxes with different centers, use distance between centers + dax = dcx; + day = dcy; + dist_axial = dist_center; + quadrant = ImGetDirQuadrantFromDelta(dcx, dcy); + } + else + { + // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) + quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; + } + + const ImGuiDir move_dir = g.NavMoveDir; +#if IMGUI_DEBUG_NAV_SCORING + char buf[200]; + if (g.IO.KeyCtrl) // Hold Ctrl to preview score in matching quadrant. Ctrl+Arrow to rotate. + { + if (quadrant == move_dir) + { + ImFormatString(buf, IM_COUNTOF(buf), "%.0f/%.0f", dist_box, dist_center); + ImDrawList* draw_list = GetForegroundDrawList(window); + draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80)); + draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200)); + draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf); + } + } + const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max); + const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space)); + if (debug_hovering || debug_tty) + { + ImFormatString(buf, IM_COUNTOF(buf), + "d-box (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c", + dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]); + if (debug_hovering) + { + ImDrawList* draw_list = GetForegroundDrawList(window); + draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100)); + draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200)); + draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200)); + draw_list->AddText(cand.Max, ~0U, buf); + } + if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); } + } +#endif + + // Is it in the quadrant we're interested in moving to? + bool new_best = false; + if (quadrant == move_dir) + { + // Does it beat the current best candidate? + if (dist_box < result->DistBox) + { + result->DistBox = dist_box; + result->DistCenter = dist_center; + return true; + } + if (dist_box == result->DistBox) + { + // Try using distance between center points to break ties + if (dist_center < result->DistCenter) + { + result->DistCenter = dist_center; + new_best = true; + } + else if (dist_center == result->DistCenter) + { + // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance + new_best = true; + } + } + } + + // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match + if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f)) + { + result->DistAxial = dist_axial; + new_best = true; + } + + return new_best; +} + +static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + result->Window = window; + result->ID = g.LastItemData.ID; + result->FocusScopeId = g.CurrentFocusScopeId; + result->ItemFlags = g.LastItemData.ItemFlags; + result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect); + if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) + { + IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid); + result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. + } +} + +// True when current work location may be scrolled horizontally when moving left / right. +// This is generally always true UNLESS within a column. We don't have a vertical equivalent. +void ImGui::NavUpdateCurrentWindowIsScrollPushableX() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL); +} + +// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +// This is called after LastItemData is set, but NextItemData is also still valid. +static void ImGui::NavProcessItem() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = g.LastItemData.ID; + const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags; + + // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816) + ImRect nav_bb = g.LastItemData.NavRect; + if (window->DC.NavIsScrollPushableX == false) + { + nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x); + nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x); + } + + // Process Init Request + if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0) + { + // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback + const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0; + if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0) + { + NavApplyItemToResult(&g.NavInitResult); + } + if (candidate_for_nav_default_focus) + { + g.NavInitRequest = false; // Found a match, clear request + NavUpdateAnyRequestFlag(); + } + } + + // Process Move Request (scoring for navigation) + // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy) + if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0) + { + if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0) + { + const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0; + if (is_tabbing) + { + NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags); + } + else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) + { + ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; + if (NavScoreItem(result, nav_bb)) + NavApplyItemToResult(result); + + // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. + const float VISIBLE_RATIO = 0.70f; + if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) + { + const ImRect& r = window->InnerRect; // window->ClipRect + if (r.Overlaps(nav_bb)) + if (ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) + if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb)) + NavApplyItemToResult(&g.NavMoveResultLocalVisible); + } + } + } + } + + // Update information for currently focused/navigated item + if (g.NavId == id) + { + if (g.NavWindow != window) + SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window. + g.NavLayer = window->DC.NavLayerCurrent; + SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath + g.NavFocusScopeId = g.CurrentFocusScopeId; + g.NavIdIsAlive = true; + if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData) + { + IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid); + g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. + } + window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position) + } +} + +// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest(). +// Note that SetKeyboardFocusHere() API calls are considered tabbing requests! +// - Case 1: no nav/active id: set result to first eligible item, stop storing. +// - Case 2: tab forward: on ref id set counter, on counter elapse store result +// - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request +// - Case 4: tab backward: store all results, on ref id pick prev, stop storing +// - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested +void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags) +{ + ImGuiContext& g = *GImGui; + + if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0) + { + if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent) + return; + if (g.NavFocusScopeId != g.CurrentFocusScopeId) + return; + } + + // - Can always land on an item when using API call. + // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item. + // - Tabbing without _NavEnableKeyboard: goes through inputable items only. + bool can_stop; + if (move_flags & ImGuiNavMoveFlags_FocusApi) + can_stop = true; + else + can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable)); + + // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows) + ImGuiNavItemData* result = &g.NavMoveResultLocal; + if (g.NavTabbingDir == +1) + { + // Tab Forward or SetKeyboardFocusHere() with >= 0 + if (can_stop && g.NavTabbingResultFirst.ID == 0) + NavApplyItemToResult(&g.NavTabbingResultFirst); + if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0) + NavMoveRequestResolveWithLastItem(result); + else if (g.NavId == id) + g.NavTabbingCounter = 1; + } + else if (g.NavTabbingDir == -1) + { + // Tab Backward + if (g.NavId == id) + { + if (result->ID) + { + g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); + } + } + else if (can_stop) + { + // Keep applying until reaching NavId + NavApplyItemToResult(result); + } + } + else if (g.NavTabbingDir == 0) + { + if (can_stop && g.NavId == id) + NavMoveRequestResolveWithLastItem(result); + if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init + NavApplyItemToResult(&g.NavTabbingResultFirst); + } +} + +bool ImGui::NavMoveRequestButNoResultYet() +{ + ImGuiContext& g = *GImGui; + return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; +} + +// FIXME: ScoringRect is not set +void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindow != NULL); + //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name); + + if (move_flags & ImGuiNavMoveFlags_IsTabbing) + move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId; + + g.NavMoveSubmitted = g.NavMoveScoringItems = true; + g.NavMoveDir = move_dir; + g.NavMoveDirForDebug = move_dir; + g.NavMoveClipDir = clip_dir; + g.NavMoveFlags = move_flags; + g.NavMoveScrollFlags = scroll_flags; + g.NavMoveForwardToNextFrame = false; + g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods; + g.NavMoveResultLocal.Clear(); + g.NavMoveResultLocalVisible.Clear(); + g.NavMoveResultOther.Clear(); + g.NavTabbingCounter = 0; + g.NavTabbingResultFirst.Clear(); + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) +{ + ImGuiContext& g = *GImGui; + g.NavMoveScoringItems = false; // Ensure request doesn't need more processing + NavApplyItemToResult(result); + NavUpdateAnyRequestFlag(); +} + +// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent +void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data) +{ + ImGuiContext& g = *GImGui; + g.NavMoveScoringItems = false; + g.LastItemData.ID = tree_node_data->ID; + g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper). + g.LastItemData.NavRect = tree_node_data->NavRect; + NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult() + NavClearPreferredPosForAxis(ImGuiAxis_Y); + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavMoveRequestCancel() +{ + ImGuiContext& g = *GImGui; + g.NavMoveSubmitted = g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); +} + +// Forward will reuse the move request again on the next frame (generally with modifications done to it) +void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavMoveForwardToNextFrame == false); + NavMoveRequestCancel(); + g.NavMoveForwardToNextFrame = true; + g.NavMoveDir = move_dir; + g.NavMoveClipDir = clip_dir; + g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded; + g.NavMoveScrollFlags = scroll_flags; +} + +// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire +// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. +void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY + + // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it: + // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest(). + if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == window->DC.NavLayerCurrent) + g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags; +} + +// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +// This way we could find the last focused window among our children. It would be much less confusing this way? +static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window) +{ + ImGuiWindow* parent = nav_window; + while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + parent = parent->ParentWindow; + if (parent && parent != nav_window) + parent->NavLastChildNavWindow = nav_window; +} + +// Restore the last focused child. +// Call when we are expected to land on the Main Layer (0) after FocusWindow() +static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) +{ + if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) + return window->NavLastChildNavWindow; + if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar) + if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar)) + return tab->Window; + return window; +} + +void ImGui::NavRestoreLayer(ImGuiNavLayer layer) +{ + ImGuiContext& g = *GImGui; + if (layer == ImGuiNavLayer_Main) + { + ImGuiWindow* prev_nav_window = g.NavWindow; + g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests? + g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + if (prev_nav_window) + IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name); + } + ImGuiWindow* window = g.NavWindow; + if (window->NavLastIds[layer] != 0) + { + SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]); + } + else + { + g.NavLayer = layer; + NavInitWindow(window, true); + } +} + +static inline void ImGui::NavUpdateAnyRequestFlag() +{ + ImGuiContext& g = *GImGui; + g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL); + if (g.NavAnyRequest) + IM_ASSERT(g.NavWindow != NULL); +} + +// This needs to be called before we submit any widget (aka in or before Begin) +void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) +{ + // FIXME: ChildWindow test here is wrong for docking + ImGuiContext& g = *GImGui; + IM_ASSERT(window == g.NavWindow); + + if (window->Flags & ImGuiWindowFlags_NoNavInputs) + { + g.NavId = 0; + SetNavFocusScope(window->NavRootFocusScopeId); + return; + } + + bool init_for_nav = false; + if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) + init_for_nav = true; + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); + if (init_for_nav) + { + SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect()); + g.NavInitRequest = true; + g.NavInitRequestFromMove = false; + g.NavInitResult.ID = 0; + NavUpdateAnyRequestFlag(); + } + else + { + g.NavId = window->NavLastIds[0]; + SetNavFocusScope(window->NavRootFocusScopeId); + } +} + +// Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138) +// When calling for ImGuiWindowFlags_Popup we use LastItemData. +static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.NavWindow; + + const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + if ((window_type & ImGuiWindowFlags_Popup) && activated_shortcut) + return ImGuiInputSource_Keyboard; + + if (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) + return ImGuiInputSource_Mouse; + else + return ImGuiInputSource_Keyboard; // or Nav in general +} + +static ImVec2 ImGui::NavCalcPreferredRefPos(ImGuiWindowFlags window_type) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.NavWindow; + ImGuiInputSource source = NavCalcPreferredRefPosSource(window_type); + + if (source == ImGuiInputSource_Mouse) + { + // Mouse (we need a fallback in case the mouse becomes invalid after being used) + // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard. + // In theory we could move that +1.0f offset in OpenPopupEx() + ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos; + return ImVec2(p.x + 1.0f, p.y); + } + else + { + // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item + const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + ImRect ref_rect; + if (activated_shortcut && (window_type & ImGuiWindowFlags_Popup)) + ref_rect = g.LastItemData.NavRect; + else if (window != NULL) + ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]); + + // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?) + if (window != NULL && window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX)) + { + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); + ref_rect.Translate(window->Scroll - next_scroll); + } + ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight())); + if (window != NULL) + if (ImGuiViewport* viewport = window->Viewport) + pos = ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size); + return ImTrunc(pos); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta. + } +} + +float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + float repeat_delay, repeat_rate; + GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate); + + ImGuiKey key_less, key_more; + if (g.NavInputSource == ImGuiInputSource_Gamepad) + { + key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp; + key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown; + } + else + { + key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow; + key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow; + } + float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate); + if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase + amount = 0.0f; + return amount; +} + +static void ImGui::NavUpdate() +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + io.WantSetMousePos = false; + //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); + + // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard) + // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource? + const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown }; + if (nav_gamepad_active) + for (ImGuiKey key : nav_gamepad_keys_to_change_source) + if (IsKeyDown(key)) + g.NavInputSource = ImGuiInputSource_Gamepad; + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow }; + if (nav_keyboard_active) + for (ImGuiKey key : nav_keyboard_keys_to_change_source) + if (IsKeyDown(key)) + g.NavInputSource = ImGuiInputSource_Keyboard; + + // Process navigation init request (select first/default focus) + g.NavJustMovedToId = 0; + g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0; + if (g.NavInitResult.ID != 0) + NavInitRequestApplyResult(); + g.NavInitRequest = false; + g.NavInitRequestFromMove = false; + g.NavInitResult.ID = 0; + + // Process navigation move request + if (g.NavMoveSubmitted) + NavMoveRequestApplyResult(); + g.NavTabbingCounter = 0; + g.NavMoveSubmitted = g.NavMoveScoringItems = false; + if (g.NavCursorHideFrames > 0) + if (--g.NavCursorHideFrames == 0) + g.NavCursorVisible = true; + + // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling) + bool set_mouse_pos = false; + if (g.NavMousePosDirty && g.NavIdIsAlive) + if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow) + set_mouse_pos = true; + g.NavMousePosDirty = false; + IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu); + + // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0 + if (g.NavWindow) + NavSaveLastChildNavWindowIntoParent(g.NavWindow); + if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main) + g.NavWindow->NavLastChildNavWindow = NULL; + + // Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.) + NavUpdateWindowing(); + + // Set output flags for user application + io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); + io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL); + + // Process NavCancel input (to close a popup, get back to parent, clear focus) + NavUpdateCancelRequest(); + + // Process manual activation request + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0; + g.NavActivateFlags = ImGuiActivateFlags_None; + if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + { + const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner)); + const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner))); + const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner)); + const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner))); + if (g.ActiveId == 0 && activate_pressed) + { + g.NavActivateId = g.NavId; + g.NavActivateFlags = ImGuiActivateFlags_PreferTweak; + } + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed) + { + g.NavActivateId = g.NavId; + g.NavActivateFlags = ImGuiActivateFlags_PreferInput; + } + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down)) + g.NavActivateDownId = g.NavId; + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed)) + { + g.NavActivatePressedId = g.NavId; + NavHighlightActivated(g.NavId); + } + } + if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + g.NavCursorVisible = false; + else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0) + g.NavCursorVisible = true; + if (g.NavActivateId != 0) + IM_ASSERT(g.NavActivateDownId == g.NavActivateId); + + // Highlight + if (g.NavHighlightActivatedTimer > 0.0f) + g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime); + if (g.NavHighlightActivatedTimer == 0.0f) + g.NavHighlightActivatedId = 0; + + // Process programmatic activation request + // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others) + if (g.NavNextActivateId != 0) + { + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId; + g.NavActivateFlags = g.NavNextActivateFlags; + } + g.NavNextActivateId = 0; + + // Process move requests + NavUpdateCreateMoveRequest(); + if (g.NavMoveDir == ImGuiDir_None) + NavUpdateCreateTabbingRequest(); + NavUpdateAnyRequestFlag(); + g.NavIdIsAlive = false; + + // Scrolling + if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) + { + // *Fallback* manual-scroll with Nav directional keys when window has no navigable item + ImGuiWindow* window = g.NavWindow; + const float scroll_speed = IM_ROUND(window->FontRefSize * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. + const ImGuiDir move_dir = g.NavMoveDir; + if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None) + { + if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) + SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); + if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) + SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); + } + + // *Normal* Manual scroll with LStick + // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. + if (nav_gamepad_active) + { + const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown); + const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f; + if (scroll_dir.x != 0.0f && window->ScrollbarX) + SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor)); + if (scroll_dir.y != 0.0f) + SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor)); + } + } + + // Always prioritize mouse highlight if navigation is disabled + if (!nav_keyboard_active && !nav_gamepad_active) + { + g.NavCursorVisible = false; + g.NavHighlightItemUnderNav = set_mouse_pos = false; + } + + // Update mouse position if requested + // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) + if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) + TeleportMousePos(NavCalcPreferredRefPos(ImGuiWindowFlags_Popup)); + + // [DEBUG] + g.NavScoringDebugCount = 0; +#if IMGUI_DEBUG_NAV_RECTS + if (ImGuiWindow* debug_window = g.NavWindow) + { + ImDrawList* draw_list = GetForegroundDrawList(debug_window); + int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); } + //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } + } +#endif +} + +void ImGui::NavInitRequestApplyResult() +{ + // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) + ImGuiContext& g = *GImGui; + if (!g.NavWindow) + return; + + ImGuiNavItemData* result = &g.NavInitResult; + if (g.NavId != result->ID) + { + g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId; + g.NavJustMovedToId = result->ID; + g.NavJustMovedToFocusScopeId = result->FocusScopeId; + g.NavJustMovedToKeyMods = 0; + g.NavJustMovedToIsTabbing = false; + g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; + } + + // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name); + SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); + g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result + if (result->SelectionUserData != ImGuiSelectionUserData_Invalid) + g.NavLastValidSelectionUserData = result->SelectionUserData; + if (g.NavInitRequestFromMove) + SetNavCursorVisibleAfterMove(); +} + +// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position +static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags) +{ + // Bias initial rect + ImGuiContext& g = *GImGui; + const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos; + + // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias. + // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column. + // - But each successful move sets new bias on one axis, only cleared when using mouse. + if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0) + { + if (preferred_pos_rel.x == FLT_MAX) + preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x; + if (preferred_pos_rel.y == FLT_MAX) + preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y; + } + + // Apply general bias on the other axis + if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX) + r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x; + else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX) + r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y; +} + +void ImGui::NavUpdateCreateMoveRequest() +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + ImGuiWindow* window = g.NavWindow; + const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + + if (g.NavMoveForwardToNextFrame && window != NULL) + { + // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) + // (preserve most state, which were already set by the NavMoveRequestForward() function) + IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None); + IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded); + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir); + } + else + { + // Initiate directional inputs request + g.NavMoveDir = ImGuiDir_None; + g.NavMoveFlags = ImGuiNavMoveFlags_None; + g.NavMoveScrollFlags = ImGuiScrollFlags_None; + if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs)) + { + const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove; + if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; } + if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; } + if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; } + if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; } + } + g.NavMoveClipDir = g.NavMoveDir; + g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + } + + // Update PageUp/PageDown/Home/End scroll + // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag? + float scoring_page_offset_y = 0.0f; + if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active) + scoring_page_offset_y = NavUpdatePageUpPageDown(); + + // [DEBUG] Always send a request when holding Ctrl. Hold Ctrl + Arrow change the direction. +#if IMGUI_DEBUG_NAV_SCORING + //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C)) + // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3); + if (io.KeyCtrl) + { + if (g.NavMoveDir == ImGuiDir_None) + g.NavMoveDir = g.NavMoveDirForDebug; + g.NavMoveClipDir = g.NavMoveDir; + g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult; + } +#endif + + // Submit + g.NavMoveForwardToNextFrame = false; + if (g.NavMoveDir != ImGuiDir_None) + NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); + + // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) + if (g.NavMoveSubmitted && g.NavId == 0) + { + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer); + g.NavInitRequest = g.NavInitRequestFromMove = true; + g.NavInitResult.ID = 0; + if (g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = true; + } + + // When using gamepad, we project the reference nav bounding box into window visible area. + // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, + // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse). + if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded)) + { + bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0; + bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0; + ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1))); + + // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171) + // Otherwise 'inner_rect_rel' would be off on the move result frame. + inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll); + + if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer])) + { + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n"); + float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f); + float pad_y = ImMin(inner_rect_rel.GetHeight(), window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item + inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX; + inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX; + inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX; + inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX; + window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel); + g.NavId = 0; + } + } + + // Prepare scoring rectangle. + // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) + ImRect scoring_rect; + if (window != NULL) + { + ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); + scoring_rect = WindowRectRelToAbs(window, nav_rect_rel); + + if (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove) + { + // When we start from a visible location, score visible items and prioritize this result. + if (window->InnerRect.Contains(scoring_rect)) + g.NavMoveFlags |= ImGuiNavMoveFlags_AlsoScoreVisibleSet; + g.NavScoringNoClipRect = scoring_rect; + scoring_rect.TranslateY(scoring_page_offset_y); + g.NavScoringNoClipRect.Add(scoring_rect); + } + + //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Pre-bias + if (g.NavMoveSubmitted) + NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags); + IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem(). + //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Post-bias + //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)); } // [DEBUG] + } + g.NavScoringRect = scoring_rect; + //g.NavScoringNoClipRect.Add(scoring_rect); +} + +void ImGui::NavUpdateCreateTabbingRequest() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.NavWindow; + IM_ASSERT(g.NavMoveDir == ImGuiDir_None); + if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs)) + return; + + const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt; + if (!tab_pressed) + return; + + // Initiate tabbing request + // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!) + // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping. + const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + if (nav_keyboard_active) + g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1; + else + g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1; + ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate; + ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY; + ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down; + NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. + g.NavTabbingCounter = -1; +} + +// Apply result from previous frame navigation directional move request. Always called from NavUpdate() +void ImGui::NavMoveRequestApplyResult() +{ + ImGuiContext& g = *GImGui; +#if IMGUI_DEBUG_NAV_SCORING + if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times + return; +#endif + + // Select which result to use + ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL; + + // Tabbing forward wrap + if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL) + if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID) + result = &g.NavTabbingResultFirst; + + // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) + const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + if (result == NULL) + { + if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) + g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible; + if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0) + SetNavCursorVisibleAfterMove(); + NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis. + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n"); + return; + } + + // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. + if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) + if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId) + result = &g.NavMoveResultLocalVisible; + + // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. + if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) + if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter)) + result = &g.NavMoveResultOther; + IM_ASSERT(g.NavWindow && result->Window); + + // Scroll to keep newly navigated item fully into view. + if (g.NavLayer == ImGuiNavLayer_Main) + { + ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel); + ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags); + + if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY) + { + // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge? + float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f; + SetScrollY(result->Window, scroll_target); + } + } + + if (g.NavWindow != result->Window) + { + IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name); + g.NavWindow = result->Window; + g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + } + + // Clear active id unless requested not to + // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction, + // so this is mostly provided as a gateway for further experiments (see #1418, #2890) + if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0) + ClearActiveID(); + + // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) + // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior. + if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0) + { + g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId; + g.NavJustMovedToId = result->ID; + g.NavJustMovedToFocusScopeId = result->FocusScopeId; + g.NavJustMovedToKeyMods = g.NavMoveKeyMods; + g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0; + g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; + //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId); + } + + // Apply new NavID/Focus + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name); + ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer]; + SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); + if (result->SelectionUserData != ImGuiSelectionUserData_Invalid) + g.NavLastValidSelectionUserData = result->SelectionUserData; + + // Restore last preferred position for current axis + // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..) + if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0) + { + preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis]; + g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel; + } + + // Tabbing: Activates Inputable, otherwise only Focus + if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0) + g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate; + + // Activate + if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate) + { + g.NavNextActivateId = result->ID; + g.NavNextActivateFlags = ImGuiActivateFlags_None; + if (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) + g.NavNextActivateFlags |= ImGuiActivateFlags_FromFocusApi; + if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) + g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing; + } + + // Make nav cursor visible + if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0) + SetNavCursorVisibleAfterMove(); +} + +// Process Escape/NavCancel input (to close a popup, get back to parent, clear focus) +// FIXME: In order to support e.g. Escape to clear a selection we'll need: +// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it. +// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept +static void ImGui::NavUpdateCancelRequest() +{ + ImGuiContext& g = *GImGui; + const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner))) + return; + + IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n"); + if (g.ActiveId != 0) + { + ClearActiveID(); + } + else if (g.NavLayer != ImGuiNavLayer_Main) + { + // Leave the "menu" layer + NavRestoreLayer(ImGuiNavLayer_Main); + SetNavCursorVisibleAfterMove(); + } + else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow) + { + // Exit child window + ImGuiWindow* child_window = g.NavWindow->RootWindowForNav; + ImGuiWindow* parent_window = child_window->ParentWindow; + IM_ASSERT(child_window->ChildId != 0); + FocusWindow(parent_window); + SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect())); + SetNavCursorVisibleAfterMove(); + } + else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) + { + // Close open popup/menu + ClosePopupToLevel(g.OpenPopupStack.Size - 1, true); + } + else + { + // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + // FIXME-NAV: This should happen on window appearing. + if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow) + if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) + g.NavWindow->NavLastIds[0] = 0; + + // Clear nav focus + if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow) + g.NavId = 0; + if (g.IO.ConfigNavEscapeClearFocusWindow) + FocusWindow(NULL); + } +} + +// Handle PageUp/PageDown/Home/End keys +// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request +// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference +// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid? +static float ImGui::NavUpdatePageUpPageDown() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.NavWindow; + if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL) + return 0.0f; + + const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner); + const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner); + const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner); + const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner); + if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out + return 0.0f; + + if (g.NavLayer != ImGuiNavLayer_Main) + NavRestoreLayer(ImGuiNavLayer_Main); + + if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY) + { + // Fallback manual-scroll when window has no navigable item + if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner)) + SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); + else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner)) + SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); + else if (home_pressed) + SetScrollY(window, 0.0f); + else if (end_pressed) + SetScrollY(window, window->ScrollMax.y); + } + else + { + ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; + const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight()); + float nav_scoring_rect_offset_y = 0.0f; + if (IsKeyPressed(ImGuiKey_PageUp, true)) + { + nav_scoring_rect_offset_y = -page_offset_y; + g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Up; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later + } + else if (IsKeyPressed(ImGuiKey_PageDown, true)) + { + nav_scoring_rect_offset_y = +page_offset_y; + g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Down; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later + } + else if (home_pressed) + { + // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y + // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result. + // Preserve current horizontal position if we have any. + nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f; + if (nav_rect_rel.IsInverted()) + nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; + g.NavMoveDir = ImGuiDir_Down; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY; + // FIXME-NAV: MoveClipDir left to _None, intentional? + } + else if (end_pressed) + { + nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y; + if (nav_rect_rel.IsInverted()) + nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; + g.NavMoveDir = ImGuiDir_Up; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY; + // FIXME-NAV: MoveClipDir left to _None, intentional? + } + return nav_scoring_rect_offset_y; + } + return 0.0f; +} + +static void ImGui::NavEndFrame() +{ + ImGuiContext& g = *GImGui; + + // Show Ctrl+Tab list window + if (g.NavWindowingTarget != NULL) + NavUpdateWindowingOverlay(); + + // Perform wrap-around in menus + // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly. + // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame. + if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0) + NavUpdateCreateWrappingRequest(); +} + +static void ImGui::NavUpdateCreateWrappingRequest() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.NavWindow; + + bool do_forward = false; + ImRect bb_rel = window->NavRectRel[g.NavLayer]; + ImGuiDir clip_dir = g.NavMoveDir; + + const ImGuiNavMoveFlags move_flags = g.NavMoveFlags; + //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + + // Menu layer does not maintain scrolling / content size (#9178) + ImVec2 wrap_size = (g.NavLayer == ImGuiNavLayer_Menu) ? window->Size : window->ContentSize + window->WindowPadding; + + if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = wrap_size.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row + clip_dir = ImGuiDir_Up; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row + clip_dir = ImGuiDir_Down; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = wrap_size.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column + clip_dir = ImGuiDir_Left; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column + clip_dir = ImGuiDir_Right; + } + do_forward = true; + } + if (!do_forward) + return; + window->NavRectRel[g.NavLayer] = bb_rel; + NavClearPreferredPosForAxis(ImGuiAxis_X); + NavClearPreferredPosForAxis(ImGuiAxis_Y); + NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags); +} + +// Can we focus this window with Ctrl+Tab (or PadMenu + PadFocusPrev/PadFocusNext) +// Note that NoNavFocus makes the window not reachable with Ctrl+Tab but it can still be focused with mouse or programmatically. +// If you want a window to never be focused, you may use the e.g. NoInputs flag. +bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) +{ + return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); +} + +static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) +{ + ImGuiContext& g = *GImGui; + for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir) + if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i])) + return g.WindowsFocusOrder[i]; + return NULL; +} + +static void NavUpdateWindowingTarget(int focus_change_dir) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindowingTarget); + if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) + return; + + const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget); + ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); + if (!window_target) + window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); + if (window_target) // Don't reset windowing target if there's a single window in the list + { + g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target; + g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f); + } + g.NavWindowingToggleLayer = false; +} + +// Apply focus and close overlay +static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window) +{ + // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ? + // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow() + ImGuiContext& g = *GImGui; + if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow) + { + ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL; + ClearActiveID(); + SetNavCursorVisibleAfterMove(); + ClosePopupsOverWindow(apply_focus_window, false); + FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild); + IM_ASSERT(g.NavWindow != NULL); + apply_focus_window = g.NavWindow; + if (apply_focus_window->NavLastIds[0] == 0) // FIXME: This is the equivalent of the 'if (g.NavId == 0) { NavInitWindow() }' in DockNodeUpdateTabBar(). + NavInitWindow(apply_focus_window, false); + + // If the window has ONLY a menu layer (no main layer), select it directly + // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame, + // so Ctrl+Tab where the keys are only held for 1 frame will be able to use correct layers mask since + // the target window as already been previewed once. + // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases, + // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask* + // won't be valid. + if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu)) + g.NavLayer = ImGuiNavLayer_Menu; + + // Request OS level focus + if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus) + g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport); + } + g.NavWindowingTarget = NULL; +} + +// Windowing management mode +// Keyboard: Ctrl+Tab (change focus/move/resize), Alt (toggle menu layer) +// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) +static void ImGui::NavUpdateWindowing() +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + ImGuiWindow* apply_focus_window = NULL; + bool apply_toggle_layer = false; + + ImGuiWindow* modal_window = GetTopMostPopupModal(); + bool allow_windowing = (modal_window == NULL); // FIXME: This prevent Ctrl+Tab from being usable with windows that are inside the Begin-stack of that modal. + if (!allow_windowing) + g.NavWindowingTarget = NULL; + + // Fade out + if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) + { + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f); + if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) + g.NavWindowingTargetAnim = NULL; + } + + // Start Ctrl+Tab or Square+L/R window selection + // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab) + const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing"); + const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); + const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); + const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id); + const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad; + const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard! + bool just_started_windowing_from_null_focus = false; + if (start_toggling_with_gamepad) + { + g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer + g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu; + g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad; + } + if (start_windowing_with_gamepad || start_windowing_with_keyboard) + if (ImGuiWindow* window = (g.NavWindow && IsWindowNavFocusable(g.NavWindow)) ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) + { + if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad) + g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location + g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; + g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f); + g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; + if (g.NavWindow == NULL) + just_started_windowing_from_null_focus = true; + + // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects. + if (keyboard_next_window || keyboard_prev_window) + SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id); + } + + // Gamepad update + if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad) + { + if (g.NavWindowingTarget != NULL) + { + // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise + // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. + g.NavWindowingTimer += io.DeltaTime; + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); + + // Select window to focus + const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1); + if (focus_change_dir != 0 && !just_started_windowing_from_null_focus) + { + NavUpdateWindowingTarget(focus_change_dir); + g.NavWindowingHighlightAlpha = 1.0f; + } + } + + // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) + if (!IsKeyDown(ImGuiKey_NavGamepadMenu)) + { + g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. + if (g.NavWindowingToggleLayer && g.NavWindow) + apply_toggle_layer = true; + else if (!g.NavWindowingToggleLayer) + apply_focus_window = g.NavWindowingTarget; + g.NavWindowingTarget = NULL; + g.NavWindowingToggleLayer = false; + } + } + + // Keyboard: Focus + if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) + { + // Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise + ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_; + IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows. + g.NavWindowingTimer += io.DeltaTime; + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f + if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus) + NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1); + else if ((io.KeyMods & shared_mods) != shared_mods) + apply_focus_window = g.NavWindowingTarget; + } + + // Keyboard: Press and Release Alt to toggle menu layer + const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt }; + bool windowing_toggle_layer_start = false; + if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + for (ImGuiKey windowing_toggle_key : windowing_toggle_keys) + if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner)) + { + windowing_toggle_layer_start = true; + g.NavWindowingToggleLayer = true; + g.NavWindowingToggleKey = windowing_toggle_key; + g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard; + break; + } + if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) + { + // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370) + // We cancel toggling nav layer when other modifiers are pressed. (See #4439) + // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). + // We cancel toggling nav layer if an owner has claimed the key. + if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper) + g.NavWindowingToggleLayer = false; + else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time) + g.NavWindowingToggleLayer = false; + else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false) + g.NavWindowingToggleLayer = false; + + // Apply layer toggle on Alt release + // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss. + if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer) + if (g.ActiveId == 0 || g.ActiveIdAllowOverlap) + if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev)) + apply_toggle_layer = true; + if (!IsKeyDown(g.NavWindowingToggleKey)) + g.NavWindowingToggleLayer = false; + } + + // Move window + if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) + { + ImVec2 nav_move_dir; + if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift) + nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow); + if (g.NavInputSource == ImGuiInputSource_Gamepad) + nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown); + if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f) + { + const float NAV_MOVE_SPEED = 800.0f; + const float move_step = NAV_MOVE_SPEED * io.DeltaTime * GetScale(); + g.NavWindowingAccumDeltaPos += nav_move_dir * move_step; + g.NavHighlightItemUnderNav = true; + ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos); + if (accum_floored.x != 0.0f || accum_floored.y != 0.0f) + { + ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree; + SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always); + g.NavWindowingAccumDeltaPos -= accum_floored; + } + } + } + + // Apply final focus + if (apply_focus_window) + NavUpdateWindowingApplyFocus(apply_focus_window); + + // Apply menu/layer toggle + if (apply_toggle_layer && g.NavWindow) + { + ClearActiveID(); + + // Move to parent menu if necessary + ImGuiWindow* new_nav_window = g.NavWindow; + while (new_nav_window->ParentWindow + && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0 + && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 + && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + new_nav_window = new_nav_window->ParentWindow; + if (new_nav_window != g.NavWindow) + { + ImGuiWindow* old_nav_window = g.NavWindow; + FocusWindow(new_nav_window); + new_nav_window->NavLastChildNavWindow = old_nav_window; + } + + // Toggle layer + const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main; + if (new_nav_layer != g.NavLayer) + { + // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) + const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL); + if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id) + g.NavWindow->NavLastIds[new_nav_layer] = 0; + NavRestoreLayer(new_nav_layer); + SetNavCursorVisibleAfterMove(); + } + } +} + +// Window has already passed the IsWindowNavFocusable() +static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) +{ + if (window->Flags & ImGuiWindowFlags_Popup) + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup); + if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar); + if (window->DockNodeAsHost) + return "(Dock node)"; // Not normally shown to user. + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled); +} + +// Overlay displayed when using Ctrl+Tab. Called by EndFrame(). +void ImGui::NavUpdateWindowingOverlay() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindowingTarget != NULL); + + if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) + return; + + const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport(); + SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); + Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + g.NavWindowingListWindow = g.CurrentWindow; + if (g.ContextName[0] != 0) + SeparatorText(g.ContextName); + for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) + { + ImGuiWindow* window = g.WindowsFocusOrder[n]; + IM_ASSERT(window != NULL); // Fix static analyzers + if (!IsWindowNavFocusable(window)) + continue; + const char* label = window->Name; + if (label == FindRenderedTextEnd(label)) + label = GetFallbackWindowNameForWindowingList(window); + Selectable(label, g.NavWindowingTarget == window); + } + End(); + PopStyleVar(); +} + +//----------------------------------------------------------------------------- +// [SECTION] DRAG AND DROP +//----------------------------------------------------------------------------- + +bool ImGui::IsDragDropActive() +{ + ImGuiContext& g = *GImGui; + return g.DragDropActive; +} + +void ImGui::ClearDragDrop() +{ + ImGuiContext& g = *GImGui; + if (g.DragDropActive) + IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n"); + g.DragDropActive = false; + g.DragDropPayload.Clear(); + g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None; + g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropAcceptFrameCount = -1; + + g.DragDropPayloadBufHeap.clear(); + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); +} + +bool ImGui::BeginTooltipHidden() +{ + ImGuiContext& g = *GImGui; + bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize); + SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow); + return ret; +} + +// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +// If the item has an identifier: +// - This assume/require the item to be activated (typically via ButtonBehavior). +// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button. +// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag. +// If the item has no identifier: +// - Currently always assume left mouse button. +bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button, + // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic). + ImGuiMouseButton mouse_button = ImGuiMouseButton_Left; + + bool source_drag_active = false; + ImGuiID source_id = 0; + ImGuiID source_parent_id = 0; + if ((flags & ImGuiDragDropFlags_SourceExtern) == 0) + { + source_id = g.LastItemData.ID; + if (source_id != 0) + { + // Common path: items with ID + if (g.ActiveId != source_id) + return false; + if (g.ActiveIdMouseButton != -1) + mouse_button = g.ActiveIdMouseButton; + if (g.IO.MouseDown[mouse_button] == false || window->SkipItems) + return false; + g.ActiveIdAllowOverlap = false; + } + else + { + // Uncommon path: items without ID + if (g.IO.MouseDown[mouse_button] == false || window->SkipItems) + return false; + if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window)) + return false; + + // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag. + if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) + { + IM_ASSERT(0); + return false; + } + + // Magic fallback to handle items with no assigned ID, e.g. Text(), Image() + // We build a throwaway ID based on current ID stack + relative AABB of items in window. + // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + // Rely on keeping other window->LastItemXXX fields intact. + source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect); + KeepAliveID(source_id); + bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags); + if (is_hovered && g.IO.MouseClicked[mouse_button]) + { + SetActiveID(source_id, window); + FocusWindow(window); + } + if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. + g.ActiveIdAllowOverlap = is_hovered; + } + if (g.ActiveId != source_id) + return false; + source_parent_id = window->IDStack.back(); + source_drag_active = IsMouseDragging(mouse_button); + + // Disable navigation and key inputs while dragging + cancel existing request if any + SetActiveIdUsingAllKeyboardKeys(); + } + else + { + // When ImGuiDragDropFlags_SourceExtern is set: + window = NULL; + source_id = ImHashStr("#SourceExtern"); + source_drag_active = true; + mouse_button = g.IO.MouseDown[0] ? 0 : -1; + KeepAliveID(source_id); + SetActiveID(source_id, NULL); + } + + IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() + if (!source_drag_active) + return false; + + // Activate drag and drop + if (!g.DragDropActive) + { + IM_ASSERT(source_id != 0); + ClearDragDrop(); + IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n", + source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : ""); + ImGuiPayload& payload = g.DragDropPayload; + payload.SourceId = source_id; + payload.SourceParentId = source_parent_id; + g.DragDropActive = true; + g.DragDropSourceFlags = flags; + g.DragDropMouseButton = mouse_button; + if (payload.SourceId == g.ActiveId) + g.ActiveIdNoClearOnFocusLoss = true; + } + g.DragDropSourceFrameCount = g.FrameCount; + g.DragDropWithinSource = true; + + if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + { + // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. + bool ret; + if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlagsPrev & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) + ret = BeginTooltipHidden(); + else + ret = BeginTooltip(); + IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame(). + IM_UNUSED(ret); + } + + if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) + g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; + + return true; +} + +void ImGui::EndDragDropSource() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?"); + + if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + EndTooltip(); + + // Discard the drag if have not called SetDragDropPayload() + if (g.DragDropPayload.DataFrameCount == -1) + ClearDragDrop(); + g.DragDropWithinSource = false; +} + +// Use 'cond' to choose to submit payload on drag start or every frame +bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + ImGuiPayload& payload = g.DragDropPayload; + if (cond == 0) + cond = ImGuiCond_Always; + + IM_ASSERT(type != NULL); + IM_ASSERT(ImStrlen(type) < IM_COUNTOF(payload.DataType) && "Payload type can be at most 32 characters long"); + IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); + IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); + IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() + + if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) + { + // Copy payload + ImStrncpy(payload.DataType, type, IM_COUNTOF(payload.DataType)); + g.DragDropPayloadBufHeap.resize(0); + if (data_size > sizeof(g.DragDropPayloadBufLocal)) + { + // Store in heap + g.DragDropPayloadBufHeap.resize((int)data_size); + payload.Data = g.DragDropPayloadBufHeap.Data; + memcpy(payload.Data, data, data_size); + } + else if (data_size > 0) + { + // Store locally + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); + payload.Data = g.DragDropPayloadBufLocal; + memcpy(payload.Data, data, data_size); + } + else + { + payload.Data = NULL; + } + payload.DataSize = (int)data_size; + } + payload.DataFrameCount = g.FrameCount; + + // Return whether the payload has been accepted + return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); +} + +bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow* window = g.CurrentWindow; + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree) + return false; + IM_ASSERT(id != 0); + if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) + return false; + if (window->SkipItems) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() + g.DragDropTargetRect = bb; + g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case? + g.DragDropTargetId = id; + g.DragDropTargetFullViewport = 0; + g.DragDropWithinTarget = true; + return true; +} + +// Typical usage would be: +// if (!ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) +// if (ImGui::BeginDragDropTargetViewport(ImGui::GetMainViewport(), NULL)) +// But we are leaving the hover test to the caller for maximum flexibility. +bool ImGui::BeginDragDropTargetViewport(ImGuiViewport* viewport, const ImRect* p_bb) +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImRect bb = p_bb ? *p_bb : ((ImGuiViewportP*)viewport)->GetWorkRect(); + ImGuiID id = viewport->ID; + if (g.MouseViewport != viewport || !IsMouseHoveringRect(bb.Min, bb.Max, false) || (id == g.DragDropPayload.SourceId)) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() + g.DragDropTargetRect = bb; + g.DragDropTargetClipRect = bb; + g.DragDropTargetId = id; + g.DragDropTargetFullViewport = id; + g.DragDropWithinTarget = true; + return true; +} + +// We don't use BeginDragDropTargetCustom() and duplicate its code because: +// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) +bool ImGui::BeginDragDropTarget() +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow* window = g.CurrentWindow; + if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)) + return false; + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems) + return false; + + const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect; + ImGuiID id = g.LastItemData.ID; + if (id == 0) + { + id = window->GetIDFromRectangle(display_rect); + KeepAliveID(id); + } + if (g.DragDropPayload.SourceId == id) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() + g.DragDropTargetRect = display_rect; + g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect; + g.DragDropTargetId = id; + g.DragDropWithinTarget = true; + return true; +} + +bool ImGui::IsDragDropPayloadBeingAccepted() +{ + ImGuiContext& g = *GImGui; + return g.DragDropActive && g.DragDropAcceptIdPrev != 0; +} + +const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiPayload& payload = g.DragDropPayload; + IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? + if (type != NULL && !payload.IsDataType(type)) + return NULL; + + // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! + const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); + ImRect r = g.DragDropTargetRect; + float r_surface = r.GetWidth() * r.GetHeight(); + if (r_surface > g.DragDropAcceptIdCurrRectSurface) + return NULL; + + g.DragDropAcceptFlagsCurr = flags; + g.DragDropAcceptIdCurr = g.DragDropTargetId; + g.DragDropAcceptIdCurrRectSurface = r_surface; + //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId); + + // Render default drop visuals + payload.Preview = was_accepted_previously; + flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame) + const bool draw_target_rect = payload.Preview && !(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); + if (draw_target_rect && g.DragDropTargetFullViewport != 0) + { + ImGuiViewport* viewport = FindViewportByID(g.DragDropTargetFullViewport); + IM_ASSERT(viewport != NULL); + ImRect bb = g.DragDropTargetRect; + bb.Expand(-3.5f); + RenderDragDropTargetRectEx(GetForegroundDrawList(viewport), bb); + } + else if (draw_target_rect) + { + RenderDragDropTargetRectForItem(r); + } + + g.DragDropAcceptFrameCount = g.FrameCount; + if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1) + payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount); + else + payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() + if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) + return NULL; + + if (payload.Delivery) + IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId); + return &payload; +} + +// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target. +void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImRect bb_display = bb; + bb_display.ClipWith(g.DragDropTargetClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible. + bb_display.Expand(g.Style.DragDropTargetPadding); + bool push_clip_rect = !window->ClipRect.Contains(bb_display); + if (push_clip_rect) + window->DrawList->PushClipRectFullScreen(); + RenderDragDropTargetRectEx(window->DrawList, bb_display); + if (push_clip_rect) + window->DrawList->PopClipRect(); +} + +void ImGui::RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb) +{ + ImGuiContext& g = *GImGui; + draw_list->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTargetBg), g.Style.DragDropTargetRounding, 0); + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), g.Style.DragDropTargetRounding, 0, g.Style.DragDropTargetBorderSize); +} + +const ImGuiPayload* ImGui::GetDragDropPayload() +{ + ImGuiContext& g = *GImGui; + return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL; +} + +void ImGui::EndDragDropTarget() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinTarget); + g.DragDropWithinTarget = false; + + // Clear drag and drop state payload right after delivery + if (g.DragDropPayload.Delivery) + ClearDragDrop(); +} + +//----------------------------------------------------------------------------- +// [SECTION] LOGGING/CAPTURING +//----------------------------------------------------------------------------- +// All text output from the interface can be captured into tty/file/clipboard. +// By default, tree nodes are automatically opened during logging. +//----------------------------------------------------------------------------- + +// Pass text data straight to log (without being displayed) +static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args) +{ + if (g.LogFile) + { + g.LogBuffer.Buf.resize(0); + g.LogBuffer.appendfv(fmt, args); + ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile); + } + else + { + g.LogBuffer.appendfv(fmt, args); + } +} + +void ImGui::LogText(const char* fmt, ...) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + LogTextV(g, fmt, args); + va_end(args); +} + +void ImGui::LogTextV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogTextV(g, fmt, args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +// FIXME: This code is a little complicated perhaps, considering simplifying the whole system. +void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const char* prefix = g.LogNextPrefix; + const char* suffix = g.LogNextSuffix; + g.LogNextPrefix = g.LogNextSuffix = NULL; + + if (!text_end) + text_end = FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + ImMax(g.Style.FramePadding.y, g.Style.ItemSpacing.y) + 1); + if (ref_pos) + g.LogLinePosY = ref_pos->y; + if (log_new_line) + { + LogText(IM_NEWLINE); + g.LogLineFirstItem = true; + } + + if (prefix) + LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here. + + // Re-adjust padding if we have popped out of our starting depth + if (g.LogDepthRef > window->DC.TreeDepth) + g.LogDepthRef = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); + + const char* text_remaining = text; + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. + // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. + const char* line_start = text_remaining; + const char* line_end = ImStreolRange(line_start, text_end); + const bool is_last_line = (line_end == text_end); + if (line_start != line_end || !is_last_line) + { + const int line_length = (int)(line_end - line_start); + const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1; + LogText("%*s%.*s", indentation, "", line_length, line_start); + g.LogLineFirstItem = false; + if (*line_end == '\n') + { + LogText(IM_NEWLINE); + g.LogLineFirstItem = true; + } + } + if (is_last_line) + break; + text_remaining = line_end + 1; + } + + if (suffix) + LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix)); +} + +// Start logging/capturing text output +void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(g.LogEnabled == false); + IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty()); + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used + + g.LogEnabled = g.ItemUnclipByLog = true; + g.LogFlags = flags; + g.LogWindow = window; + g.LogNextPrefix = g.LogNextSuffix = NULL; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + g.LogLinePosY = FLT_MAX; + g.LogLineFirstItem = true; +} + +// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText) +void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix) +{ + ImGuiContext& g = *GImGui; + g.LogNextPrefix = prefix; + g.LogNextSuffix = suffix; +} + +void ImGui::LogToTTY(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + IM_UNUSED(auto_open_depth); +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth); + g.LogFile = stdout; +#endif +} + +// Start logging/capturing text output to given file +void ImGui::LogToFile(int auto_open_depth, const char* filename) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + + // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still + // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. + // By opening the file in binary mode "ab" we have consistent output everywhere. + if (!filename) + filename = g.IO.LogFilename; + if (!filename || !filename[0]) + return; + ImFileHandle f = ImFileOpen(filename, "ab"); + if (!f) + { + IM_ASSERT(0); + return; + } + + LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth); + g.LogFile = f; +} + +// Start logging/capturing text output to clipboard +void ImGui::LogToClipboard(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth); +} + +void ImGui::LogToBuffer(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth); +} + +void ImGui::LogFinish() +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + switch (g.LogFlags & ImGuiLogFlags_OutputMask_) + { + case ImGuiLogFlags_OutputTTY: +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + fflush(g.LogFile); +#endif + break; + case ImGuiLogFlags_OutputFile: + ImFileClose(g.LogFile); + break; + case ImGuiLogFlags_OutputBuffer: + break; + case ImGuiLogFlags_OutputClipboard: + if (!g.LogBuffer.empty()) + SetClipboardText(g.LogBuffer.begin()); + break; + default: + IM_ASSERT(0); + break; + } + + g.LogEnabled = g.ItemUnclipByLog = false; + g.LogFlags = ImGuiLogFlags_None; + g.LogFile = NULL; + g.LogBuffer.clear(); +} + +// Helper to display logging buttons +// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) +void ImGui::LogButtons() +{ + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + const bool log_to_tty = Button("Log To TTY"); SameLine(); +#else + const bool log_to_tty = false; +#endif + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemFlag(ImGuiItemFlags_NoTabStop, true); + SetNextItemWidth(CalcTextSize("999").x); + SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); + PopItemFlag(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(); + if (log_to_file) + LogToFile(); + if (log_to_clipboard) + LogToClipboard(); +} + +//----------------------------------------------------------------------------- +// [SECTION] SETTINGS +//----------------------------------------------------------------------------- +// - UpdateSettings() [Internal] +// - MarkIniSettingsDirty() [Internal] +// - FindSettingsHandler() [Internal] +// - ClearIniSettings() [Internal] +// - LoadIniSettingsFromDisk() +// - LoadIniSettingsFromMemory() +// - SaveIniSettingsToDisk() +// - SaveIniSettingsToMemory() +//----------------------------------------------------------------------------- +// - CreateNewWindowSettings() [Internal] +// - FindWindowSettingsByID() [Internal] +// - FindWindowSettingsByWindow() [Internal] +// - ClearWindowSettings() [Internal] +// - WindowSettingsHandler_***() [Internal] +//----------------------------------------------------------------------------- + +// Called by NewFrame() +void ImGui::UpdateSettings() +{ + // Load settings on first frame (if not explicitly loaded manually before) + ImGuiContext& g = *GImGui; + if (!g.SettingsLoaded) + { + IM_ASSERT(g.SettingsWindows.empty()); + if (g.IO.IniFilename) + LoadIniSettingsFromDisk(g.IO.IniFilename); + g.SettingsLoaded = true; + } + + // Save settings (with a delay after the last modification, so we don't spam disk too much) + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + { + if (g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + else + g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. + g.SettingsDirtyTimer = 0.0f; + } + } +} + +void ImGui::MarkIniSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL); + g.SettingsHandlers.push_back(*handler); +} + +void ImGui::RemoveSettingsHandler(const char* type_name) +{ + ImGuiContext& g = *GImGui; + if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name)) + g.SettingsHandlers.erase(handler); +} + +ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) +{ + ImGuiContext& g = *GImGui; + const ImGuiID type_hash = ImHashStr(type_name); + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + if (handler.TypeHash == type_hash) + return &handler; + return NULL; +} + +// Clear all settings (windows, tables, docking etc.) +void ImGui::ClearIniSettings() +{ + ImGuiContext& g = *GImGui; + g.SettingsIniData.clear(); + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + if (handler.ClearAllFn != NULL) + handler.ClearAllFn(&g, &handler); +} + +void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) +{ + size_t file_data_size = 0; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + if (!file_data) + return; + if (file_data_size > 0) + LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + IM_FREE(file_data); +} + +// Zero-tolerance, no error reporting, cheap .ini parsing +// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty! +void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); + //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); + + // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). + // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. + if (ini_size == 0) + ini_size = ImStrlen(ini_data); + g.SettingsIniData.Buf.resize((int)ini_size + 1); + char* const buf = g.SettingsIniData.Buf.Data; + char* const buf_end = buf + ini_size; + memcpy(buf, ini_data, ini_size); + buf_end[0] = 0; + + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + if (handler.ReadInitFn != NULL) + handler.ReadInitFn(&g, &handler); + + void* entry_data = NULL; + ImGuiSettingsHandler* entry_handler = NULL; + + char* line_end = NULL; + for (char* line = buf; line < buf_end; line = line_end + 1) + { + // Skip new lines markers, then find end of the line + while (*line == '\n' || *line == '\r') + line++; + line_end = line; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + line_end[0] = 0; + if (line[0] == ';') + continue; + if (line[0] == '[' && line_end > line && line_end[-1] == ']') + { + // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. + line_end[-1] = 0; + const char* name_end = line_end - 1; + const char* type_start = line + 1; + char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']'); + const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + if (!type_end || !name_start) + continue; + *type_end = 0; // Overwrite first ']' + name_start++; // Skip second '[' + entry_handler = FindSettingsHandler(type_start); + entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; + } + else if (entry_handler != NULL && entry_data != NULL) + { + // Let type handler parse the line + entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); + } + } + g.SettingsLoaded = true; + + // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) + memcpy(buf, ini_data, ini_size); + + // Call post-read handlers + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + if (handler.ApplyAllFn != NULL) + handler.ApplyAllFn(&g, &handler); +} + +void ImGui::SaveIniSettingsToDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + size_t ini_data_size = 0; + const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); + ImFileHandle f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + ImFileWrite(ini_data, sizeof(char), ini_data_size, f); + ImFileClose(f); +} + +// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer +const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + g.SettingsIniData.Buf.resize(0); + g.SettingsIniData.Buf.push_back(0); + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + handler.WriteAllFn(&g, &handler, &g.SettingsIniData); + if (out_size) + *out_size = (size_t)g.SettingsIniData.size(); + return g.SettingsIniData.c_str(); +} + +ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + + // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. + if (g.IO.ConfigDebugIniSettings == false) + name = ImHashSkipUncontributingPrefix(name); + const size_t name_len = ImStrlen(name); + + // Allocate chunk + const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1; + ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size); + IM_PLACEMENT_NEW(settings) ImGuiWindowSettings(); + settings->ID = ImHashStr(name, name_len); + memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator + + return settings; +} + +// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names. +// This is called once per window .ini entry + once per newly instantiated window. +ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->ID == id && !settings->WantDelete) + return settings; + return NULL; +} + +// This is faster if you are holding on a Window already as we don't need to perform a search. +ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (window->SettingsOffset != -1) + return g.SettingsWindows.ptr_from_offset(window->SettingsOffset); + return FindWindowSettingsByID(window->ID); +} + +// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more. +void ImGui::ClearWindowSettings(const char* name) +{ + //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = FindWindowByName(name); + if (window != NULL) + { + window->Flags |= ImGuiWindowFlags_NoSavedSettings; + InitOrLoadWindowSettings(window, NULL); + if (window->DockId != 0) + DockContextProcessUndockWindow(&g, window, true); + } + if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name))) + settings->WantDelete = true; +} + +static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindow* window : g.Windows) + window->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiID id = ImHashStr(name); + ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id); + if (settings) + *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry + else + settings = ImGui::CreateNewWindowSettings(name); + settings->ID = id; + settings->WantApply = true; + return (void*)settings; +} + +static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; + int x, y; + int i; + ImU32 u1; + if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } + else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } + else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); } + else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } + else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } + else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } +} + +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + +static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + // Gather data from windows that were active during this session + // (if a window wasn't opened in this session we preserve its settings) + ImGuiContext& g = *ctx; + for (ImGuiWindow* window : g.Windows) + { + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + + ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window); + if (!settings) + { + settings = ImGui::CreateNewWindowSettings(window->Name); + window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); + } + IM_ASSERT(settings->ID == window->ID); + settings->Pos = ImVec2ih(window->Pos - window->ViewportPos); + settings->Size = ImVec2ih(window->SizeFull); + settings->ViewportId = window->ViewportId; + settings->ViewportPos = ImVec2ih(window->ViewportPos); + IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); + settings->DockId = window->DockId; + settings->ClassId = window->WindowClass.ClassId; + settings->DockOrder = window->DockOrder; + settings->Collapsed = window->Collapsed; + settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set. + settings->WantDelete = false; + } + + // Write to text buffer + buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + { + if (settings->WantDelete) + continue; + const char* settings_name = settings->GetName(); + buf->appendf("[%s][%s]\n", handler->TypeName, settings_name); + if (settings->IsChild) + { + buf->appendf("IsChild=1\n"); + buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); + } + else + { + if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + { + buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y); + buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); + } + if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); + if (settings->Size.x != 0 || settings->Size.y != 0) + buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); + buf->appendf("Collapsed=%d\n", settings->Collapsed); + if (settings->DockId != 0) + { + //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier. + if (settings->DockOrder == -1) + buf->appendf("DockId=0x%08X\n", settings->DockId); + else + buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); + if (settings->ClassId != 0) + buf->appendf("ClassId=0x%08X\n", settings->ClassId); + } + } + buf->append("\n"); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] LOCALIZATION +//----------------------------------------------------------------------------- + +void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count) +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < count; n++) + g.LocalizationTable[entries[n].Key] = entries[n].Text; +} + +//----------------------------------------------------------------------------- +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +//----------------------------------------------------------------------------- +// - GetMainViewport() +// - FindViewportByID() +// - FindViewportByPlatformHandle() +// - SetCurrentViewport() [Internal] +// - SetWindowViewport() [Internal] +// - GetWindowAlwaysWantOwnViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewports() [Internal] +// - TranslateWindowsInViewport() [Internal] +// - ScaleWindowsInViewport() [Internal] +// - FindHoveredViewportFromPlatformWindowStack() [Internal] +// - UpdateViewportsNewFrame() [Internal] +// - UpdateViewportsEndFrame() [Internal] +// - AddUpdateViewport() [Internal] +// - WindowSelectViewport() [Internal] +// - WindowSyncOwnedViewport() [Internal] +// - UpdatePlatformWindows() +// - RenderPlatformWindowsDefault() +// - FindPlatformMonitorForPos() [Internal] +// - FindPlatformMonitorForRect() [Internal] +// - UpdateViewportPlatformMonitor() [Internal] +// - DestroyPlatformWindow() [Internal] +// - DestroyPlatformWindows() +//----------------------------------------------------------------------------- + +void ImGuiPlatformIO::ClearPlatformHandlers() +{ + Platform_GetClipboardTextFn = NULL; + Platform_SetClipboardTextFn = NULL; + Platform_OpenInShellFn = NULL; + Platform_SetImeDataFn = NULL; + Platform_ClipboardUserData = Platform_OpenInShellUserData = Platform_ImeUserData = NULL; + Platform_CreateWindow = Platform_DestroyWindow = Platform_ShowWindow = NULL; + Platform_SetWindowPos = Platform_SetWindowSize = NULL; + Platform_GetWindowPos = Platform_GetWindowSize = Platform_GetWindowFramebufferScale = NULL; + Platform_SetWindowFocus = NULL; + Platform_GetWindowFocus = Platform_GetWindowMinimized = NULL; + Platform_SetWindowTitle = NULL; + Platform_SetWindowAlpha = NULL; + Platform_UpdateWindow = NULL; + Platform_RenderWindow = Platform_SwapBuffers = NULL; + Platform_GetWindowDpiScale = NULL; + Platform_OnChangedViewport = NULL; + Platform_GetWindowWorkAreaInsets = NULL; + Platform_CreateVkSurface = NULL; +} + +void ImGuiPlatformIO::ClearRendererHandlers() +{ + Renderer_TextureMaxWidth = Renderer_TextureMaxHeight = 0; + Renderer_RenderState = NULL; + Renderer_CreateWindow = Renderer_DestroyWindow = NULL; + Renderer_SetWindowSize = NULL; + Renderer_RenderWindow = Renderer_SwapBuffers = NULL; +} + +ImGuiViewport* ImGui::GetMainViewport() +{ + ImGuiContext& g = *GImGui; + return g.Viewports[0]; +} + +// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) +ImGuiViewport* ImGui::FindViewportByID(ImGuiID viewport_id) +{ + ImGuiContext& g = *GImGui; + for (ImGuiViewportP* viewport : g.Viewports) + if (viewport->ID == viewport_id) + return viewport; + return NULL; +} + +ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle) +{ + ImGuiContext& g = *GImGui; + for (ImGuiViewportP* viewport : g.Viewports) + if (viewport->PlatformHandle == platform_handle) + return viewport; + return NULL; +} + +void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + (void)current_window; + + if (viewport) + viewport->LastFrameActive = g.FrameCount; + if (g.CurrentViewport == viewport) + return; + g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f; + g.CurrentViewport = viewport; + IM_ASSERT(g.CurrentDpiScale > 0.0f && g.CurrentDpiScale < 99.0f); // Typical correct values would be between 1.0f and 4.0f + //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); + if (g.IO.ConfigDpiScaleFonts) + g.Style.FontScaleDpi = g.CurrentDpiScale; + + // Notify platform layer of viewport changes + // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI + if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) + g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); +} + +void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) +{ + // Abandon viewport + if (window->ViewportOwned && window->Viewport->Window == window) + window->Viewport->Size = ImVec2(0.0f, 0.0f); + + window->Viewport = viewport; + window->ViewportId = viewport->ID; + window->ViewportOwned = (viewport->Window == window); +} + +static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) +{ + // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. + ImGuiContext& g = *GImGui; + if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + if (!window->DockIsActive) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0) + if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0) + return true; + return false; +} + + +// Heuristic, see #8948: depends on how backends handle OS-level parenting. +// Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). +static bool IsViewportAbove(ImGuiViewportP* potential_above, ImGuiViewportP* potential_below) +{ + // If ImGuiBackendFlags_HasParentViewport if set, ->ParentViewport chain should be accurate. + ImGuiContext& g = *GImGui; + if (g.IO.BackendFlags & ImGuiBackendFlags_HasParentViewport) + { + for (ImGuiViewport* v = potential_above; v != NULL && v->ParentViewport; v = v->ParentViewport) + if (v->ParentViewport == potential_below) + return true; + } + else + { + if (potential_above->ParentViewport == potential_below) + return true; + } + + if (potential_above->LastFocusedStampCount > potential_below->LastFocusedStampCount) + return true; + return false; +} + +static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport_dst) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(window == window->RootWindowDockTree); + ImGuiViewportP* viewport_src = window->Viewport; // Current viewport + if (viewport_src == viewport_dst) + return false; + if ((viewport_dst->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0) + return false; + if ((viewport_dst->Flags & ImGuiViewportFlags_IsMinimized) != 0) + return false; + if (!viewport_dst->GetMainRect().Contains(window->Rect())) + return false; + if (GetWindowAlwaysWantOwnViewport(window)) + return false; + + for (ImGuiViewportP* viewport_obstructing : g.Viewports) + { + if (viewport_obstructing == viewport_src || viewport_obstructing == viewport_dst) + continue; + if (viewport_obstructing->GetMainRect().Overlaps(window->Rect())) + if (IsViewportAbove(viewport_obstructing, viewport_dst)) + if (viewport_src == NULL || IsViewportAbove(viewport_src, viewport_obstructing)) + return false; // viewport_obstructing is between viewport_src and viewport_dst -> Cannot merge. + } + + // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' merge into Viewport 0X%08X\n", window->Name, viewport_dst->ID); + if (window->ViewportOwned) + for (int n = 0; n < g.Windows.Size; n++) + if (g.Windows[n]->Viewport == viewport_src) + SetWindowViewport(g.Windows[n], viewport_dst); + SetWindowViewport(window, viewport_dst); + if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayFront(window); + + return true; +} + +// FIXME: handle 0 to N host viewports +static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); +} + +// Translate Dear ImGui windows when a Host Viewport has been moved +// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) +void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size) +{ + ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID); + IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); + + // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently + // translate imgui windows from OS-window-local to absolute coordinates or vice-versa. + // 2) If it's not going to fit into the new size, keep it at same absolute position. + // One problem with this is that most Win32 applications doesn't update their render while dragging, + // and so the window will appear to teleport when releasing the mouse. + const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); + ImRect test_still_fit_rect(old_pos, old_pos + old_size); + ImVec2 delta_pos = new_pos - old_pos; + for (ImGuiWindow* window : g.Windows) // FIXME-OPT + if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect())))) + TranslateWindow(window, delta_pos); +} + +// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) +void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) +{ + ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID); + if (viewport->Window) + { + ScaleWindow(viewport->Window, scale); + } + else + { + for (ImGuiWindow* window : g.Windows) + if (window->Viewport == viewport) + ScaleWindow(window, scale); + } +} + +// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. +// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. +// B) It requires Platform_GetWindowFocus to be implemented by backend. +ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* best_candidate = NULL; + for (ImGuiViewportP* viewport : g.Viewports) + if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos)) + if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount) + best_candidate = viewport; + return best_candidate; +} + +// Update viewports and monitor infos +// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. +static void ImGui::UpdateViewportsNewFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); + + // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) + // Update Focused status + const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0; + if (viewports_enabled) + { + ImGuiViewportP* focused_viewport = NULL; + for (ImGuiViewportP* viewport : g.Viewports) + { + const bool platform_funcs_available = viewport->PlatformWindowCreated; + if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) + { + bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); + if (is_minimized) + viewport->Flags |= ImGuiViewportFlags_IsMinimized; + else + viewport->Flags &= ~ImGuiViewportFlags_IsMinimized; + } + + // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport. + // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored. + if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available) + { + bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport); + if (is_focused) + viewport->Flags |= ImGuiViewportFlags_IsFocused; + else + viewport->Flags &= ~ImGuiViewportFlags_IsFocused; + if (is_focused) + focused_viewport = viewport; + } + } + + // Focused viewport has changed? + if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID) + { + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X '%s', attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID, focused_viewport->Window ? focused_viewport->Window->Name : "n/a"); + const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId); + const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false); + + // Store a tag so we can infer z-order easily from all our windows + // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag + // will keep the front most stamp instead of losing it back to their parent viewport. + if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount) + focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount; + g.PlatformLastFocusedViewportId = focused_viewport->ID; + + // Focus associated dear imgui window + // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299) + // - if focus didn't happen because we destroyed another window (#6462) + // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well. + const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed; + if (apply_imgui_focus_on_focused_viewport && g.IO.ConfigViewportsPlatformFocusSetsImGuiFocus) + { + focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus. + ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild; + if (focused_viewport->Window != NULL) + FocusWindow(focused_viewport->Window, focus_request_flags); + else if (focused_viewport->LastFocusedHadNavWindow) + FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport + else + FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused + } + } + if (focused_viewport) + focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); + } + + // Create/update main viewport with current platform position. + // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent. + ImGuiViewportP* main_viewport = g.Viewports[0]; + IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); + IM_ASSERT(main_viewport->Window == NULL); + ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f); + ImVec2 main_viewport_size = g.IO.DisplaySize; + ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale; + if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized)) + { + main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) + main_viewport_size = main_viewport->Size; + main_viewport_framebuffer_scale = main_viewport->FramebufferScale; + } + AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows); + + g.CurrentDpiScale = 0.0f; + g.CurrentViewport = NULL; + g.MouseViewport = NULL; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP* viewport = g.Viewports[n]; + viewport->Idx = n; + + // Erase unused viewports + if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) + { + DestroyViewport(viewport); + n--; + continue; + } + + const bool platform_funcs_available = viewport->PlatformWindowCreated; + if (viewports_enabled) + { + // Update Position and Size (from Platform Window to ImGui) if requested. + // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. + if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available) + { + // Viewport->WorkPos and WorkSize will be updated below + if (viewport->PlatformRequestMove) + viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); + if (viewport->PlatformRequestResize) + viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); + if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL) + viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport); + } + } + + // Update/copy monitor info + UpdateViewportPlatformMonitor(viewport); + + // Lock down space taken by menu bars and status bars + query initial insets from backend + // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc. + viewport->WorkInsetMin = viewport->BuildWorkInsetMin; + viewport->WorkInsetMax = viewport->BuildWorkInsetMax; + viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f); + if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL && platform_funcs_available) + { + ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport); + IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f); + viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y); + viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w); + } + viewport->UpdateWorkRect(); + + // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. + viewport->Alpha = 1.0f; + + // Translate Dear ImGui windows when a Host Viewport has been moved + // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) + const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos; + if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f)) + TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos, viewport->LastSize, viewport->Size); + + // Update DPI scale + float new_dpi_scale; + if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) + new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); + else if (viewport->PlatformMonitor != -1) + new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; + else + new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; + IM_ASSERT(new_dpi_scale > 0.0f && new_dpi_scale < 99.0f); // Typical correct values would be between 1.0f and 4.0f + if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) + { + float scale_factor = new_dpi_scale / viewport->DpiScale; + if (g.IO.ConfigDpiScaleViewports) + ScaleWindowsInViewport(viewport, scale_factor); + //if (viewport == GetMainViewport()) + // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); + + // Scale our window moving pivot so that the window will rescale roughly around the mouse position. + // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. + // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) + //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) + // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor); + } + viewport->DpiScale = new_dpi_scale; + } + + // Update fallback monitor + g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + if (g.PlatformIO.Monitors.Size == 0) + { + ImGuiPlatformMonitor* monitor = &g.FallbackMonitor; + monitor->MainPos = main_viewport->Pos; + monitor->MainSize = main_viewport->Size; + monitor->WorkPos = main_viewport->WorkPos; + monitor->WorkSize = main_viewport->WorkSize; + monitor->DpiScale = main_viewport->DpiScale; + g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos); + g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize); + } + else + { + g.FallbackMonitor = g.PlatformIO.Monitors[0]; + } + for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) + { + g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos); + g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize); + } + + if (!viewports_enabled) + { + g.MouseViewport = main_viewport; + return; + } + + // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. + // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. + ImGuiViewportP* viewport_hovered = NULL; + if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) + { + viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; + if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback. + } + else + { + // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: + // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. + // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order. + // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); + } + if (viewport_hovered != NULL) + g.MouseLastHoveredViewport = viewport_hovered; + else if (g.MouseLastHoveredViewport == NULL) + g.MouseLastHoveredViewport = g.Viewports[0]; + + // Update mouse reference viewport + // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) + // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details) + if (g.MovingWindow && g.MovingWindow->Viewport) + g.MouseViewport = g.MovingWindow->Viewport; + else + g.MouseViewport = g.MouseLastHoveredViewport; + + // When dragging something, always refer to the last hovered viewport. + // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) + // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) + // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. + // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that. + const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; + if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) + viewport_hovered = g.MouseLastHoveredViewport; + if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) + if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + g.MouseViewport = viewport_hovered; + + IM_ASSERT(g.MouseViewport != NULL); +} + +// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) +static void ImGui::UpdateViewportsEndFrame() +{ + ImGuiContext& g = *GImGui; + g.PlatformIO.Viewports.resize(0); + for (int i = 0; i < g.Viewports.Size; i++) + { + ImGuiViewportP* viewport = g.Viewports[i]; + viewport->LastPos = viewport->Pos; + viewport->LastSize = viewport->Size; + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) + if (i > 0) // Always include main viewport in the list + continue; + if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) + continue; + if (i > 0) + IM_ASSERT(viewport->Window != NULL); + g.PlatformIO.Viewports.push_back(viewport); + } + g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called +} + +// FIXME: We should ideally refactor the system to call this every frame (we currently don't) +ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(id != 0); + + flags |= ImGuiViewportFlags_IsPlatformWindow; + if (window != NULL) + { + const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false; + if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window) + flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; + if (!window_can_use_inputs) + flags |= ImGuiViewportFlags_NoInputs; + if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) + flags |= ImGuiViewportFlags_NoFocusOnAppearing; + } + + ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id); + if (viewport) + { + // Always update for main viewport as we are already pulling correct platform pos/size (see #4900) + ImVec2 prev_pos = viewport->Pos; + ImVec2 prev_size = viewport->Size; + if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) + viewport->Pos = pos; + if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) + viewport->Size = size; + viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags + if (prev_pos != viewport->Pos || prev_size != viewport->Size) + UpdateViewportPlatformMonitor(viewport); + } + else + { + // New viewport + viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = id; + viewport->Idx = g.Viewports.Size; + viewport->Pos = viewport->LastPos = pos; + viewport->Size = viewport->LastSize = size; + viewport->Flags = flags; + UpdateViewportPlatformMonitor(viewport); + g.Viewports.push_back(viewport); + g.ViewportCreatedCount++; + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : ""); + + // We assume the window becomes front-most (even when ImGuiViewportFlags_NoFocusOnAppearing is used). + // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. + viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount; + + // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. + // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame + g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x); + g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y); + g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); + g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); + + // Store initial DpiScale before the OS platform window creation, based on expected monitor data. + // This is so we can select an appropriate font size on the first frame of our window lifetime + viewport->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale; + } + + viewport->Window = window; + viewport->LastFrameActive = g.FrameCount; + viewport->UpdateWorkRect(); + IM_ASSERT(window == NULL || viewport->ID == window->ID); + + if (window != NULL) + window->ViewportOwned = true; + + return viewport; +} + +static void ImGui::DestroyViewport(ImGuiViewportP* viewport) +{ + // Clear references to this viewport in windows (window->ViewportId becomes the master data) + ImGuiContext& g = *GImGui; + for (ImGuiWindow* window : g.Windows) + { + if (window->Viewport != viewport) + continue; + window->Viewport = NULL; + window->ViewportOwned = false; + } + if (viewport == g.MouseLastHoveredViewport) + g.MouseLastHoveredViewport = NULL; + + // Destroy + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. + IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); + IM_ASSERT(g.Viewports[viewport->Idx] == viewport); + g.Viewports.erase(g.Viewports.Data + viewport->Idx); + IM_DELETE(viewport); +} + +// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. +static void ImGui::WindowSelectViewport(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + window->ViewportAllowPlatformMonitorExtend = -1; + + // Restore main viewport if multi-viewport is not supported by the backend + ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport(); + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) + { + SetWindowViewport(window, main_viewport); + return; + } + window->ViewportOwned = false; + + // Appearing popups reset their viewport so they can inherit again + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) + { + window->Viewport = NULL; + window->ViewportId = 0; + } + + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) == 0) + { + // By default inherit from parent window + if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive)) + window->Viewport = window->ParentWindow->Viewport; + + // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file + if (window->Viewport == NULL && window->ViewportId != 0) + { + window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId); + if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) + window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); + } + } + + bool lock_viewport = false; + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) + { + // Code explicitly request a viewport + window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); + window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. + if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL) + { + window->Viewport->Window = window; + window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node) + } + lock_viewport = true; + } + else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) + { + // Always inherit viewport from parent window + if (window->DockNode && window->DockNode->HostWindow) + IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport); + window->Viewport = window->ParentWindow->Viewport; + } + else if (window->DockNode && window->DockNode->HostWindow) + { + // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame + window->Viewport = window->DockNode->HostWindow->Viewport; + } + else if (flags & ImGuiWindowFlags_Tooltip) + { + window->Viewport = g.MouseViewport; + } + else if (GetWindowAlwaysWantOwnViewport(window)) + { + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid()) + { + if (window->Viewport != NULL && window->Viewport->Window == window) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else + { + // Merge into host viewport? + // We cannot test window->ViewportOwned as it set lower in the function. + // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212) + bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap)); + if (try_to_merge_into_host_viewport) + UpdateTryMergeWindowIntoHostViewports(window); + } + + // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport + if (window->Viewport == NULL) + if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + + // Mark window as allowed to protrude outside of its viewport and into the current monitor + if (!lock_viewport) + { + if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + { + // We need to take account of the possibility that mouse may become invalid. + // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. + ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; + bool use_mouse_ref = (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !g.NavWindow); + bool mouse_valid = IsMousePosValid(&mouse_ref); + if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid)) + window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos(window->Flags)); + else + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + } + else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL) + { + // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. + const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; + if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) + { + // Steal/transfer ownership + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name); + window->Viewport->Window = window; + window->Viewport->ID = window->ID; + window->Viewport->LastNameHash = 0; + } + else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge? + { + // New viewport + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + } + } + else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) + { + // Regular (non-child, non-popup) windows by default are also allowed to protrude + // Child windows are kept contained within their parent. + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + } + } + + // Update flags + window->ViewportOwned = (window == window->Viewport->Window); + window->ViewportId = window->Viewport->ID; + + // If the OS window has a title bar, hide our imgui title bar + //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) + // window->Flags |= ImGuiWindowFlags_NoTitleBar; +} + +void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack) +{ + ImGuiContext& g = *GImGui; + + bool viewport_rect_changed = false; + + // Synchronize window --> viewport in most situations + // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM + if (window->Viewport->PlatformRequestMove) + { + window->Pos = window->Viewport->Pos; + MarkIniSettingsDirty(window); + } + else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Pos = window->Pos; + } + + if (window->Viewport->PlatformRequestResize) + { + window->Size = window->SizeFull = window->Viewport->Size; + MarkIniSettingsDirty(window); + } + else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Size = window->Size; + } + window->Viewport->UpdateWorkRect(); + + // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame() + // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect. + if (viewport_rect_changed) + UpdateViewportPlatformMonitor(window->Viewport); + + // Update common viewport flags + const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; + ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; + ImGuiWindowFlags window_flags = window->Flags; + const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0; + const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; + if (window_flags & ImGuiWindowFlags_Tooltip) + viewport_flags |= ImGuiViewportFlags_TopMost; + if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) + viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; + if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) + viewport_flags |= ImGuiViewportFlags_NoDecoration; + + // Not correct to set modal as topmost because: + // - Because other popups can be stacked above a modal (e.g. combo box in a modal) + // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" + //if (flags & ImGuiWindowFlags_Modal) + // viewport_flags |= ImGuiViewportFlags_TopMost; + + // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them + // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). + // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, + // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. + if (is_short_lived_floating_window && !is_modal) + viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; + + // We can overwrite viewport flags using ImGuiWindowClass (advanced users) + if (window->WindowClass.ViewportFlagsOverrideSet) + viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet; + if (window->WindowClass.ViewportFlagsOverrideClear) + viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; + + // We can also tell the backend that clearing the platform window won't be necessary, + // as our window background is filling the viewport and we have disabled BgAlpha. + // FIXME: Work on support for per-viewport transparency (#2766) + if (!(window_flags & ImGuiWindowFlags_NoBackground)) + viewport_flags |= ImGuiViewportFlags_NoRendererClear; + + window->Viewport->Flags = viewport_flags; + + // Update parent viewport ID + // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport()) + if (window->WindowClass.ParentViewportId != (ImGuiID)-1) + { + ImGuiID old_parent_viewport_id = window->Viewport->ParentViewportId; + window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; + if (window->Viewport->ParentViewportId != old_parent_viewport_id) + window->Viewport->ParentViewport = FindViewportByID(window->Viewport->ParentViewportId); + } + else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive)) + { + window->Viewport->ParentViewport = parent_window_in_stack->Viewport; + window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; + } + else + { + window->Viewport->ParentViewport = g.IO.ConfigViewportsNoDefaultParent ? NULL : GetMainViewport(); + window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; + } +} + +// Called by user at the end of the main loop, after EndFrame() +// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. +void ImGui::UpdatePlatformWindows() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); + IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); + g.FrameCountPlatformEnded = g.FrameCount; + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) + return; + + // Create/resize/destroy platform windows to match each active viewport. + // Skip the main viewport (index 0), which is always fully handled by the application! + for (int i = 1; i < g.Viewports.Size; i++) + { + ImGuiViewportP* viewport = g.Viewports[i]; + + // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window + // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame) + bool destroy_platform_window = false; + destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); + destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); + if (destroy_platform_window) + { + DestroyPlatformWindow(viewport); + continue; + } + + // New windows that appears directly in a new viewport won't always have a size on their first frame + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) + continue; + + // Create window + const bool is_new_platform_window = (viewport->PlatformWindowCreated == false); + if (is_new_platform_window) + { + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + g.PlatformIO.Platform_CreateWindow(viewport); + if (g.PlatformIO.Renderer_CreateWindow != NULL) + g.PlatformIO.Renderer_CreateWindow(viewport); + g.PlatformWindowsCreatedCount++; + viewport->LastNameHash = 0; + viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) + viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. + viewport->PlatformWindowCreated = true; + } + + // Apply Position and Size (from ImGui to Platform/Renderer backends) + if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) + g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); + if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) + g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); + if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) + g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); + viewport->LastPlatformPos = viewport->Pos; + viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; + + // Update title bar (if it changed) + if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window)) + { + const char* title_begin = window_for_title->Name; + char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin); + const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); + if (viewport->LastNameHash != title_hash) + { + char title_end_backup_c = *title_end; + *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. + g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); + *title_end = title_end_backup_c; + viewport->LastNameHash = title_hash; + } + } + + // Update alpha (if it changed) + if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) + g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); + viewport->LastAlpha = viewport->Alpha; + + // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed. + if (g.PlatformIO.Platform_UpdateWindow) + g.PlatformIO.Platform_UpdateWindow(viewport); + + if (is_new_platform_window) + { + // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) + if (g.FrameCount < 3) + viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; + + // Show window + g.PlatformIO.Platform_ShowWindow(viewport); + } + + // Clear request flags + viewport->ClearRequestFlags(); + } +} + +// This is a default/basic function for performing the rendering/swap of multiple Platform Windows. +// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. +// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: +// +// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MyRenderFunction(platform_io.Viewports[i], my_args); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MySwapBufferFunction(platform_io.Viewports[i], my_args); +// +void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) +{ + // Skip the main viewport (index 0), which is always fully handled by the application! + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport* viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_IsMinimized) + continue; + if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); + if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); + } + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport* viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_IsMinimized) + continue; + if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); + if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); + } +} + +static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) + { + const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; + if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) + return monitor_n; + } + return -1; +} + +// Search for the monitor with the largest intersection area with the given rectangle +// We generally try to avoid searching loops but the monitor count should be very small here +// FIXME-OPT: We could test the last monitor used for that viewport first, and early +static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + + const int monitor_count = g.PlatformIO.Monitors.Size; + if (monitor_count <= 1) + return monitor_count - 1; + + // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. + // This is necessary for tooltips which always resize down to zero at first. + const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); + int best_monitor_n = 0; // Default to the first monitor as fallback + float best_monitor_surface = 0.001f; + + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) + { + const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; + const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); + if (monitor_rect.Contains(rect)) + return monitor_n; + ImRect overlapping_rect = rect; + overlapping_rect.ClipWithFull(monitor_rect); + float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); + if (overlapping_surface < best_monitor_surface) + continue; + best_monitor_surface = overlapping_surface; + best_monitor_n = monitor_n; + } + return best_monitor_n; +} + +// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) +static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport) +{ + viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect()); +} + +// Return value is always != NULL, but don't hold on it across frames. +const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p) +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p; + int monitor_idx = viewport->PlatformMonitor; + if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) + return &g.PlatformIO.Monitors[monitor_idx]; + return &g.FallbackMonitor; +} + +void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + if (viewport->PlatformWindowCreated) + { + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + if (g.PlatformIO.Renderer_DestroyWindow) + g.PlatformIO.Renderer_DestroyWindow(viewport); + if (g.PlatformIO.Platform_DestroyWindow) + g.PlatformIO.Platform_DestroyWindow(viewport); + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL); + + // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize() + // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public. + if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID) + viewport->PlatformWindowCreated = false; + } + else + { + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL); + } + viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL; + viewport->ClearRequestFlags(); +} + +void ImGui::DestroyPlatformWindows() +{ + // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend + // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling + // code to operator a consistent manner. + // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + // crashing if it doesn't have data stored. + ImGuiContext& g = *GImGui; + for (ImGuiViewportP* viewport : g.Viewports) + DestroyPlatformWindow(viewport); +} + + +//----------------------------------------------------------------------------- +// [SECTION] DOCKING +//----------------------------------------------------------------------------- +// Docking: Internal Types +// Docking: Forward Declarations +// Docking: ImGuiDockContext +// Docking: ImGuiDockContext Docking/Undocking functions +// Docking: ImGuiDockNode +// Docking: ImGuiDockNode Tree manipulation functions +// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +// Docking: Builder Functions +// Docking: Begin/End Support Functions (called from Begin/End) +// Docking: Settings +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typical Docking call flow: (root level is generally public API): +//----------------------------------------------------------------------------- +// - NewFrame() new dear imgui frame +// | DockContextNewFrameUpdateUndocking() - process queued undocking requests +// | - DockContextProcessUndockWindow() - process one window undocking request +// | - DockContextProcessUndockNode() - process one whole node undocking request +// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes +// | - update g.HoveredDockNode - [debug] update node hovered by mouse +// | - DockContextProcessDock() - process one docking request +// | - DockNodeUpdate() +// | - DockNodeUpdateForRootNode() +// | - DockNodeUpdateFlagsAndCollapse() +// | - DockNodeFindInfo() +// | - destroy unused node or tab bar +// | - create dock node host window +// | - Begin() etc. +// | - DockNodeStartMouseMovingWindow() +// | - DockNodeTreeUpdatePosSize() +// | - DockNodeTreeUpdateSplitter() +// | - draw node background +// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node +// | - DockNodeAddTabBar() +// | - DockNodeWindowMenuUpdate() +// | - DockNodeCalcTabBarLayout() +// | - BeginTabBarEx() +// | - TabItemEx() calls +// | - EndTabBar() +// | - BeginDockableDragDropTarget() +// | - DockNodeUpdate() - recurse into child nodes... +//----------------------------------------------------------------------------- +// - DockSpace() user submit a dockspace into a window +// | Begin(Child) - create a child window +// | DockNodeUpdate() - call main dock node update function +// | End(Child) +// | ItemSize() +//----------------------------------------------------------------------------- +// - Begin() +// | BeginDocked() +// | BeginDockableDragDropSource() +// | BeginDockableDragDropTarget() +// | - DockNodePreviewDockRender() +//----------------------------------------------------------------------------- +// - EndFrame() +// | DockContextEndFrame() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Docking: Internal Types +//----------------------------------------------------------------------------- +// - ImGuiDockRequestType +// - ImGuiDockRequest +// - ImGuiDockPreviewData +// - ImGuiDockNodeSettings +// - ImGuiDockContext +//----------------------------------------------------------------------------- + +enum ImGuiDockRequestType +{ + ImGuiDockRequestType_None = 0, + ImGuiDockRequestType_Dock, + ImGuiDockRequestType_Undock, + ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload +}; + +struct ImGuiDockRequest +{ + ImGuiDockRequestType Type; + ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL) + ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into + ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional] + ImGuiDir DockSplitDir; + float DockSplitRatio; + bool DockSplitOuter; + ImGuiWindow* UndockTargetWindow; + ImGuiDockNode* UndockTargetNode; + + ImGuiDockRequest() + { + Type = ImGuiDockRequestType_None; + DockTargetWindow = DockPayload = UndockTargetWindow = NULL; + DockTargetNode = UndockTargetNode = NULL; + DockSplitDir = ImGuiDir_None; + DockSplitRatio = 0.5f; + DockSplitOuter = false; + } +}; + +struct ImGuiDockPreviewData +{ + ImGuiDockNode FutureNode; + bool IsDropAllowed; + bool IsCenterAvailable; + bool IsSidesAvailable; // Hold your breath, grammar freaks.. + bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) + ImGuiDockNode* SplitNode; + ImGuiDir SplitDir; + float SplitRatio; + ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() + + ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_COUNTOF(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); } +}; + +// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) +struct ImGuiDockNodeSettings +{ + ImGuiID ID; + ImGuiID ParentNodeId; + ImGuiID ParentWindowId; + ImGuiID SelectedTabId; + signed char SplitAxis; + char Depth; + ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) + ImVec2ih Pos; + ImVec2ih Size; + ImVec2ih SizeRef; + ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; } +}; + +//----------------------------------------------------------------------------- +// Docking: Forward Declarations +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // ImGuiDockContext + static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id); + static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node); + static void DockContextDeleteNode(ImGuiContext* ctx, ImGuiDockNode* node); + static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node); + static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req); + static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx); + static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window); + static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count); + static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all + + // ImGuiDockNode + static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar); + static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); + static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); + static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id); + static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node); + static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id); + static void DockNodeHideHostWindow(ImGuiDockNode* node); + static void DockNodeUpdate(ImGuiDockNode* node); + static void DockNodeUpdateForRootNode(ImGuiDockNode* node); + static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node); + static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node); + static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); + static void DockNodeAddTabBar(ImGuiDockNode* node); + static void DockNodeRemoveTabBar(ImGuiDockNode* node); + static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar); + static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); + static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); + static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); + static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); + static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); + static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos); + static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); + static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); + static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } + static int DockNodeGetTabOrder(ImGuiWindow* window); + + // ImGuiDockNode tree manipulations + static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node); + static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); + static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL); + static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node); + static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos); + static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); + + // Settings + static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); + static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); + static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); + static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); + static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); + static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); + static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); + static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockContext +//----------------------------------------------------------------------------- +// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, +// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. +// At boot time only, we run a simple GC to remove nodes that have no references. +// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), +// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). +// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. +//----------------------------------------------------------------------------- +// - DockContextInitialize() +// - DockContextShutdown() +// - DockContextClearNodes() +// - DockContextRebuildNodes() +// - DockContextNewFrameUpdateUndocking() +// - DockContextNewFrameUpdateDocking() +// - DockContextEndFrame() +// - DockContextFindNodeByID() +// - DockContextBindNodeToWindow() +// - DockContextGenNodeID() +// - DockContextAddNode() +// - DockContextRemoveNode() +// - ImGuiDockContextPruneNodeData +// - DockContextPruneUnusedSettingsNodes() +// - DockContextBuildNodesFromSettings() +// - DockContextBuildAddWindowsToNodes() +//----------------------------------------------------------------------------- + +void ImGui::DockContextInitialize(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + + // Add .ini handle for persistent docking data + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Docking"; + ini_handler.TypeHash = ImHashStr("Docking"); + ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read + ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; + g.SettingsHandlers.push_back(ini_handler); + + g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default; +} + +void ImGui::DockContextShutdown(ImGuiContext* ctx) +{ + ImGuiDockContext* dc = &ctx->DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + DockContextDeleteNode(ctx, node); +} + +void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs) +{ + IM_UNUSED(ctx); + IM_ASSERT(ctx == GImGui); + DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); + DockBuilderRemoveNodeChildNodes(root_id); +} + +// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) +void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &ctx->DockContext; + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n"); + SaveIniSettingsToMemory(); + ImGuiID root_id = 0; // Rebuild all + DockContextClearNodes(ctx, root_id, false); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); + DockContextBuildAddWindowsToNodes(ctx, root_id); +} + +// Docking context update function, called by NewFrame() +void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + { + if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) + DockContextClearNodes(ctx, 0, true); + return; + } + + // Setting NoSplit at runtime merges all nodes + if (g.IO.ConfigDockingNoSplit) + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->IsRootNode() && node->IsSplitNode()) + { + DockBuilderRemoveNodeChildNodes(node->ID); + //dc->WantFullRebuild = true; + } + + // Process full rebuild +#if 0 + if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C))) + dc->WantFullRebuild = true; +#endif + if (dc->WantFullRebuild) + { + DockContextRebuildNodes(ctx); + dc->WantFullRebuild = false; + } + + // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) + for (ImGuiDockRequest& req : dc->Requests) + { + if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow) + DockContextProcessUndockWindow(ctx, req.UndockTargetWindow); + else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode) + DockContextProcessUndockNode(ctx, req.UndockTargetNode); + } +} + +// Docking context update function, called by NewFrame() +void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return; + + // [DEBUG] Store hovered dock node. + // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. + // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. + g.DebugHoveredDockNode = NULL; + if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) + { + if (hovered_window->DockNodeAsHost) + g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + else if (hovered_window->RootWindow->DockNode) + g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode; + } + + // Process Docking requests + for (ImGuiDockRequest& req : dc->Requests) + if (req.Type == ImGuiDockRequestType_Dock) + DockContextProcessDock(ctx, &req); + dc->Requests.resize(0); + + // Create windows for each automatic docking nodes + // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high) + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->IsFloatingNode()) + DockNodeUpdate(node); +} + +void ImGui::DockContextEndFrame(ImGuiContext* ctx) +{ + // Draw backgrounds of node missing their window + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &g.DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame) + { + ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size); + ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize); + node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); + node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags); + } +} + +ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id) +{ + return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id); +} + +ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) +{ + // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) + // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 + // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted. + ImGuiID id = 0x0001; + while (DockContextFindNodeByID(ctx, id) != NULL) + id++; + return id; +} + +static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) +{ + // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. + ImGuiContext& g = *ctx; + if (id == 0) + id = DockContextGenNodeID(ctx); + else + IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); + + // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id); + ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); + ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); + return node; +} + +static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node) +{ + ImGuiContext& g = *ctx; + + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID); + IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); + IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL); + IM_ASSERT(node->Windows.Size == 0); + + if (node->HostWindow) + node->HostWindow->DockNodeAsHost = NULL; + + ImGuiDockNode* parent_node = node->ParentNode; + const bool merge = (merge_sibling_into_parent_node && parent_node != NULL); + if (merge) + { + IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node); + ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]); + DockNodeTreeMerge(&g, parent_node, sibling_node); + } + else + { + for (int n = 0; parent_node && n < IM_COUNTOF(parent_node->ChildNodes); n++) + if (parent_node->ChildNodes[n] == node) + node->ParentNode->ChildNodes[n] = NULL; + DockContextDeleteNode(ctx, node); + } +} + +// Raw-ish delete +static void ImGui::DockContextDeleteNode(ImGuiContext* ctx, ImGuiDockNode* node) +{ + ImGuiDockContext* dc = &ctx->DockContext; + if (node->TabBar) + IM_DELETE(node->TabBar); + node->TabBar = NULL; + dc->Nodes.SetVoidPtr(node->ID, NULL); + IM_DELETE(node); +} + +static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs) +{ + const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs; + const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs; + return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a); +} + +// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here. +struct ImGuiDockContextPruneNodeData +{ + int CountWindows, CountChildWindows, CountChildNodes; + ImGuiID RootId; + ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; } +}; + +// Garbage collect unused nodes (run once at init time) +static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &ctx->DockContext; + IM_ASSERT(g.Windows.Size == 0); + + ImPool pool; + pool.Reserve(dc->NodesSettings.Size); + + // Count child nodes and compute RootID + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; + if (pool.GetByKey(settings->ID) != 0) + { + settings->ID = 0; // Duplicate + continue; + } + ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; + pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; + if (settings->ParentNodeId) + pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++; + } + + // Count reference to dock ids from dockspaces + // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; + if (settings->ParentWindowId != 0) + if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId)) + if (window_settings->DockId) + if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId)) + data->CountChildNodes++; + } + + // Count reference to dock ids from window settings + // We guard against the possibility of an invalid .ini file (RootID may point to a missing node) + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (ImGuiID dock_id = settings->DockId) + if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id)) + { + data->CountWindows++; + if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId)) + data_root->CountChildWindows++; + } + + // Prune + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; + ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); + if (data == NULL || data->CountWindows > 1) + continue; + ImGuiDockContextPruneNodeData* data_root = (settings->ID == data->RootId) ? data : pool.GetByKey(data->RootId); + ImGuiDockContextPruneNodeData* data_parent = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : NULL; + + bool remove = false; + remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window + remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window + remove |= (data_root == NULL || data_root->CountChildWindows == 0); + if (remove) + { + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID); + DockSettingsRemoveNodeReferences(&settings->ID, 1); + settings->ID = 0; + } + else if (data_parent && data_parent->CountChildNodes == 1) + { + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Merge 0x%08X->0X%08X\n", settings->ID, settings->ParentNodeId); + DockSettingsRenameNodeReferences(settings->ID, settings->ParentNodeId); + settings->ID = 0; + } + } +} + +static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count) +{ + // Build nodes + ImGuiContext& g = *ctx; IM_UNUSED(g); + for (int node_n = 0; node_n < node_settings_count; node_n++) + { + ImGuiDockNodeSettings* settings = &node_settings_array[node_n]; + if (settings->ID == 0) + continue; + if (DockContextFindNodeByID(ctx, settings->ID) != NULL) + { + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextBuildNodesFromSettings: skip duplicate node 0x%08X\n", settings->ID); + continue; + } + ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID); + node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL; + node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); + node->Size = ImVec2(settings->Size.x, settings->Size.y); + node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode; + if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) + node->ParentNode->ChildNodes[0] = node; + else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) + node->ParentNode->ChildNodes[1] = node; + node->SelectedTabId = settings->SelectedTabId; + node->SplitAxis = (ImGuiAxis)settings->SplitAxis; + node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); + + // Bind host window immediately if it already exist (in case of a rebuild) + // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. + char host_window_title[20]; + ImGuiDockNode* root_node = DockNodeGetRootNode(node); + node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_COUNTOF(host_window_title))); + } +} + +void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id) +{ + // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) + ImGuiContext& g = *ctx; + for (ImGuiWindow* window : g.Windows) + { + if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1) + continue; + if (window->DockNode != NULL) + continue; + + ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); + IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings() + if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id) + DockNodeAddWindow(node, window, true); + } +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockContext Docking/Undocking functions +//----------------------------------------------------------------------------- +// - DockContextQueueDock() +// - DockContextQueueUndockWindow() +// - DockContextQueueUndockNode() +// - DockContextQueueNotifyRemovedNode() +// - DockContextProcessDock() +// - DockContextProcessUndockWindow() +// - DockContextProcessUndockNode() +// - DockContextCalcDropPosForDocking() +//----------------------------------------------------------------------------- + +void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer) +{ + IM_ASSERT(target != payload); + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Dock; + req.DockTargetWindow = target; + req.DockTargetNode = target_node; + req.DockPayload = payload; + req.DockSplitDir = split_dir; + req.DockSplitRatio = split_ratio; + req.DockSplitOuter = split_outer; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) +{ + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Undock; + req.UndockTargetWindow = window; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) +{ + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Undock; + req.UndockTargetNode = node; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node) +{ + ImGuiDockContext* dc = &ctx->DockContext; + for (ImGuiDockRequest& req : dc->Requests) + if (req.DockTargetNode == node) + req.Type = ImGuiDockRequestType_None; +} + +void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) +{ + IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL)); + IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL); + + ImGuiContext& g = *ctx; + IM_UNUSED(g); + + ImGuiWindow* payload_window = req->DockPayload; // Optional + ImGuiWindow* target_window = req->DockTargetWindow; + ImGuiDockNode* node = req->DockTargetNode; + if (payload_window) + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir); + else + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir); + + // Decide which Tab will be selected at the end of the operation + ImGuiID next_selected_id = 0; + ImGuiDockNode* payload_node = NULL; + if (payload_window) + { + payload_node = payload_window->DockNodeAsHost; + payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later. + if (payload_node && payload_node->IsLeafNode()) + next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId; + if (payload_node == NULL) + next_selected_id = payload_window->TabId; + } + + // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. + if (node) + IM_ASSERT(node->LastFrameAlive <= g.FrameCount); + if (node && target_window && node == target_window->DockNodeAsHost) + IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode()); + + // Create new node and add existing window to it + if (node == NULL) + { + node = DockContextAddNode(ctx, 0); + node->Pos = target_window->Pos; + node->Size = target_window->Size; + if (target_window->DockNodeAsHost == NULL) + { + DockNodeAddWindow(node, target_window, true); + node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; + target_window->DockIsActive = true; + } + } + + ImGuiDir split_dir = req->DockSplitDir; + if (split_dir != ImGuiDir_None) + { + // Split into two, one side will be our payload node unless we are dropping a loose window + const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side + const float split_ratio = req->DockSplitRatio; + DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! + ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1]; + new_node->HostWindow = node->HostWindow; + node = new_node; + } + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); + + if (node != payload_node) + { + // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) + if (node->Windows.Size > 0 && node->TabBar == NULL) + { + DockNodeAddTabBar(node); + for (int n = 0; n < node->Windows.Size; n++) + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); + } + + if (payload_node != NULL) + { + // Transfer full payload node (with 1+ child windows or child nodes) + if (payload_node->IsSplitNode()) + { + if (node->Windows.Size > 0) + { + // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. + // In this situation, we move the windows of the target node into the currently visible node of the payload. + // This allows us to preserve some of the underlying dock tree settings nicely. + IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. + ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows; + if (visible_node->TabBar) + IM_ASSERT(visible_node->TabBar->Tabs.Size > 0); + DockNodeMoveWindows(node, visible_node); + DockNodeMoveWindows(visible_node, node); + DockSettingsRenameNodeReferences(node->ID, visible_node->ID); + } + if (node->IsCentralNode()) + { + // Central node property needs to be moved to a leaf node, pick the last focused one. + // FIXME-DOCK: If we had to transfer other flags here, what would the policy be? + ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId); + IM_ASSERT(last_focused_node != NULL); + ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node); + IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node)); + last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode); + last_focused_root_node->CentralNode = last_focused_node; + } + + IM_ASSERT(node->Windows.Size == 0); + DockNodeMoveChildNodes(node, payload_node); + } + else + { + const ImGuiID payload_dock_id = payload_node->ID; + DockNodeMoveWindows(node, payload_node); + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); + } + DockContextRemoveNode(ctx, payload_node, true); + } + else if (payload_window) + { + // Transfer single window + const ImGuiID payload_dock_id = payload_window->DockId; + node->VisibleWindow = payload_window; + DockNodeAddWindow(node, payload_window, true); + if (payload_dock_id != 0) + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); + } + } + else + { + // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar + node->WantHiddenTabBarUpdate = true; + } + + // Update selection immediately + if (ImGuiTabBar* tab_bar = node->TabBar) + tab_bar->NextSelectedTabId = next_selected_id; + MarkIniSettingsDirty(); +} + +// Problem: +// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more +// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic +// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be +// due to missing ImGuiBackendFlags_HasMouseCursors backend flag). +// Solution: +// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor. +// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). +static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport) +{ + if (ref_viewport == NULL) + return size; + + ImGuiContext& g = *GImGui; + ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f); + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + { + const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport); + max_size = ImTrunc(monitor->WorkSize * 0.90f); + } + return ImMin(size, max_size); +} + +void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref) +{ + ImGuiContext& g = *ctx; + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref); + if (window->DockNode) + DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId); + else + window->DockId = 0; + window->Collapsed = false; + window->DockIsActive = false; + window->DockNodeIsVisible = window->DockTabIsVisible = false; + window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport); + + MarkIniSettingsDirty(); +} + +void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) +{ + ImGuiContext& g = *ctx; + IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID); + IM_ASSERT(node->IsLeafNode()); + IM_ASSERT(node->Windows.Size >= 1); + + if (node->IsRootNode() || node->IsCentralNode()) + { + // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. + ImGuiDockNode* new_node = DockContextAddNode(ctx, 0); + new_node->Pos = node->Pos; + new_node->Size = node->Size; + new_node->SizeRef = node->SizeRef; + DockNodeMoveWindows(new_node, node); + DockSettingsRenameNodeReferences(node->ID, new_node->ID); + node = new_node; + } + else + { + // Otherwise extract our node and merge our sibling back into the parent node. + IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); + int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; + node->ParentNode->ChildNodes[index_in_parent] = NULL; + DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]); + node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport + node->ParentNode = NULL; + } + for (ImGuiWindow* window : node->Windows) + { + window->Flags &= ~ImGuiWindowFlags_ChildWindow; + if (window->ParentWindow) + window->ParentWindow->DC.ChildWindows.find_erase(window); + UpdateWindowParentAndRootLinks(window, window->Flags, NULL); + } + node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode; + node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport); + node->WantMouseMove = true; + MarkIniSettingsDirty(); +} + +// This is mostly used for automation. +bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos) +{ + if (target != NULL && target_node == NULL) + target_node = target->DockNode; + + // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects + // (which would be functionally identical) we only show the outer one. Reflect this here. + if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None) + split_outer = true; + ImGuiDockPreviewData split_data; + DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer); + if (split_data.DropRectsDraw[split_dir+1].IsInverted()) + return false; + *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter(); + return true; +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockNode +//----------------------------------------------------------------------------- +// - DockNodeGetTabOrder() +// - DockNodeAddWindow() +// - DockNodeRemoveWindow() +// - DockNodeMoveChildNodes() +// - DockNodeMoveWindows() +// - DockNodeApplyPosSizeToWindows() +// - DockNodeHideHostWindow() +// - ImGuiDockNodeFindInfoResults +// - DockNodeFindInfo() +// - DockNodeFindWindowByID() +// - DockNodeUpdateFlagsAndCollapse() +// - DockNodeUpdateHasCentralNodeFlag() +// - DockNodeUpdateVisibleFlag() +// - DockNodeStartMouseMovingWindow() +// - DockNodeUpdate() +// - DockNodeUpdateWindowMenu() +// - DockNodeBeginAmendTabBar() +// - DockNodeEndAmendTabBar() +// - DockNodeUpdateTabBar() +// - DockNodeAddTabBar() +// - DockNodeRemoveTabBar() +// - DockNodeIsDropAllowedOne() +// - DockNodeIsDropAllowed() +// - DockNodeCalcTabBarLayout() +// - DockNodeCalcSplitRects() +// - DockNodeCalcDropRectsAndTestMousePos() +// - DockNodePreviewDockSetup() +// - DockNodePreviewDockRender() +//----------------------------------------------------------------------------- + +ImGuiDockNode::ImGuiDockNode(ImGuiID id) +{ + ID = id; + SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None; + ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; + TabBar = NULL; + SplitAxis = ImGuiAxis_None; + + State = ImGuiDockNodeState_Unknown; + LastBgColor = IM_COL32_WHITE; + HostWindow = VisibleWindow = NULL; + CentralNode = OnlyNodeWithWindows = NULL; + CountNodeWithWindows = 0; + LastFrameAlive = LastFrameActive = LastFrameFocused = -1; + LastFocusedNodeId = 0; + SelectedTabId = 0; + WantCloseTabId = 0; + RefViewportId = 0; + AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; + AuthorityForViewport = ImGuiDataAuthority_Auto; + IsVisible = true; + IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false; + IsBgDrawnThisFrame = false; + WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; +} + +ImGuiDockNode::~ImGuiDockNode() +{ + IM_ASSERT(TabBar == NULL); + ChildNodes[0] = ChildNodes[1] = NULL; +} + +int ImGui::DockNodeGetTabOrder(ImGuiWindow* window) +{ + ImGuiTabBar* tab_bar = window->DockNode->TabBar; + if (tab_bar == NULL) + return -1; + ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId); + return tab ? TabBarGetTabOrder(tab_bar, tab) : -1; +} + +static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window) +{ + window->Hidden = true; + window->HiddenFramesCanSkipItems = window->Active ? 1 : 2; +} + +static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar) +{ + ImGuiContext& g = *GImGui; (void)g; + if (window->DockNode) + { + // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node) + IM_ASSERT(window->DockNode->ID != node->ID); + DockNodeRemoveWindow(window->DockNode, window, 0); + } + IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name); + + // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, + // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). + // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() + if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false) + DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]); + + node->Windows.push_back(window); + node->WantHiddenTabBarUpdate = true; + window->DockNode = node; + window->DockId = node->ID; + window->DockIsActive = (node->Windows.Size > 1); + window->DockTabWantClose = false; + + // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. + // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. + if (node->HostWindow == NULL && node->IsFloatingNode()) + { + if (node->AuthorityForPos == ImGuiDataAuthority_Auto) + node->AuthorityForPos = ImGuiDataAuthority_Window; + if (node->AuthorityForSize == ImGuiDataAuthority_Auto) + node->AuthorityForSize = ImGuiDataAuthority_Window; + if (node->AuthorityForViewport == ImGuiDataAuthority_Auto) + node->AuthorityForViewport = ImGuiDataAuthority_Window; + } + + // Add to tab bar if requested + if (add_to_tab_bar) + { + if (node->TabBar == NULL) + { + DockNodeAddTabBar(node); + node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId; + + // Add existing windows + for (int n = 0; n < node->Windows.Size - 1; n++) + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); + } + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window); + } + + DockNodeUpdateVisibleFlag(node); + + // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. + if (node->HostWindow) + UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow); +} + +static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(window->DockNode == node); + //IM_ASSERT(window->RootWindowDockTree == node->HostWindow); + //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin() + IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name); + + window->DockNode = NULL; + window->DockIsActive = window->DockTabWantClose = false; + window->DockId = save_dock_id; + window->Flags &= ~ImGuiWindowFlags_ChildWindow; + if (window->ParentWindow) + window->ParentWindow->DC.ChildWindows.find_erase(window); + UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately + + if (node->HostWindow && node->HostWindow->ViewportOwned) + { + // When undocking from a user interaction this will always run in NewFrame() and have not much effect. + // But mid-frame, if we clear viewport we need to mark window as hidden as well. + window->Viewport = NULL; + window->ViewportId = 0; + window->ViewportOwned = false; + window->Hidden = true; + } + + // Remove window + bool erased = false; + for (int n = 0; n < node->Windows.Size; n++) + if (node->Windows[n] == window) + { + node->Windows.erase(node->Windows.Data + n); + erased = true; + break; + } + if (!erased) + IM_ASSERT(erased); + if (node->VisibleWindow == window) + node->VisibleWindow = NULL; + + // Remove tab and possibly tab bar + node->WantHiddenTabBarUpdate = true; + if (node->TabBar) + { + TabBarRemoveTab(node->TabBar, window->TabId); + const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2; + if (node->Windows.Size < tab_count_threshold_for_tab_bar) + DockNodeRemoveTabBar(node); + } + + if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID) + { + // Automatic dock node delete themselves if they are not holding at least one tab + DockContextRemoveNode(&g, node, true); + return; + } + + if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow) + { + ImGuiWindow* remaining_window = node->Windows[0]; + // Note: we used to transport viewport ownership here. + remaining_window->Collapsed = node->HostWindow->Collapsed; + } + + // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree + DockNodeUpdateVisibleFlag(node); +} + +static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) +{ + IM_ASSERT(dst_node->Windows.Size == 0); + dst_node->ChildNodes[0] = src_node->ChildNodes[0]; + dst_node->ChildNodes[1] = src_node->ChildNodes[1]; + if (dst_node->ChildNodes[0]) + dst_node->ChildNodes[0]->ParentNode = dst_node; + if (dst_node->ChildNodes[1]) + dst_node->ChildNodes[1]->ParentNode = dst_node; + dst_node->SplitAxis = src_node->SplitAxis; + dst_node->SizeRef = src_node->SizeRef; + src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL; +} + +static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) +{ + // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered) + IM_ASSERT(src_node && dst_node && dst_node != src_node); + ImGuiTabBar* src_tab_bar = src_node->TabBar; + if (src_tab_bar != NULL) + IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size); + + // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) + bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL); + if (move_tab_bar) + { + dst_node->TabBar = src_node->TabBar; + src_node->TabBar = NULL; + } + + // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). + for (ImGuiWindow* window : src_node->Windows) + { + window->DockNode = NULL; + window->DockIsActive = false; + DockNodeAddWindow(dst_node, window, !move_tab_bar); + } + src_node->Windows.clear(); + + if (!move_tab_bar && src_node->TabBar) + { + if (dst_node->TabBar) + dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId; + DockNodeRemoveTabBar(src_node); + } +} + +static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node) +{ + for (ImGuiWindow* window : node->Windows) + { + SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame + SetWindowSize(window, node->Size, ImGuiCond_Always); + } +} + +static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node) +{ + if (node->HostWindow) + { + if (node->HostWindow->DockNodeAsHost == node) + node->HostWindow->DockNodeAsHost = NULL; + node->HostWindow = NULL; + } + + if (node->Windows.Size == 1) + { + node->VisibleWindow = node->Windows[0]; + node->Windows[0]->DockIsActive = false; + } + + if (node->TabBar) + DockNodeRemoveTabBar(node); +} + +// Search function called once by root node in DockNodeUpdate() +struct ImGuiDockNodeTreeInfo +{ + ImGuiDockNode* CentralNode; + ImGuiDockNode* FirstNodeWithWindows; + int CountNodesWithWindows; + //ImGuiWindowClass WindowClassForMerges; + + ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); } +}; + +static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info) +{ + if (node->Windows.Size > 0) + { + if (info->FirstNodeWithWindows == NULL) + info->FirstNodeWithWindows = node; + info->CountNodesWithWindows++; + } + if (node->IsCentralNode()) + { + IM_ASSERT(info->CentralNode == NULL); // Should be only one + IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this."); + info->CentralNode = node; + } + if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL) + return; + if (node->ChildNodes[0]) + DockNodeFindInfo(node->ChildNodes[0], info); + if (node->ChildNodes[1]) + DockNodeFindInfo(node->ChildNodes[1], info); +} + +static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id) +{ + IM_ASSERT(id != 0); + for (ImGuiWindow* window : node->Windows) + if (window->ID == id) + return window; + return NULL; +} + +// - Remove inactive windows/nodes. +// - Update visibility flag. +static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); + + // Inherit most flags + if (node->ParentNode) + node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + + // Recurse into children + // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. + // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node' + // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) + node->HasCentralNodeChild = false; + if (node->ChildNodes[0]) + DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]); + + // Remove inactive windows, collapse nodes + // Merge node flags overrides stored in windows + node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow* window = node->Windows[window_n]; + IM_ASSERT(window->DockNode == node); + + bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); + bool remove = false; + remove |= node_was_active && (window->WasActive == false); // Can't use 'window->LastFrameActive + 1 < g.FrameCount'. (see #9151) + remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame + remove |= (window->DockTabWantClose); + if (remove) + { + window->DockTabWantClose = false; + if (node->Windows.Size == 1 && !node->IsCentralNode()) + { + DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; + DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return + return; + } + DockNodeRemoveWindow(node, window, node->ID); + window_n--; + continue; + } + + // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. + //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear; + node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet; + } + node->UpdateMergedFlags(); + + // Auto-hide tab bar option + ImGuiDockNodeFlags node_flags = node->MergedFlags; + if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar()) + node->WantHiddenTabBarToggle = true; + node->WantHiddenTabBarUpdate = false; + + // Cancel toggling if we know our tab bar is enforced to be hidden at all times + if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar)) + node->WantHiddenTabBarToggle = false; + + // Apply toggles at a single point of the frame (here!) + if (node->Windows.Size > 1) + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); + else if (node->WantHiddenTabBarToggle) + node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar); + node->WantHiddenTabBarToggle = false; + + DockNodeUpdateVisibleFlag(node); +} + +// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. +static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node) +{ + node->HasCentralNodeChild = false; + if (node->ChildNodes[0]) + DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]); + if (node->IsRootNode()) + { + ImGuiDockNode* mark_node = node->CentralNode; + while (mark_node) + { + mark_node->HasCentralNodeChild = true; + mark_node = mark_node->ParentNode; + } + } +} + +static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node) +{ + // Update visibility flag + bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode(); + is_visible |= (node->Windows.Size > 0); + is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); + is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); + node->IsVisible = is_visible; +} + +static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(node->WantMouseMove == true); + StartMouseMovingWindow(window); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; + g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. + node->WantMouseMove = false; +} + +// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. +static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node) +{ + DockNodeUpdateFlagsAndCollapse(node); + + // - Setup central node pointers + // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) + // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing + ImGuiDockNodeTreeInfo info; + DockNodeFindInfo(node, &info); + node->CentralNode = info.CentralNode; + node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL; + node->CountNodeWithWindows = info.CountNodesWithWindows; + if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL) + node->LastFocusedNodeId = info.FirstNodeWithWindows->ID; + + // Copy the window class from of our first window so it can be used for proper dock filtering. + // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. + // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. + if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows) + { + node->WindowClass = first_node_with_windows->Windows[0]->WindowClass; + for (int n = 1; n < first_node_with_windows->Windows.Size; n++) + if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false) + { + node->WindowClass = first_node_with_windows->Windows[n]->WindowClass; + break; + } + } + + ImGuiDockNode* mark_node = node->CentralNode; + while (mark_node) + { + mark_node->HasCentralNodeChild = true; + mark_node = mark_node->ParentNode; + } +} + +static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window) +{ + // Remove ourselves from any previous different host window + // This can happen if a user mistakenly does (see #4295 for details): + // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace + // - N+1: NewFrame() // will create floating host window for that node + // - N+1: DockSpace(id) // requalify node as dockspace, moving host window + if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node) + node->HostWindow->DockNodeAsHost = NULL; + + host_window->DockNodeAsHost = node; + node->HostWindow = host_window; +} + +static void ImGui::DockNodeUpdate(ImGuiDockNode* node) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(node->LastFrameActive != g.FrameCount); + node->LastFrameAlive = g.FrameCount; + node->IsBgDrawnThisFrame = false; + + node->CentralNode = node->OnlyNodeWithWindows = NULL; + if (node->IsRootNode()) + DockNodeUpdateForRootNode(node); + + // Remove tab bar if not needed + if (node->TabBar && node->IsNoTabBar()) + DockNodeRemoveTabBar(node); + + // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) + bool want_to_hide_host_window = false; + if (node->IsFloatingNode()) + { + if (node->Windows.Size <= 1 && node->IsLeafNode()) + if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar)) + want_to_hide_host_window = true; + if (node->CountNodeWithWindows == 0) + want_to_hide_host_window = true; + } + if (want_to_hide_host_window) + { + if (node->Windows.Size == 1) + { + // Floating window pos/size is authoritative + ImGuiWindow* single_window = node->Windows[0]; + node->Pos = single_window->Pos; + node->Size = single_window->SizeFull; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; + + // Transfer focus immediately so when we revert to a regular window it is immediately selected + if (node->HostWindow && g.NavWindow == node->HostWindow) + FocusWindow(single_window); + if (node->HostWindow) + { + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name); + single_window->Viewport = node->HostWindow->Viewport; + single_window->ViewportId = node->HostWindow->ViewportId; + if (node->HostWindow->ViewportOwned) + { + single_window->Viewport->ID = single_window->ID; + single_window->Viewport->Window = single_window; + single_window->ViewportOwned = true; + } + } + node->RefViewportId = single_window->ViewportId; + } + + DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; + node->WantCloseAll = false; + node->WantCloseTabId = 0; + node->HasCloseButton = node->HasWindowMenuButton = false; + node->LastFrameActive = g.FrameCount; + + if (node->WantMouseMove && node->Windows.Size == 1) + DockNodeStartMouseMovingWindow(node, node->Windows[0]); + return; + } + + // In some circumstance we will defer creating the host window (so everything will be kept hidden), + // while the expected visible window is resizing itself. + // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + // N+0: Begin(): window created (with no known size), node is created + // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + // In reality it isn't very important as user quickly ends up with size data in .ini file. + if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode()) + { + IM_ASSERT(node->Windows.Size > 0); + ImGuiWindow* ref_window = NULL; + if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! + ref_window = DockNodeFindWindowByID(node, node->SelectedTabId); + if (ref_window == NULL) + ref_window = node->Windows[0]; + if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0) + { + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing; + return; + } + } + + const ImGuiDockNodeFlags node_flags = node->MergedFlags; + + // Decide if the node will have a close button and a window menu button + node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; + node->HasCloseButton = false; + for (ImGuiWindow* window : node->Windows) + { + // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. + node->HasCloseButton |= window->HasCloseButton; + window->DockIsActive = (node->Windows.Size > 1); + } + if ((node_flags & ImGuiDockNodeFlags_NoCloseButton) || !g.Style.DockingNodeHasCloseButton) + node->HasCloseButton = false; + + // Bind or create host window + ImGuiWindow* host_window = NULL; + bool beginned_into_host_window = false; + if (node->IsDockSpace()) + { + // [Explicit root dockspace node] + IM_ASSERT(node->HostWindow); + host_window = node->HostWindow; + } + else + { + // [Automatic root or child nodes] + if (node->IsRootNode() && node->IsVisible) + { + ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL; + + // Sync Pos + if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window) + SetNextWindowPos(ref_window->Pos); + else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode) + SetNextWindowPos(node->Pos); + + // Sync Size + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) + SetNextWindowSize(ref_window->SizeFull); + else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode) + SetNextWindowSize(node->Size); + + // Sync Collapsed + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) + SetNextWindowCollapsed(ref_window->Collapsed); + + // Sync Viewport + if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window) + SetNextWindowViewport(ref_window->ViewportId); + else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0) + SetNextWindowViewport(node->RefViewportId); + + SetNextWindowClass(&node->WindowClass); + + // Begin into the host window + char window_label[20]; + DockNodeGetHostWindowTitle(node, window_label, IM_COUNTOF(window_label)); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost; + window_flags |= ImGuiWindowFlags_NoFocusOnAppearing; + window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse; + window_flags |= ImGuiWindowFlags_NoTitleBar; + + SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + Begin(window_label, NULL, window_flags); + PopStyleVar(); + beginned_into_host_window = true; + + host_window = g.CurrentWindow; + DockNodeSetupHostWindow(node, host_window); + host_window->DC.CursorPos = host_window->Pos; + node->Pos = host_window->Pos; + node->Size = host_window->Size; + + // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) + // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. + // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. + // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window + // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back + // after the dock host window, losing their top-most status. + if (node->HostWindow->Appearing) + BringWindowToDisplayFront(node->HostWindow); + + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; + } + else if (node->ParentNode) + { + node->HostWindow = host_window = node->ParentNode->HostWindow; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; + } + if (node->WantMouseMove && node->HostWindow) + DockNodeStartMouseMovingWindow(node, node->HostWindow); + } + node->RefViewportId = 0; // Clear when we have a host window + + // Update focused node (the one whose title bar is highlight) within a node tree + if (node->IsSplitNode()) + IM_ASSERT(node->TabBar == NULL); + if (node->IsRootNode()) + if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL) + while (p_window != NULL && p_window->DockNode != NULL) + { + ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode); + if (p_node == node) + { + node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID! + break; + } + p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL; + } + + // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace + ImGuiDockNode* central_node = node->CentralNode; + const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); + bool central_node_hole_register_hit_test_hole = central_node_hole; + if (central_node_hole) + if (const ImGuiPayload* payload = ImGui::GetDragDropPayload()) + if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data)) + central_node_hole_register_hit_test_hole = false; + if (central_node_hole_register_hit_test_hole) + { + // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. + // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen + // covering passthru node we'd have a gap on the edge not covered by the hole) + IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode + ImGuiDockNode* root_node = DockNodeGetRootNode(central_node); + ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size); + ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size); + if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += g.WindowsBorderHoverPadding; } + if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= g.WindowsBorderHoverPadding; } + if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += g.WindowsBorderHoverPadding; } + if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= g.WindowsBorderHoverPadding; } + //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)); + if (central_node_hole && !hole_rect.IsInverted()) + { + SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min); + if (host_window->ParentWindow) + SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min); + } + } + + // Update position/size, process and draw resizing splitters + if (node->IsRootNode() && host_window) + { + DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size); + PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]); + PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]); + PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]); + DockNodeTreeUpdateSplitter(node); + PopStyleColor(3); + } + + // Draw empty node background (currently can only be the Central Node) + if (host_window && node->IsEmpty() && node->IsVisible) + { + host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); + node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg); + if (node->LastBgColor != 0) + host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor); + node->IsBgDrawnThisFrame = true; + } + + // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. + // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size + // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! + const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; + if (render_dockspace_bg && node->IsVisible) + { + host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); + if (central_node_hole) + RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f); + else + host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f); + } + + // Draw and populate Tab Bar + if (host_window) + host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); + if (host_window && node->Windows.Size > 0) + { + DockNodeUpdateTabBar(node, host_window); + } + else + { + node->WantCloseAll = false; + node->WantCloseTabId = 0; + node->IsFocused = false; + } + if (node->TabBar && node->TabBar->SelectedTabId) + node->SelectedTabId = node->TabBar->SelectedTabId; + else if (node->Windows.Size > 0) + node->SelectedTabId = node->Windows[0]->TabId; + + // Draw payload drop target + if (host_window && node->IsVisible) + if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window)) + BeginDockableDragDropTarget(host_window); + + // We update this after DockNodeUpdateTabBar() + node->LastFrameActive = g.FrameCount; + + // Recurse into children + // FIXME-DOCK FIXME-OPT: Should not need to recurse into children + if (host_window) + { + if (node->ChildNodes[0]) + DockNodeUpdate(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdate(node->ChildNodes[1]); + + // Render outer borders last (after the tab bar) + if (node->IsRootNode()) + RenderWindowOuterBorders(host_window); + } + + // End host window + if (beginned_into_host_window) //-V1020 + End(); +} + +// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. +static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs) +{ + ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window; + ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window; + if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder)) + return d; + return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); +} + +// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node. +// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented) +// Custom overrides may want to decorate, group, sort entries. +// Please note those are internal structures: if you copy this expect occasional breakage. +// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler) +void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar) +{ + IM_UNUSED(ctx); + if (tab_bar->Tabs.Size == 1) + { + // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table. + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar())) + node->WantHiddenTabBarToggle = true; + } + else + { + // Display a selectable list of windows in this docking node + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (tab->Flags & ImGuiTabItemFlags_Button) + continue; + if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId)) + TabBarQueueFocus(tab_bar, tab); + SameLine(); + Text(" "); + } + } +} + +static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar) +{ + // Try to position the menu so it is more likely to stays within the same viewport + ImGuiContext& g = *GImGui; + if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left) + SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); + else + SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); + if (BeginPopup("#WindowMenu")) + { + node->IsFocused = true; + g.DockNodeWindowMenuHandler(&g, node, tab_bar); + EndPopup(); + } +} + +// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. +bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node) +{ + if (node->TabBar == NULL || node->HostWindow == NULL) + return false; + if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) + return false; + if (node->TabBar->ID == 0) + return false; + Begin(node->HostWindow->Name); + PushOverrideID(node->ID); + bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags); + IM_UNUSED(ret); + IM_ASSERT(ret); + return true; +} + +void ImGui::DockNodeEndAmendTabBar() +{ + EndTabBar(); + PopID(); + End(); +} + +static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node) +{ + // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy) + ImGuiContext& g = *GImGui; + if (g.NavWindowingTarget) + return (g.NavWindowingTarget->DockNode == node); + + // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window) + if (g.NavWindow && root_node->LastFocusedNodeId == node->ID) + { + // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node) + ImGuiWindow* parent_window = g.NavWindow->RootWindow; + while (parent_window->Flags & ImGuiWindowFlags_ChildMenu) + parent_window = parent_window->ParentWindow->RootWindow; + ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode; + for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL) + if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node) + return true; + } + return false; +} + +// Submit the tab bar corresponding to a dock node and various housekeeping details. +static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + + const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); + node->WantCloseAll = false; + node->WantCloseTabId = 0; + + // Decide if we should use a focused title bar color + bool is_focused = false; + ImGuiDockNode* root_node = DockNodeGetRootNode(node); + if (IsDockNodeTitleBarHighlighted(node, root_node)) + is_focused = true; + + // Hidden tab bar will show a triangle on the upper-left (in Begin) + if (node->IsHiddenTabBar() || node->IsNoTabBar()) + { + node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; + node->IsFocused = is_focused; + if (is_focused) + node->LastFrameFocused = g.FrameCount; + if (node->VisibleWindow) + { + // Notify root of visible window (used to display title in OS task bar) + if (is_focused || root_node->VisibleWindow == NULL) + root_node->VisibleWindow = node->VisibleWindow; + if (node->TabBar) + node->TabBar->VisibleTabId = node->VisibleWindow->TabId; + } + return; + } + + // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed + bool backup_skip_item = host_window->SkipItems; + if (!node->IsDockSpace()) + { + host_window->SkipItems = false; + host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + } + + // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + // as docked windows themselves will override the stack with their own root ID. + PushOverrideID(node->ID); + ImGuiTabBar* tab_bar = node->TabBar; + bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden + if (tab_bar == NULL) + { + DockNodeAddTabBar(node); + tab_bar = node->TabBar; + } + + ImGuiID focus_tab_id = 0; + node->IsFocused = is_focused; + + const ImGuiDockNodeFlags node_flags = node->MergedFlags; + const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None); + + // In a dock node, the Collapse Button turns into the Window Menu button. + // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? + if (has_window_menu_button && IsPopupOpen("#WindowMenu")) + { + ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId; + DockNodeWindowMenuUpdate(node, tab_bar); + if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id) + focus_tab_id = tab_bar->NextSelectedTabId; + is_focused |= node->IsFocused; + } + + // Layout + ImRect title_bar_rect, tab_bar_rect; + ImVec2 window_menu_button_pos; + ImVec2 close_button_pos; + DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos); + + // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. + const int tabs_count_old = tab_bar->Tabs.Size; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow* window = node->Windows[window_n]; + if (TabBarFindTabByID(tab_bar, window->TabId) == NULL) + TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window); + } + + // Title bar + if (is_focused) + node->LastFrameFocused = g.FrameCount; + ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); + ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize); + host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags); + + // Docking/Collapse button + if (has_window_menu_button) + { + if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node) + OpenPopup("#WindowMenu"); + if (IsItemActive()) + focus_tab_id = tab_bar->SelectedTabId; + if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f) + SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode)); + } + + // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value + int tabs_unsorted_start = tab_bar->Tabs.Size; + for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--) + { + // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? + tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted; + tabs_unsorted_start = tab_n; + } + if (tab_bar->Tabs.Size > tabs_unsorted_start) + { + IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); + for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + IM_UNUSED(tab); + IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1); + } + IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1); + if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) + ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); + } + + // Apply NavWindow focus back to the tab bar + if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node) + tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId; + + // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated + if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL) + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId; + else if (tab_bar->Tabs.Size > tabs_count_old) + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId; + + // Begin tab bar + ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons); + tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode; + tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyMixed; // Enforce default policy. Since 1.92.2 this is now reasonable. May expose later if needed. (#8800, #3421) + tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline; + if (!host_window->Collapsed && is_focused) + tab_bar_flags |= ImGuiTabBarFlags_IsFocused; + tab_bar->ID = node->ID;// GetID("#TabBar"); + tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width + tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize; + BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags); + //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)); + + // Backup style colors + ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT]; + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]]; + + // Submit actual tabs + node->VisibleWindow = NULL; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow* window = node->Windows[window_n]; + if (window->LastFrameActive + 1 < g.FrameCount && node_was_active) + continue; // FIXME: Not sure if that's still taken/useful, as windows are normally removed in DockNodeUpdateFlagsAndCollapse(). + + ImGuiTabItemFlags tab_item_flags = 0; + tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet; + if (window->Flags & ImGuiWindowFlags_UnsavedDocument) + tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument; + if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) + tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Apply stored style overrides for the window + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]); + + // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) + bool tab_open = true; + TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window); + if (!tab_open) + node->WantCloseTabId = window->TabId; + if (tab_bar->VisibleTabId == window->TabId) + node->VisibleWindow = window; + + // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call + window->DC.DockTabItemStatusFlags = g.LastItemData.StatusFlags; + window->DC.DockTabItemRect = g.LastItemData.Rect; + + // Update navigation ID on menu layer + if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) + host_window->NavLastIds[1] = window->TabId; + } + + // Restore style colors + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n]; + + // Notify root of visible window (used to display title in OS task bar) + if (node->VisibleWindow) + if (is_focused || root_node->VisibleWindow == NULL) + root_node->VisibleWindow = node->VisibleWindow; + + // Close button (after VisibleWindow was updated) + // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId + const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton; + const bool close_button_is_visible = node->HasCloseButton; + //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) + if (close_button_is_visible) + { + if (!close_button_is_enabled) + { + PushItemFlag(ImGuiItemFlags_Disabled, true); + PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f)); + } + if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos)) + { + node->WantCloseAll = true; + for (int n = 0; n < tab_bar->Tabs.Size; n++) + TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]); + } + //if (IsItemActive()) + // focus_tab_id = tab_bar->SelectedTabId; + if (!close_button_is_enabled) + { + PopStyleColor(); + PopItemFlag(); + } + } + + // When clicking on the title bar outside of tabs, we still focus the selected tab for that node + // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them. + ImGuiID title_bar_id = host_window->GetID("#TITLEBAR"); + if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) + { + // AllowOverlap mode required for appending into dock node tab bar, + // otherwise dragging window will steal HoveredId and amended tabs cannot get them. + bool held; + KeepAliveID(title_bar_id); + ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap); + if (g.HoveredId == title_bar_id) + { + g.LastItemData.ID = title_bar_id; + } + if (held) + { + if (IsMouseClicked(0)) + focus_tab_id = tab_bar->SelectedTabId; + + // Forward moving request to selected window + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space + } + } + + // Forward focus from host node to selected window + //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget) + // focus_tab_id = tab_bar->SelectedTabId; + + // When clicked on a tab we requested focus to the docked child + // This overrides the value set by "forward focus from host node to selected window". + if (tab_bar->NextSelectedTabId) + focus_tab_id = tab_bar->NextSelectedTabId; + + // Apply navigation focus + if (focus_tab_id != 0) + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id)) + if (tab->Window) + { + FocusWindow(tab->Window); + if (g.NavId == 0) // only init if FocusWindow() didn't restore anything. + NavInitWindow(tab->Window, false); + } + + EndTabBar(); + PopID(); + + // Restore SkipItems flag + if (!node->IsDockSpace()) + { + host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + host_window->SkipItems = backup_skip_item; + } +} + +static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node) +{ + IM_ASSERT(node->TabBar == NULL); + node->TabBar = IM_NEW(ImGuiTabBar); +} + +static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node) +{ + if (node->TabBar == NULL) + return; + IM_DELETE(node->TabBar); + node->TabBar = NULL; +} + +static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window) +{ + if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext) + return false; + + ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass; + ImGuiWindowClass* payload_class = &payload->WindowClass; + if (host_class->ClassId != payload_class->ClassId) + { + bool pass = false; + if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0) + pass = true; + if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0) + pass = true; + if (!pass) + return false; + } + + // Prevent docking any window created above a popup + // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), + // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test. + // But it would requires more work on our end because the dock host windows is technically created in NewFrame() + // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking. + ImGuiContext& g = *GImGui; + for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--) + if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window) + if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack. + return false; + + return true; +} + +static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload) +{ + if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering + return true; + + const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1; + for (int payload_n = 0; payload_n < payload_count; payload_n++) + { + ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload; + if (DockNodeIsDropAllowedOne(payload, host_window)) + return true; + } + return false; +} + +// window menu button == collapse button when not in a dock node. +// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. +static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + + ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); + if (out_title_rect) { *out_title_rect = r; } + + r.Min.x += style.WindowBorderSize; + r.Max.x -= style.WindowBorderSize; + + float button_sz = g.FontSize; + r.Min.x += style.FramePadding.x; + r.Max.x -= style.FramePadding.x; + ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y); + if (node->HasCloseButton) + { + if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y); + r.Max.x -= button_sz + style.ItemInnerSpacing.x; + } + if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left) + { + r.Min.x += button_sz + style.ItemInnerSpacing.x; + } + else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right) + { + window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y); + r.Max.x -= button_sz + style.ItemInnerSpacing.x; + } + if (out_tab_bar_rect) { *out_tab_bar_rect = r; } + if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; } +} + +void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired) +{ + ImGuiContext& g = *GImGui; + const float dock_spacing = g.Style.ItemInnerSpacing.x; + const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + pos_new[axis ^ 1] = pos_old[axis ^ 1]; + size_new[axis ^ 1] = size_old[axis ^ 1]; + + // Distribute size on given axis (with a desired size or equally) + const float w_avail = size_old[axis] - dock_spacing; + if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f) + { + size_new[axis] = size_new_desired[axis]; + size_old[axis] = IM_TRUNC(w_avail - size_new[axis]); + } + else + { + size_new[axis] = IM_TRUNC(w_avail * 0.5f); + size_old[axis] = IM_TRUNC(w_avail - size_new[axis]); + } + + // Position each node + if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) + { + pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing; + } + else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up) + { + pos_new[axis] = pos_old[axis]; + pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing; + } +} + +// Retrieve the drop rectangles for a given direction or for the center + perform hit testing. +bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos) +{ + ImGuiContext& g = *GImGui; + + const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight()); + const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f)); + float hs_w; // Half-size, longer axis + float hs_h; // Half-size, smaller axis + ImVec2 off; // Distance from edge or center + if (outer_docking) + { + //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f)); + //hs_h = ImTrunc(hs_w * 0.15f); + //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h)); + hs_w = ImTrunc(hs_for_central_nodes * 1.50f); + hs_h = ImTrunc(hs_for_central_nodes * 0.80f); + off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h)); + } + else + { + hs_w = ImTrunc(hs_for_central_nodes); + hs_h = ImTrunc(hs_for_central_nodes * 0.90f); + off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f)); + } + + ImVec2 c = ImTrunc(parent.GetCenter()); + if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); } + else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); } + else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); } + else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); } + else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); } + + if (test_mouse_pos == NULL) + return false; + + ImRect hit_r = out_r; + if (!outer_docking) + { + // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides + hit_r.Expand(ImTrunc(hs_w * 0.30f)); + ImVec2 mouse_delta = (*test_mouse_pos - c); + float mouse_delta_len2 = ImLengthSqr(mouse_delta); + float r_threshold_center = hs_w * 1.4f; + float r_threshold_sides = hs_w * (1.4f + 1.2f); + if (mouse_delta_len2 < r_threshold_center * r_threshold_center) + return (dir == ImGuiDir_None); + if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides) + return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y)); + } + return hit_r.Contains(*test_mouse_pos); +} + +// host_node may be NULL if the window doesn't have a DockNode already. +// FIXME-DOCK: This is misnamed since it's also doing the filtering. +static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking) +{ + ImGuiContext& g = *GImGui; + + // There is an edge case when docking into a dockspace which only has inactive nodes. + // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. + // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. + if (payload_node == NULL) + payload_node = payload_window->DockNodeAsHost; + ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node; + if (ref_node_for_rect) + IM_ASSERT(ref_node_for_rect->IsVisible == true); + + // Filter, figure out where we are allowed to dock + ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet; + ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet; + data->IsCenterAvailable = true; + if (is_outer_docking) + data->IsCenterAvailable = false; + else if (g.IO.ConfigDockingNoDockingOver) + data->IsCenterAvailable = false; + else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) + data->IsCenterAvailable = false; + else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode()) + data->IsCenterAvailable = false; + else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? + data->IsCenterAvailable = false; + else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty())) + data->IsCenterAvailable = false; + else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty()) + data->IsCenterAvailable = false; + + data->IsSidesAvailable = true; + if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit) + data->IsSidesAvailable = false; + else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) + data->IsSidesAvailable = false; + else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther) + data->IsSidesAvailable = false; + + // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) + data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton); + data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); + data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos; + data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size; + + // Calculate drop shapes geometry for allowed splitting directions + IM_ASSERT(ImGuiDir_None == -1); + data->SplitNode = host_node; + data->SplitDir = ImGuiDir_None; + data->IsSplitDirExplicit = false; + if (!host_window->Collapsed) + for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) + { + if (dir == ImGuiDir_None && !data->IsCenterAvailable) + continue; + if (dir != ImGuiDir_None && !data->IsSidesAvailable) + continue; + if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos)) + { + data->SplitDir = (ImGuiDir)dir; + data->IsSplitDirExplicit = true; + } + } + + // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar + data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable); + if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift) + data->IsDropAllowed = false; + + // Calculate split area + data->SplitRatio = 0.0f; + if (data->SplitDir != ImGuiDir_None) + { + ImGuiDir split_dir = data->SplitDir; + ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + ImVec2 pos_new, pos_old = data->FutureNode.Pos; + ImVec2 size_new, size_old = data->FutureNode.Size; + DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size); + + // Calculate split ratio so we can pass it down the docking request + float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]); + data->FutureNode.Pos = pos_new; + data->FutureNode.Size = size_new; + data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio); + } +} + +static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes + + // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. + // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. + const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload; + + // In case the two windows involved are on different viewports, we will draw the overlay on each of them. + int overlay_draw_lists_count = 0; + ImDrawList* overlay_draw_lists[2]; + overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport); + if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload) + overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport); + + // Draw main preview rectangle + const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f); + const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f); + const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f); + const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f); + + // Display area preview + const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0); + if (data->IsDropAllowed) + { + ImRect overlay_rect = data->FutureNode.Rect(); + if (data->SplitDir == ImGuiDir_None && can_preview_tabs) + overlay_rect.Min.y += GetFrameHeight(); + if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable) + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize)); + } + + // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) + if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable) + { + // Compute target tab bar geometry so we can locate our preview tabs + ImRect tab_bar_rect; + DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL); + ImVec2 tab_pos = tab_bar_rect.Min; + if (host_node && host_node->TabBar) + { + if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar()) + tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. + else + tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x; + } + else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost)) + { + tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar + } + + // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) + if (root_payload->DockNodeAsHost) + IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size); + ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL; + const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1; + for (int payload_n = 0; payload_n < payload_count; payload_n++) + { + // DockNode's TabBar may have non-window Tabs manually appended by user + ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload; + if (tab_bar_with_payload && payload_window == NULL) + continue; + if (!DockNodeIsDropAllowedOne(payload_window, host_window)) + continue; + + // Calculate the tab bounding box for each payload window + ImVec2 tab_size = TabItemCalcSize(payload_window); + ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y); + tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x; + const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]); + const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]); + const ImU32 overlay_col_unsaved_marker = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_UnsavedMarker]); + PushStyleColor(ImGuiCol_Text, overlay_col_text); + PushStyleColor(ImGuiCol_UnsavedMarker, overlay_col_unsaved_marker); + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + { + ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0; + if (!tab_bar_rect.Contains(tab_bb)) + overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max); + TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs); + TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL); + if (!tab_bar_rect.Contains(tab_bb)) + overlay_draw_lists[overlay_n]->PopClipRect(); + } + PopStyleColor(2); + } + } + + // Display drop boxes + const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding); + for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) + { + if (!data->DropRectsDraw[dir + 1].IsInverted()) + { + ImRect draw_r = data->DropRectsDraw[dir + 1]; + ImRect draw_r_in = draw_r; + draw_r_in.Expand(-2.0f); + ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop; + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + { + ImVec2 center = ImFloor(draw_r_in.GetCenter()); + overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding); + overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding); + if (dir == ImGuiDir_Left || dir == ImGuiDir_Right) + overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines); + if (dir == ImGuiDir_Up || dir == ImGuiDir_Down) + overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines); + } + } + + // Stop after ImGuiDir_None + if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit) + return; + } +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockNode Tree manipulation functions +//----------------------------------------------------------------------------- +// - DockNodeTreeSplit() +// - DockNodeTreeMerge() +// - DockNodeTreeUpdatePosSize() +// - DockNodeTreeUpdateSplitterFindTouchingNode() +// - DockNodeTreeUpdateSplitter() +// - DockNodeTreeFindFallbackLeafNode() +// - DockNodeTreeFindNodeByPos() +//----------------------------------------------------------------------------- + +void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(split_axis != ImGuiAxis_None); + + ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0); + child_0->ParentNode = parent_node; + + ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0); + child_1->ParentNode = parent_node; + + ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1; + DockNodeMoveChildNodes(child_inheritor, parent_node); + parent_node->ChildNodes[0] = child_0; + parent_node->ChildNodes[1] = child_1; + parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow; + parent_node->SplitAxis = split_axis; + parent_node->VisibleWindow = NULL; + parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; + + float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize); + size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); + IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. + child_0->SizeRef = child_1->SizeRef = parent_node->Size; + child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio); + child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]); + + DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); + DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID); + DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node)); + DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); + + // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property) + child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; + child_0->UpdateMergedFlags(); + child_1->UpdateMergedFlags(); + parent_node->UpdateMergedFlags(); + if (child_inheritor->IsCentralNode()) + DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor; +} + +void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child) +{ + // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL. + ImGuiContext& g = *GImGui; + ImGuiDockNode* child_0 = parent_node->ChildNodes[0]; + ImGuiDockNode* child_1 = parent_node->ChildNodes[1]; + IM_ASSERT(child_0 || child_1); + IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1); + if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0)) + { + IM_ASSERT(parent_node->TabBar == NULL); + IM_ASSERT(parent_node->Windows.Size == 0); + } + IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID); + + ImVec2 backup_last_explicit_size = parent_node->SizeRef; + DockNodeMoveChildNodes(parent_node, merge_lead_child); + if (child_0) + { + DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows + DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID); + } + if (child_1) + { + DockNodeMoveWindows(parent_node, child_1); + DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID); + } + DockNodeApplyPosSizeToWindows(parent_node); + parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto; + parent_node->VisibleWindow = merge_lead_child->VisibleWindow; + parent_node->SizeRef = backup_last_explicit_size; + + // Flags transfer + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag + parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows + parent_node->UpdateMergedFlags(); + + if (child_0) + DockContextDeleteNode(ctx, child_0); + if (child_1) + DockContextDeleteNode(ctx, child_1); +} + +// Update Pos/Size for a node hierarchy (don't affect child Windows yet) +// (Depth-first, Pre-Order) +void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node) +{ + // During the regular dock node update we write to all nodes. + // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. + ImGuiContext& g = *GImGui; + const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node; + if (write_to_node) + { + node->Pos = pos; + node->Size = size; + } + + if (node->IsLeafNode()) + return; + + ImGuiDockNode* child_0 = node->ChildNodes[0]; + ImGuiDockNode* child_1 = node->ChildNodes[1]; + ImVec2 child_0_pos = pos, child_1_pos = pos; + ImVec2 child_0_size = size, child_1_size = size; + + const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0)); + const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1)); + const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node; + const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node; + + if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible) + { + const float spacing = g.Style.DockingSeparatorSize; + const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; + const float size_avail = ImMax(size[axis] - spacing, 0.0f); + + // Size allocation policy + // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. + const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); + + // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. + // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc() + // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce + + // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) + if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) + { + child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); + child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) + { + child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) + { + // FIXME-DOCK: We cannot honor the requested size, so apply ratio. + // Currently this path will only be taken if code programmatically sets WantLockSizeOnce + float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio); + child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + + // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node + else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild) + { + child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]); + child_1_size[axis] = (size_avail - child_0_size[axis]); + } + else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild) + { + child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]); + child_0_size[axis] = (size_avail - child_1_size[axis]); + } + else + { + // 4) Otherwise distribute according to the relative ratio of each SizeRef value + float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]); + child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f)); + child_1_size[axis] = (size_avail - child_0_size[axis]); + } + + child_1_pos[axis] += spacing + child_0_size[axis]; + } + + if (only_write_to_single_node == NULL) + child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; + + const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible; + const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible; + if (child_0_recurse) + DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); + if (child_1_recurse) + DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size); +} + +static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector* touching_nodes) +{ + if (node->IsLeafNode()) + { + touching_nodes->push_back(node); + return; + } + if (node->ChildNodes[0]->IsVisible) + if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible) + DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes); + if (node->ChildNodes[1]->IsVisible) + if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible) + DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes); +} + +// (Depth-First, Pre-Order) +void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) +{ + if (node->IsLeafNode()) + return; + + ImGuiContext& g = *GImGui; + + ImGuiDockNode* child_0 = node->ChildNodes[0]; + ImGuiDockNode* child_1 = node->ChildNodes[1]; + if (child_0->IsVisible && child_1->IsVisible) + { + // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) + const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; + IM_ASSERT(axis != ImGuiAxis_None); + ImRect bb; + bb.Min = child_0->Pos; + bb.Max = child_1->Pos; + bb.Min[axis] += child_0->Size[axis]; + bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; + //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); + + const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs + const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; + if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) + { + ImGuiWindow* window = g.CurrentWindow; + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); + } + else + { + //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. + //bb.Max[axis] -= 1; + PushID(node->ID); + + // Find resizing limits by gathering list of nodes that are touching the splitter line. + ImVector touching_nodes[2]; + float min_size = g.Style.WindowMinSize[axis]; + float resize_limits[2]; + resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size; + resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size; + + ImGuiID splitter_id = GetID("##Splitter"); + if (g.ActiveId == splitter_id) // Only process when splitter is active + { + DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]); + DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]); + for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++) + resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size); + for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++) + resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size); + + // [DEBUG] Render touching nodes & limits + /* + ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + for (int n = 0; n < 2; n++) + { + for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++) + draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255)); + if (axis == ImGuiAxis_X) + draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); + else + draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); + } + */ + } + + // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters + float cur_size_0 = child_0->Size[axis]; + float cur_size_1 = child_1->Size[axis]; + float min_size_0 = resize_limits[0] - child_0->Pos[axis]; + float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1]; + ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg); + if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, g.WindowsBorderHoverPadding, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col)) + { + if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0) + { + child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0; + child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis]; + child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1; + + // Lock the size of every node that is a sibling of the node we are touching + // This might be less desirable if we can merge sibling of a same axis into the same parental level. + for (int side_n = 0; side_n < 2; side_n++) + for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) + { + ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n]; + //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255)); + while (touching_node->ParentNode != node) + { + if (touching_node->ParentNode->SplitAxis == axis) + { + // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). + ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n]; + node_to_preserve->WantLockSizeOnce = true; + //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255)); + //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100)); + } + touching_node = touching_node->ParentNode; + } + } + + DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size); + DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size); + MarkIniSettingsDirty(); + } + } + PopID(); + } + } + + if (child_0->IsVisible) + DockNodeTreeUpdateSplitter(child_0); + if (child_1->IsVisible) + DockNodeTreeUpdateSplitter(child_1); +} + +ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node) +{ + if (node->IsLeafNode()) + return node; + if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0])) + return leaf_node; + if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1])) + return leaf_node; + return NULL; +} + +ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos) +{ + if (!node->IsVisible) + return NULL; + + const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? + ImRect r(node->Pos, node->Pos + node->Size); + r.Expand(dock_spacing * 0.5f); + bool inside = r.Contains(pos); + if (!inside) + return NULL; + + if (node->IsLeafNode()) + return node; + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) + return hovered_node; + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) + return hovered_node; + + // This means we are hovering over the splitter/spacing of a parent node + return node; +} + +//----------------------------------------------------------------------------- +// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +//----------------------------------------------------------------------------- +// - SetWindowDock() [Internal] +// - DockSpace() +// - DockSpaceOverViewport() +//----------------------------------------------------------------------------- + +// [Internal] Called via SetNextWindowDockID() +void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowDockAllowFlags & cond) == 0) + return; + window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + if (window->DockId == dock_id) + return; + + // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot + ImGuiContext& g = *GImGui; + if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id)) + if (new_node->IsSplitNode()) + { + // Policy: Find central node or latest focused node. We first move back to our root node. + new_node = DockNodeGetRootNode(new_node); + if (new_node->CentralNode) + { + IM_ASSERT(new_node->CentralNode->IsCentralNode()); + dock_id = new_node->CentralNode->ID; + } + else + { + dock_id = new_node->LastFocusedNodeId; + } + } + + if (window->DockId == dock_id) + return; + + if (window->DockNode) + DockNodeRemoveWindow(window->DockNode, window, 0); + window->DockId = dock_id; +} + +// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. +// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. +// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. +// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location). +ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return 0; + + // Early out if parent window is hidden/collapsed + // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. + // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. + if (window->SkipItems) + flags |= ImGuiDockNodeFlags_KeepAliveOnly; + if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0) + window = GetCurrentWindow(); // call to set window->WriteAccessed = true; + + IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! + IM_ASSERT((flags & ImGuiDockNodeFlags_CentralNode) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145) + + IM_ASSERT(dockspace_id != 0); + ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id); + if (node == NULL) + { + IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id); + node = DockContextAddNode(&g, dockspace_id); + node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode); + } + if (window_class && window_class->ClassId != node->WindowClass.ClassId) + IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId); + node->SharedFlags = flags; + node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); + + // When a DockSpace transitioned form implicit to explicit this may be called a second time + // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. + if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) + { + IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); + return dockspace_id; + } + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); + + // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible + if (flags & ImGuiDockNodeFlags_KeepAliveOnly) + { + node->LastFrameAlive = g.FrameCount; + return dockspace_id; + } + + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImTrunc(size_arg); + if (size.x <= 0.0f) + size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) + if (size.y <= 0.0f) + size.y = ImMax(content_avail.y + size.y, 4.0f); + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); + + node->Pos = window->DC.CursorPos; + node->Size = node->SizeRef = size; + SetNextWindowPos(node->Pos); + SetNextWindowSize(node->Size); + g.NextWindowData.PosUndock = false; + + // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? + // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) + ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost; + window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; + window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + window_flags |= ImGuiWindowFlags_NoBackground; + + char title[256]; + ImFormatString(title, IM_COUNTOF(title), "%s/DockSpace_%08X", window->Name, dockspace_id); + + PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); + Begin(title, NULL, window_flags); + PopStyleVar(); + + ImGuiWindow* host_window = g.CurrentWindow; + DockNodeSetupHostWindow(node, host_window); + host_window->ChildId = window->GetID(title); + node->OnlyNodeWithWindows = NULL; + + IM_ASSERT(node->IsRootNode()); + + // We need to handle the rare case were a central node is missing. + // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. + // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + // as it doesn't make sense for an empty dockspace to not have this property. + if (node->IsLeafNode() && !node->IsCentralNode()) + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + + // Update the node + DockNodeUpdate(node); + + End(); + + ImRect bb(node->Pos, node->Pos + size); + ItemSize(size); + ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?) + if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild() + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + + return dockspace_id; +} + +// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! +// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar(). +// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. +// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. +ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class) +{ + if (viewport == NULL) + viewport = GetMainViewport(); + + // Submit a window filling the entire viewport + SetNextWindowPos(viewport->WorkPos); + SetNextWindowSize(viewport->WorkSize); + SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags host_window_flags = 0; + host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; + host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; + if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) + host_window_flags |= ImGuiWindowFlags_NoBackground; + + // FIXME-OPT: When using ImGuiDockNodeFlags_KeepAliveOnly with DockSpaceOverViewport() we might be able to spare submitting the window, + // since DockSpace() with that flag doesn't need a window. We'd only need to compute the default ID accordingly. + if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly) + host_window_flags |= ImGuiWindowFlags_NoMouseInputs; + + char label[32]; + ImFormatString(label, IM_COUNTOF(label), "WindowOverViewport_%08X", viewport->ID); + + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + Begin(label, NULL, host_window_flags); + PopStyleVar(3); + + // Submit the dockspace + if (dockspace_id == 0) + dockspace_id = GetID("DockSpace"); + DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class); + + End(); + + return dockspace_id; +} + +//----------------------------------------------------------------------------- +// Docking: Builder Functions +//----------------------------------------------------------------------------- +// Very early end-user API to manipulate dock nodes. +// Only available in imgui_internal.h. Expect this API to change/break! +// It is expected that those functions are all called _before_ the dockspace node submission. +//----------------------------------------------------------------------------- +// - DockBuilderDockWindow() +// - DockBuilderGetNode() +// - DockBuilderSetNodePos() +// - DockBuilderSetNodeSize() +// - DockBuilderAddNode() +// - DockBuilderRemoveNode() +// - DockBuilderRemoveNodeChildNodes() +// - DockBuilderRemoveNodeDockedWindows() +// - DockBuilderSplitNode() +// - DockBuilderCopyNodeRec() +// - DockBuilderCopyNode() +// - DockBuilderCopyWindowSettings() +// - DockBuilderCopyDockSpace() +// - DockBuilderFinish() +//----------------------------------------------------------------------------- + +void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id) +{ + // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) + ImGuiContext& g = *GImGui; IM_UNUSED(g); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id); + ImGuiID window_id = ImHashStr(window_name); + if (ImGuiWindow* window = FindWindowByID(window_id)) + { + // Apply to created window + ImGuiID prev_node_id = window->DockId; + SetWindowDock(window, node_id, ImGuiCond_Always); + if (window->DockId != prev_node_id) + window->DockOrder = -1; + } + else + { + // Apply to settings + ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id); + if (settings == NULL) + settings = CreateNewWindowSettings(window_name); + if (settings->DockId != node_id) + settings->DockOrder = -1; + settings->DockId = node_id; + } +} + +ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id) +{ + ImGuiContext& g = *GImGui; + return DockContextFindNodeByID(&g, node_id); +} + +void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos) +{ + ImGuiContext& g = *GImGui; + ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); + if (node == NULL) + return; + node->Pos = pos; + node->AuthorityForPos = ImGuiDataAuthority_DockNode; +} + +void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) +{ + ImGuiContext& g = *GImGui; + ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); + if (node == NULL) + return; + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); + node->Size = node->SizeRef = size; + node->AuthorityForSize = ImGuiDataAuthority_DockNode; +} + +// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +// - Use (id == 0) to let the system allocate a node identifier. +// - Existing node with a same id will be removed. +ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags) +{ + ImGuiContext& g = *GImGui; IM_UNUSED(g); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags); + + if (node_id != 0) + DockBuilderRemoveNode(node_id); + + ImGuiDockNode* node = NULL; + if (flags & ImGuiDockNodeFlags_DockSpace) + { + DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); + node = DockContextFindNodeByID(&g, node_id); + } + else + { + node = DockContextAddNode(&g, node_id); + node->SetLocalFlags(flags); + } + node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame. + return node->ID; +} + +void ImGui::DockBuilderRemoveNode(ImGuiID node_id) +{ + ImGuiContext& g = *GImGui; IM_UNUSED(g); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id); + + ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); + if (node == NULL) + return; + DockBuilderRemoveNodeDockedWindows(node_id, true); + DockBuilderRemoveNodeChildNodes(node_id); + // Node may have moved or deleted if e.g. any merge happened + node = DockContextFindNodeByID(&g, node_id); + if (node == NULL) + return; + if (node->IsCentralNode() && node->ParentNode) + node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode); + DockContextRemoveNode(&g, node, true); +} + +// root_id = 0 to remove all, root_id != 0 to remove child of given node. +void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) +{ + ImGuiContext& g = *GImGui; + ImGuiDockContext* dc = &g.DockContext; + + ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL; + if (root_id && root_node == NULL) + return; + bool has_central_node = false; + + ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto; + ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto; + + // Process active windows + ImVector nodes_to_remove; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + { + bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id); + if (want_removal) + { + if (node->IsCentralNode()) + has_central_node = true; + if (root_id != 0) + DockContextQueueNotifyRemovedNode(&g, node); + if (root_node) + { + DockNodeMoveWindows(root_node, node); + DockSettingsRenameNodeReferences(node->ID, root_node->ID); + } + nodes_to_remove.push_back(node); + } + } + + // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) + // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) + if (root_node) + { + root_node->AuthorityForPos = backup_root_node_authority_for_pos; + root_node->AuthorityForSize = backup_root_node_authority_for_size; + } + + // Apply to settings + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (ImGuiID window_settings_dock_id = settings->DockId) + for (int n = 0; n < nodes_to_remove.Size; n++) + if (nodes_to_remove[n]->ID == window_settings_dock_id) + { + settings->DockId = root_id; + break; + } + + // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes + if (nodes_to_remove.Size > 1) + ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst); + for (int n = 0; n < nodes_to_remove.Size; n++) + DockContextRemoveNode(&g, nodes_to_remove[n], false); + + if (root_id == 0) + { + dc->Nodes.Clear(); + dc->Requests.clear(); + } + else if (has_central_node) + { + root_node->CentralNode = root_node; + root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + } +} + +void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) +{ + // Clear references in settings + ImGuiContext& g = *GImGui; + if (clear_settings_refs) + { + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + { + bool want_removal = (root_id == 0) || (settings->DockId == root_id); + if (!want_removal && settings->DockId != 0) + if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId)) + if (DockNodeGetRootNode(node)->ID == root_id) + want_removal = true; + if (want_removal) + settings->DockId = 0; + } + } + + // Clear references in windows + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow* window = g.Windows[n]; + bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id); + if (want_removal) + { + const ImGuiID backup_dock_id = window->DockId; + IM_UNUSED(backup_dock_id); + DockContextProcessUndockWindow(&g, window, clear_settings_refs); + if (!clear_settings_refs) + IM_ASSERT(window->DockId == backup_dock_id); + } + } +} + +// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created. +// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set. +// FIXME-DOCK: We are not exposing nor using split_outer. +ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(split_dir != ImGuiDir_None); + IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir); + + ImGuiDockNode* node = DockContextFindNodeByID(&g, id); + if (node == NULL) + { + IM_ASSERT(node != NULL); + return 0; + } + + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Split; + req.DockTargetWindow = NULL; + req.DockTargetNode = node; + req.DockPayload = NULL; + req.DockSplitDir = split_dir; + req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir); + req.DockSplitOuter = false; + DockContextProcessDock(&g, &req); + + ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID; + ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; + if (out_id_at_dir) + *out_id_at_dir = id_at_dir; + if (out_id_at_opposite_dir) + *out_id_at_opposite_dir = id_at_opposite_dir; + return id_at_dir; +} + +static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector* out_node_remap_pairs) +{ + ImGuiContext& g = *GImGui; + ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known); + dst_node->SharedFlags = src_node->SharedFlags; + dst_node->LocalFlags = src_node->LocalFlags; + dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; + dst_node->Pos = src_node->Pos; + dst_node->Size = src_node->Size; + dst_node->SizeRef = src_node->SizeRef; + dst_node->SplitAxis = src_node->SplitAxis; + dst_node->UpdateMergedFlags(); + + out_node_remap_pairs->push_back(src_node->ID); + out_node_remap_pairs->push_back(dst_node->ID); + + for (int child_n = 0; child_n < IM_COUNTOF(src_node->ChildNodes); child_n++) + if (src_node->ChildNodes[child_n]) + { + dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs); + dst_node->ChildNodes[child_n]->ParentNode = dst_node; + } + + IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); + return dst_node; +} + +void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(src_node_id != 0); + IM_ASSERT(dst_node_id != 0); + IM_ASSERT(out_node_remap_pairs != NULL); + + DockBuilderRemoveNode(dst_node_id); + + ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id); + IM_ASSERT(src_node != NULL); + + out_node_remap_pairs->clear(); + DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs); + + IM_ASSERT((out_node_remap_pairs->Size % 2) == 0); +} + +void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name) +{ + ImGuiWindow* src_window = FindWindowByName(src_name); + if (src_window == NULL) + return; + if (ImGuiWindow* dst_window = FindWindowByName(dst_name)) + { + dst_window->Pos = src_window->Pos; + dst_window->Size = src_window->Size; + dst_window->SizeFull = src_window->SizeFull; + dst_window->Collapsed = src_window->Collapsed; + } + else + { + ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name)); + if (!dst_settings) + dst_settings = CreateNewWindowSettings(dst_name); + ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos); + if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID) + { + dst_settings->ViewportPos = window_pos_2ih; + dst_settings->ViewportId = src_window->ViewportId; + dst_settings->Pos = ImVec2ih(0, 0); + } + else + { + dst_settings->Pos = window_pos_2ih; + } + dst_settings->Size = ImVec2ih(src_window->SizeFull); + dst_settings->Collapsed = src_window->Collapsed; + } +} + +// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. +void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(src_dockspace_id != 0); + IM_ASSERT(dst_dockspace_id != 0); + IM_ASSERT(in_window_remap_pairs != NULL); + IM_ASSERT((in_window_remap_pairs->Size % 2) == 0); + + // Duplicate entire dock + // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, + // whereas we could attempt to at least keep them together in a new, same floating node. + ImVector node_remap_pairs; + DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs); + + // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes + // (The windows associated to src_dockspace_id are staying in place) + ImVector src_windows; + for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2) + { + const char* src_window_name = (*in_window_remap_pairs)[remap_window_n]; + const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1]; + ImGuiID src_window_id = ImHashStr(src_window_name); + src_windows.push_back(src_window_id); + + // Search in the remapping tables + ImGuiID src_dock_id = 0; + if (ImGuiWindow* src_window = FindWindowByID(src_window_id)) + src_dock_id = src_window->DockId; + else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id)) + src_dock_id = src_window_settings->DockId; + ImGuiID dst_dock_id = 0; + for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) + if (node_remap_pairs[dock_remap_n] == src_dock_id) + { + dst_dock_id = node_remap_pairs[dock_remap_n + 1]; + //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear + break; + } + + if (dst_dock_id != 0) + { + // Docked windows gets redocked into the new node hierarchy. + IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id); + DockBuilderDockWindow(dst_window_name, dst_dock_id); + } + else + { + // Floating windows gets their settings transferred (regardless of whether the new window already exist or not) + // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? + IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name); + DockBuilderCopyWindowSettings(src_window_name, dst_window_name); + } + } + + // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list. + // Find those windows and move to them to the cloned dock node. This may be optional? + // Dock those are a second step as undocking would invalidate source dock nodes. + struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } }; + ImVector dock_remaining_windows; + for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) + if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n]) + { + ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1]; + ImGuiDockNode* node = DockBuilderGetNode(src_dock_id); + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow* window = node->Windows[window_n]; + if (src_windows.contains(window->ID)) + continue; + + // Docked windows gets redocked into the new node hierarchy. + IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); + dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id)); + } + } + for (const DockRemainingWindowTask& task : dock_remaining_windows) + DockBuilderDockWindow(task.Window->Name, task.DockId); +} + +// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. +void ImGui::DockBuilderFinish(ImGuiID root_id) +{ + ImGuiContext& g = *GImGui; + //DockContextRebuild(&g); + DockContextBuildAddWindowsToNodes(&g, root_id); +} + +//----------------------------------------------------------------------------- +// Docking: Begin/End Support Functions (called from Begin/End) +//----------------------------------------------------------------------------- +// - GetWindowAlwaysWantOwnTabBar() +// - DockContextBindNodeToWindow() +// - BeginDocked() +// - BeginDockableDragDropSource() +// - BeginDockableDragDropTarget() +//----------------------------------------------------------------------------- + +bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) + if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise + return true; + return false; +} + +static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window) +{ + ImGuiContext& g = *ctx; + ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); + IM_ASSERT(window->DockNode == NULL); + + // We should not be docking into a split node (SetWindowDock should avoid this) + if (node && node->IsSplitNode()) + { + DockContextProcessUndockWindow(ctx, window); + return NULL; + } + + // Create node + if (node == NULL) + { + node = DockContextAddNode(ctx, window->DockId); + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; + node->LastFrameAlive = g.FrameCount; + } + + // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. + if (!node->IsVisible) + { + ImGuiDockNode* ancestor_node = node; + while (!ancestor_node->IsVisible && ancestor_node->ParentNode) + ancestor_node = ancestor_node->ParentNode; + IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); + DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node)); + DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node); + } + + // Add window to node + bool node_was_visible = node->IsVisible; + DockNodeAddWindow(node, window, true); + node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) + IM_ASSERT(node == window->DockNode); + return node; +} + +static void StoreDockStyleForWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); +} + +void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) +{ + ImGuiContext& g = *GImGui; + + // Specific extra processing for fallback window (#9151), could be in Begin() as well. + if (window->IsFallbackWindow && !window->WasActive) + { + DockNodeHideWindowDuringHostWindowCreation(window); + return; + } + + const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window); + if (auto_dock_node) + { + if (window->DockId == 0) + { + IM_ASSERT(window->DockNode == NULL); + window->DockId = DockContextGenNodeID(&g); + } + } + else + { + // Calling SetNextWindowPos() undock windows by default (by setting PosUndock) + bool want_undock = false; + want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0; + want_undock |= (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock; + if (want_undock) + { + DockContextProcessUndockWindow(&g, window); + return; + } + } + + // Bind to our dock node + ImGuiDockNode* node = window->DockNode; + if (node != NULL) + IM_ASSERT(window->DockId == node->ID); + if (window->DockId != 0 && node == NULL) + { + node = DockContextBindNodeToWindow(&g, window); + if (node == NULL) + return; + } + +#if 0 + // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set + if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode)) + { + DockContextProcessUndockWindow(ctx, window); + return; + } +#endif + + // Undock if our dockspace node disappeared + // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly. + if (node->LastFrameAlive < g.FrameCount) + { + // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() + ImGuiDockNode* root_node = DockNodeGetRootNode(node); + if (root_node->LastFrameAlive < g.FrameCount) + DockContextProcessUndockWindow(&g, window); + else + window->DockIsActive = true; + return; + } + + // Store style overrides + StoreDockStyleForWindow(window); + + // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + // and never create neither a host window neither a tab bar. + // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) + if (node->HostWindow == NULL) + { + if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing) + window->DockIsActive = true; + if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window + DockNodeHideWindowDuringHostWindowCreation(window); + return; + } + + // We can have zero-sized nodes (e.g. children of a small-size dockspace) + IM_ASSERT(node->HostWindow); + IM_ASSERT(node->IsLeafNode()); + IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f); + node->State = ImGuiDockNodeState_HostWindowVisible; + + // Undock if we are submitted earlier than the host window + if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) + { + DockContextProcessUndockWindow(&g, window); + return; + } + + // Position/Size window + SetNextWindowPos(node->Pos); + SetNextWindowSize(node->Size); + g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() + window->DockIsActive = true; + window->DockNodeIsVisible = true; + window->DockTabIsVisible = false; + if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) + return; + + // When the window is selected we mark it as visible. + if (node->VisibleWindow == window) + window->DockTabIsVisible = true; + + // Update window flag + IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); + window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize; + window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding; + if (node->IsHiddenTabBar() || node->IsNoTabBar()) + window->Flags |= ImGuiWindowFlags_NoTitleBar; + else + window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! + + // Save new dock order only if the window has been visible once already + // This allows multiple windows to be created in the same frame and have their respective dock orders preserved. + if (node->TabBar && window->WasActive) + window->DockOrder = (short)DockNodeGetTabOrder(window); + + if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL) + *p_open = false; + + // Update ChildId to allow returning from Child to Parent with Escape + ImGuiWindow* parent_window = window->DockNode->HostWindow; + window->ChildId = parent_window->GetID(window->Name); +} + +void ImGui::BeginDockableDragDropSource(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.ActiveId == window->MoveId); + IM_ASSERT(g.MovingWindow == window); + IM_ASSERT(g.CurrentWindow == window); + + // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking. + if (g.IO.ConfigDockingWithShift != g.IO.KeyShift) + { + // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance. + // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active + // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function) + IM_ASSERT(g.NextWindowData.HasFlags == 0); + if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f) + SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock)); + return; + } + + g.LastItemData.ID = window->MoveId; + window = window->RootWindowDockTree; + IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); + bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit + ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess; + if (is_drag_docking && BeginDragDropSource(drag_drop_flags)) + { + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window)); + EndDragDropSource(); + StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it. + } +} + +void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace + IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); + if (!g.DragDropActive) + return; + //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) + return; + + // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering + // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) + const ImGuiPayload* payload = &g.DragDropPayload; + if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data)) + { + EndDragDropTarget(); + return; + } + + ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data; + if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + // Select target node + // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) + bool dock_into_floating_window = false; + ImGuiDockNode* node = NULL; + if (window->DockNodeAsHost) + { + // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + + // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + if (node && node->IsDockSpace() && node->IsRootNode()) + node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); + } + else + { + if (window->DockNode) + node = window->DockNode; + else + dock_into_floating_window = true; // Dock into a regular window + } + + const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); + const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); + + // Preview docking request and find out split direction/ratio + //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. + const bool do_preview = payload->IsPreview() || payload->IsDelivery(); + if (do_preview && (node != NULL || dock_into_floating_window)) + { + // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear. + ImGuiDockPreviewData split_inner; + ImGuiDockPreviewData split_outer; + ImGuiDockPreviewData* split_data = &split_inner; + if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode())) + if (ImGuiDockNode* root_node = DockNodeGetRootNode(node)) + { + DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true); + if (split_outer.IsSplitDirExplicit) + split_data = &split_outer; + } + if (!node || node->IsLeafNode()) + DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false); + if (split_data == &split_outer) + split_inner.IsDropAllowed = false; + + // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes + DockNodePreviewDockRender(window, node, payload_window, &split_inner); + DockNodePreviewDockRender(window, node, payload_window, &split_outer); + + // Queue docking request + if (split_data->IsDropAllowed && payload->IsDelivery()) + DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer); + } + } + EndDragDropTarget(); +} + +//----------------------------------------------------------------------------- +// Docking: Settings +//----------------------------------------------------------------------------- +// - DockSettingsRenameNodeReferences() +// - DockSettingsRemoveNodeReferences() +// - DockSettingsFindNodeSettings() +// - DockSettingsHandler_ApplyAll() +// - DockSettingsHandler_ReadOpen() +// - DockSettingsHandler_ReadLine() +// - DockSettingsHandler_DockNodeToSettings() +// - DockSettingsHandler_WriteAll() +//----------------------------------------------------------------------------- + +static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) +{ + ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id); + for (int window_n = 0; window_n < g.Windows.Size; window_n++) + { + ImGuiWindow* window = g.Windows[window_n]; + if (window->DockId == old_node_id && window->DockNode == NULL) + window->DockId = new_node_id; + } + //// FIXME-OPT: We could remove this loop by storing the index in the map + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId == old_node_id) + settings->DockId = new_node_id; +} + +// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings +static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count) +{ + ImGuiContext& g = *GImGui; + int found = 0; + //// FIXME-OPT: We could remove this loop by storing the index in the map + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + for (int node_n = 0; node_n < node_ids_count; node_n++) + if (settings->DockId == node_ids[node_n]) + { + settings->DockId = 0; + settings->DockOrder = -1; + if (++found < node_ids_count) + break; + return; + } +} + +static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) +{ + // FIXME-OPT + ImGuiDockContext* dc = &ctx->DockContext; + for (int n = 0; n < dc->NodesSettings.Size; n++) + if (dc->NodesSettings[n].ID == id) + return &dc->NodesSettings[n]; + return NULL; +} + +// Clear settings data +static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiDockContext* dc = &ctx->DockContext; + dc->NodesSettings.clear(); + DockContextClearNodes(ctx, 0, true); +} + +// Recreate nodes based on settings data +static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + // Prune settings at boot time only + ImGuiDockContext* dc = &ctx->DockContext; + if (ctx->Windows.Size == 0) + DockContextPruneUnusedSettingsNodes(ctx); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); + DockContextBuildAddWindowsToNodes(ctx, 0); +} + +static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + if (strcmp(name, "Data") != 0) + return NULL; + return (void*)1; +} + +static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line) +{ + char c = 0; + int x = 0, y = 0; + int r = 0; + + // Parsing, e.g. + // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " + // " DockNode ID=0x00000002 Parent=0x00000001 " + // Important: this code expect currently fields in a fixed order. + ImGuiDockNodeSettings node; + line = ImStrSkipBlank(line); + if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); } + else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; } + else return; + if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; + if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; } + if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; } + if (node.ParentNodeId == 0) + { + if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return; + if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return; + } + else + { + if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); } + } + if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; } + if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; } + if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; } + if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; } + if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } + if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } + if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } + if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; } + if (node.ParentNodeId != 0) + if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) + node.Depth = parent_settings->Depth + 1; + ctx->DockContext.NodesSettings.push_back(node); +} + +static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth) +{ + ImGuiDockNodeSettings node_settings; + IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); + node_settings.ID = node->ID; + node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0; + node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0; + node_settings.SelectedTabId = node->SelectedTabId; + node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None); + node_settings.Depth = (char)depth; + node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); + node_settings.Pos = ImVec2ih(node->Pos); + node_settings.Size = ImVec2ih(node->Size); + node_settings.SizeRef = ImVec2ih(node->SizeRef); + dc->NodesSettings.push_back(node_settings); + if (node->ChildNodes[0]) + DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); + if (node->ChildNodes[1]) + DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1); +} + +static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + ImGuiContext& g = *ctx; + ImGuiDockContext* dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return; + + // Gather settings data + // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) + dc->NodesSettings.resize(0); + dc->NodesSettings.reserve(dc->Nodes.Data.Size); + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->IsRootNode()) + DockSettingsHandler_DockNodeToSettings(dc, node, 0); + + int max_depth = 0; + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); + + // Write to text buffer + buf->appendf("[%s][Data]\n", handler->TypeName); + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + { + const int line_start_pos = buf->size(); (void)line_start_pos; + const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n]; + buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file + buf->appendf(" ID=0x%08X", node_settings->ID); + if (node_settings->ParentNodeId) + { + buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y); + } + else + { + if (node_settings->ParentWindowId) + buf->appendf(" Window=0x%08X", node_settings->ParentWindowId); + buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); + } + if (node_settings->SplitAxis != ImGuiAxis_None) + buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); + if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) + buf->appendf(" NoResize=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) + buf->appendf(" CentralNode=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) + buf->appendf(" NoTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar) + buf->appendf(" HiddenTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton) + buf->appendf(" NoWindowMenuButton=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) + buf->appendf(" NoCloseButton=1"); + if (node_settings->SelectedTabId) + buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId); + + // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!) + if (g.IO.ConfigDebugIniSettings) + if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID)) + { + buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything + if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) + buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); + // Iterate settings so we can give info about windows that didn't exist during the session. + int contains_window = 0; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId == node_settings->ID) + { + if (contains_window++ == 0) + buf->appendf(" ; contains "); + buf->appendf("'%s' ", settings->GetName()); + } + } + + buf->appendf("\n"); + } + buf->appendf("\n"); +} + + +//----------------------------------------------------------------------------- +// [SECTION] PLATFORM DEPENDENT HELPERS +//----------------------------------------------------------------------------- +// - Default clipboard handlers +// - Default shell function handlers +// - Default IME handlers +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#pragma comment(lib, "kernel32") +#endif + +// Win32 clipboard implementation +// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown() +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + g.ClipboardHandlerData.clear(); + if (!::OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return NULL; + } + if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle)) + { + int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL); + g.ClipboardHandlerData.resize(buf_len); + ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL); + } + ::GlobalUnlock(wbuf_handle); + ::CloseClipboard(); + return g.ClipboardHandlerData.Data; +} + +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text) +{ + if (!::OpenClipboard(NULL)) + return; + const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0); + HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR)); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return; + } + WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle); + ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length); + ::GlobalUnlock(wbuf_handle); + ::EmptyClipboard(); + if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) + ::GlobalFree(wbuf_handle); + ::CloseClipboard(); +} + +#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS) + +#include // Use old API to avoid need for separate .mm file +static PasteboardRef main_clipboard = 0; + +// OSX clipboard implementation +// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line! +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text) +{ + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardClear(main_clipboard); + CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text)); + if (cf_data) + { + PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0); + CFRelease(cf_data); + } +} + +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardSynchronize(main_clipboard); + + ItemCount item_count = 0; + PasteboardGetItemCount(main_clipboard, &item_count); + for (ItemCount i = 0; i < item_count; i++) + { + PasteboardItemID item_id = 0; + PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id); + CFArrayRef flavor_type_array = 0; + PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array); + for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++) + { + CFDataRef cf_data; + if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr) + { + g.ClipboardHandlerData.clear(); + int length = (int)CFDataGetLength(cf_data); + g.ClipboardHandlerData.resize(length + 1); + CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data); + g.ClipboardHandlerData[length] = 0; + CFRelease(cf_data); + return g.ClipboardHandlerData.Data; + } + } + } + return NULL; +} + +#else + +// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers. +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) +{ + ImGuiContext& g = *ctx; + return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin(); +} + +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text) +{ + ImGuiContext& g = *ctx; + g.ClipboardHandlerData.clear(); + const char* text_end = text + ImStrlen(text); + g.ClipboardHandlerData.resize((int)(text_end - text) + 1); + memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text)); + g.ClipboardHandlerData[(int)(text_end - text)] = 0; +} + +#endif // Default clipboard handlers + +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#if defined(__APPLE__) && TARGET_OS_IPHONE +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif +#if defined(__3DS__) +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif +#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif +#endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS + +#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#ifdef _WIN32 +#include // ShellExecuteA() +#ifdef _MSC_VER +#pragma comment(lib, "shell32") +#endif +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +{ + const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0); + ImVector path_wbuf; + path_wbuf.resize(path_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize); + return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32; +} +#else +#include +#include +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +{ +#if defined(__APPLE__) + const char* args[] { "open", "--", path, NULL }; +#else + const char* args[] { "xdg-open", path, NULL }; +#endif + pid_t pid = fork(); + if (pid < 0) + return false; + if (!pid) + { + execvp(args[0], const_cast(args)); + exit(-1); + } + else + { + int status; + waitpid(pid, &status, 0); + return WEXITSTATUS(status) == 0; + } +} +#endif +#else +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; } +#endif // Default shell handlers + +//----------------------------------------------------------------------------- + +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) + +#include +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif + +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) +{ + // Notify OS Input Method Editor of text input position + HWND hwnd = (HWND)viewport->PlatformHandleRaw; + if (hwnd == 0) + return; + + //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0); + if (HIMC himc = ::ImmGetContext(hwnd)) + { + COMPOSITIONFORM composition_form = {}; + composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); + composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + composition_form.dwStyle = CFS_FORCE_POSITION; + ::ImmSetCompositionWindow(himc, &composition_form); + CANDIDATEFORM candidate_form = {}; + candidate_form.dwStyle = CFS_CANDIDATEPOS; + candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); + candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + ::ImmSetCandidateWindow(himc, &candidate_form); + ::ImmReleaseContext(hwnd, himc); + } +} + +#else + +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {} + +#endif // Default IME handlers + +//----------------------------------------------------------------------------- +// [SECTION] METRICS/DEBUGGER WINDOW +//----------------------------------------------------------------------------- +// - MetricsHelpMarker() [Internal] +// - DebugRenderViewportThumbnail() [Internal] +// - RenderViewportsThumbnails() [Internal] +// - DebugRenderKeyboardPreview() [Internal] +// - DebugTextEncoding() +// - DebugFlashStyleColorStop() [Internal] +// - DebugFlashStyleColor() +// - UpdateDebugToolFlashStyleColor() [Internal] +// - ShowFontAtlas() [Internal but called by Demo!] +// - DebugNodeTexture() [Internal] +// - ShowMetricsWindow() +// - DebugNodeColumns() [Internal] +// - DebugNodeDockNode() [Internal] +// - DebugNodeDrawList() [Internal] +// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] +// - DebugNodeFont() [Internal] +// - DebugNodeFontGlyph() [Internal] +// - DebugNodeStorage() [Internal] +// - DebugNodeTabBar() [Internal] +// - DebugNodeViewport() [Internal] +// - DebugNodeWindow() [Internal] +// - DebugNodeWindowSettings() [Internal] +// - DebugNodeWindowsList() [Internal] +// - DebugNodeWindowsListByBeginStackParent() [Internal] +// - ShowFontSelector() +//----------------------------------------------------------------------------- + +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) +// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. +static void MetricsHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::BeginItemTooltip()) + { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} +#endif + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + +void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + ImVec2 scale = bb.GetSize() / viewport->Size; + ImVec2 off = bb.Min - viewport->Pos * scale; + float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f; + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f)); + for (ImGuiWindow* thumb_window : g.Windows) + { + if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) + continue; + if (thumb_window->Viewport != viewport) + continue; + + ImRect thumb_r = thumb_window->Rect(); + ImRect title_r = thumb_window->TitleBarRect(); + thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale)); + title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height + thumb_r.ClipWithFull(bb); + title_r.ClipWithFull(bb); + const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight); + window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul)); + window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul)); + window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); + window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name)); + } + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); + if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID) + window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); +} + +static void RenderViewportsThumbnails() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Draw monitor and calculate their boundaries + float SCALE = 1.0f / 8.0f; + ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) + bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize)); + ImVec2 p = window->DC.CursorPos; + ImVec2 off = p - bb_full.Min * SCALE; + for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) + { + ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE); + window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f); + window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f); + } + + // Draw viewports + for (ImGuiViewportP* viewport : g.Viewports) + { + ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE); + ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb); + } + ImGui::Dummy(bb_full.GetSize() * SCALE); +} + +static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs) +{ + const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs; + const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs; + return b->LastFocusedStampCount - a->LastFocusedStampCount; +} + +// Draw an arbitrary US keyboard layout to visualize translated keys +void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list) +{ + const float scale = ImGui::GetFontSize() / 13.0f; + const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale; + const float key_rounding = 3.0f * scale; + const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale; + const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale; + const float key_face_rounding = 2.0f * scale; + const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale; + const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f); + const float key_row_offset = 9.0f * scale; + + ImVec2 board_min = GetCursorScreenPos(); + ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f); + ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y); + + struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; }; + const KeyLayoutData keys_to_display[] = + { + { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R }, + { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F }, + { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V } + }; + + // Elements rendered manually via ImDrawList API are not clipped automatically. + // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view. + Dummy(board_max - board_min); + if (!IsItemVisible()) + return; + draw_list->PushClipRect(board_min, board_max, true); + for (int n = 0; n < IM_COUNTOF(keys_to_display); n++) + { + const KeyLayoutData* key_data = &keys_to_display[n]; + ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y); + ImVec2 key_max = key_min + key_size; + draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding); + draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding); + ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y); + ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y); + draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f); + draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding); + ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y); + draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label); + if (IsKeyDown(key_data->Key)) + draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding); + } + draw_list->PopClipRect(); +} + +// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. +void ImGui::DebugTextEncoding(const char* str) +{ + Text("Text: \"%s\"", str); + if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable)) + return; + TableSetupColumn("Offset"); + TableSetupColumn("UTF-8"); + TableSetupColumn("Glyph"); + TableSetupColumn("Codepoint"); + TableHeadersRow(); + const char* str_end = str + strlen(str); // As we may receive malformed UTF-8, pass an explicit end instead of relying on ImTextCharFromUtf8() assuming enough space. + for (const char* p = str; *p != 0; ) + { + unsigned int c; + const int c_utf8_len = ImTextCharFromUtf8(&c, p, str_end); + TableNextColumn(); + Text("%d", (int)(p - str)); + TableNextColumn(); + for (int byte_index = 0; byte_index < c_utf8_len; byte_index++) + { + if (byte_index > 0) + SameLine(); + Text("0x%02X", (int)(unsigned char)p[byte_index]); + } + TableNextColumn(); + TextUnformatted(p, p + c_utf8_len); + if (!GetFont()->IsGlyphInFont((ImWchar)c)) + { + SameLine(); + TextUnformatted("[missing]"); + } + TableNextColumn(); + Text("U+%04X", (int)c); + p += c_utf8_len; + } + EndTable(); +} + +static void DebugFlashStyleColorStop() +{ + ImGuiContext& g = *GImGui; + if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT) + g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup; + g.DebugFlashStyleColorIdx = ImGuiCol_COUNT; +} + +// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls. +void ImGui::DebugFlashStyleColor(ImGuiCol idx) +{ + ImGuiContext& g = *GImGui; + DebugFlashStyleColorStop(); + g.DebugFlashStyleColorTime = 0.5f; + g.DebugFlashStyleColorIdx = idx; + g.DebugFlashStyleColorBackup = g.Style.Colors[idx]; +} + +void ImGui::UpdateDebugToolFlashStyleColor() +{ + ImGuiContext& g = *GImGui; + if (g.DebugFlashStyleColorTime <= 0.0f) + return; + ColorConvertHSVtoRGB(ImCos(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z); + g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f; + if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f) + DebugFlashStyleColorStop(); +} + +ImU64 ImGui::DebugTextureIDToU64(ImTextureID tex_id) +{ + ImU64 v = 0; + memcpy(&v, &tex_id, ImMin(sizeof(ImU64), sizeof(ImTextureID))); + return v; +} + +static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref) +{ + char* buf_p = buf; + char* buf_end = buf + buf_size; + if (tex_ref._TexData != NULL) + buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID); + ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); + return buf; +} + +#ifdef IMGUI_ENABLE_FREETYPE +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); } +#endif + +// [DEBUG] List fonts in a font atlas and display its texture +void ImGui::ShowFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + ImGuiStyle& style = g.Style; + + BeginDisabled(); + CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); + EndDisabled(); + ShowFontSelector("Font"); + //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + //BeginDisabled(io.ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); + if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } + BulletText("Load a nice font for better results!"); + BulletText("Please submit feedback:"); + SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); + BulletText("Read FAQ for more details:"); + SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/"); + //EndDisabled(); + + SeparatorText("Font List"); + + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show font preview", &cfg->ShowFontPreview); + + // Font loaders + if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) + { + const ImFontLoader* loader_current = atlas->FontLoader; + BeginDisabled(!atlas->RendererHasTextures); +#ifdef IMGUI_ENABLE_STB_TRUETYPE + const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); + if (RadioButton("stb_truetype", loader_current == loader_stbtruetype)) + atlas->SetFontLoader(loader_stbtruetype); +#else + BeginDisabled(); + RadioButton("stb_truetype", false); + SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE"); + EndDisabled(); +#endif + SameLine(); +#ifdef IMGUI_ENABLE_FREETYPE + const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader(); + if (RadioButton("FreeType", loader_current == loader_freetype)) + atlas->SetFontLoader(loader_freetype); + if (loader_current == loader_freetype) + { + unsigned int loader_flags = atlas->FontLoaderFlags; + Text("Shared FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) + { + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + atlas->FontLoaderFlags = loader_flags; + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontInitOutput(atlas, font); + } + } +#else + BeginDisabled(); + RadioButton("FreeType", false); + SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp."); + EndDisabled(); +#endif + EndDisabled(); + TreePop(); + } + + // Font list + for (ImFont* font : atlas->Fonts) + { + PushID(font); + DebugNodeFont(font); + PopID(); + } + + SeparatorText("Font Atlas"); + if (Button("Compact")) + atlas->CompactCache(); + SameLine(); + if (Button("Grow")) + ImFontAtlasTextureGrow(atlas); + SameLine(); + if (Button("Clear All")) + ImFontAtlasBuildClear(atlas); + SetItemTooltip("Destroy cache and custom rectangles."); + + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + ImTextureData* tex = atlas->TexList[tex_n]; + if (tex_n > 0) + SameLine(); + Text("Tex: %dx%d", tex->Width, tex->Height); + } + const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface); + const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface); + Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt); + Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt); + + ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid; + if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles + { + PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f); + if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12))) + { + for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex) + if (entry.IsUsed) + { + ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation); + ImFontAtlasRect r = {}; + atlas->GetCustomRect(id, &r); + const char* buf; + ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y); + TableNextColumn(); + Selectable(buf); + if (IsItemHovered()) + highlight_r_id = id; + TableNextColumn(); + Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + } + EndTable(); + } + PopStyleVar(); + TreePop(); + } + + // Texture list + // (ensure the last texture always use the same ID, so we can keep it open neatly) + ImFontAtlasRect highlight_r; + if (highlight_r_id != ImFontAtlasRectId_Invalid) + atlas->GetCustomRect(highlight_r_id, &highlight_r); + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + if (tex_n == atlas->TexList.Size - 1) + SetNextItemOpen(true, ImGuiCond_Once); + DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL); + } +} + +void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect) +{ + ImGuiContext& g = *GImGui; + PushID(int_id); + if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) + { + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show used rect", &cfg->ShowTextureUsedRect); + PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); + ImVec2 p = GetCursorScreenPos(); + if (tex->WantDestroyNextFrame) + Dummy(ImVec2((float)tex->Width, (float)tex->Height)); + else + ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (cfg->ShowTextureUsedRect) + GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255)); + if (highlight_rect != NULL) + { + ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height); + ImRect r_inner(p.x + highlight_rect->x, p.y + highlight_rect->y, p.x + highlight_rect->x + highlight_rect->w, p.y + highlight_rect->y + highlight_rect->h); + RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f); + GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255)); + } + PopStyleVar(); + + char texref_desc[30]; + Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); + Text("TexRef = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texref_desc, IM_COUNTOF(texref_desc), tex->GetTexRef()), tex->BackendUserData); + TreePop(); + } + PopID(); +} + +void ImGui::ShowMetricsWindow(bool* p_open) +{ + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + if (cfg->ShowDebugLog) + ShowDebugLogWindow(&cfg->ShowDebugLog); + if (cfg->ShowIDStackTool) + ShowIDStackToolWindow(&cfg->ShowIDStackTool); + + if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1) + { + End(); + return; + } + + // [DEBUG] Clear debug breaks hooks after exactly one cycle. + DebugBreakClearData(); + + // Basic info + Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + if (g.ContextName[0] != 0) + { + SameLine(); + Text("(Context Name: \"%s\")", g.ContextName); + } + Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount); + //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; } + + Separator(); + + // Debugging enums + enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type + const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" }; + enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type + const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" }; + if (cfg->ShowWindowsRectsType < 0) + cfg->ShowWindowsRectsType = WRT_WorkRect; + if (cfg->ShowTablesRectsType < 0) + cfg->ShowTablesRectsType = TRT_WorkRect; + + struct Funcs + { + static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n) + { + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance + if (rect_type == TRT_OuterRect) { return table->OuterRect; } + else if (rect_type == TRT_InnerRect) { return table->InnerRect; } + else if (rect_type == TRT_WorkRect) { return table->WorkRect; } + else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; } + else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; } + else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; } + else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); } + else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); } + else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; } + else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate + else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } + else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); } + else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); } + IM_ASSERT(0); + return ImRect(); + } + + static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) + { + if (rect_type == WRT_OuterRect) { return window->Rect(); } + else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; } + else if (rect_type == WRT_InnerRect) { return window->InnerRect; } + else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; } + else if (rect_type == WRT_WorkRect) { return window->WorkRect; } + else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } + else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); } + else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; } + IM_ASSERT(0); + return ImRect(); + } + }; + +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + + // Tools + if (TreeNode("Tools")) + { + // Debug Break features + // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. + SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x); + SameLine(); + MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); + if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive) + DebugStartItemPicker(); + Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent); + + SeparatorText("Visualize"); + + Checkbox("Show Debug Log", &cfg->ShowDebugLog); + SameLine(); + MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code."); + + Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool); + SameLine(); + MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code."); + + Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder); + Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count); + if (cfg->ShowWindowsRects && g.NavWindow != NULL) + { + BulletText("'%s':", g.NavWindow->Name); + Indent(); + for (int rect_n = 0; rect_n < WRT_Count; rect_n++) + { + ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); + Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); + } + Unindent(); + } + + Checkbox("Show tables rectangles", &cfg->ShowTablesRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count); + if (cfg->ShowTablesRects && g.NavWindow != NULL) + { + for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++) + { + ImGuiTable* table = g.Tables.TryGetMapData(table_n); + if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow)) + continue; + + BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); + if (IsItemHovered()) + GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + Indent(); + char buf[128]; + for (int rect_n = 0; rect_n < TRT_Count; rect_n++) + { + if (rect_n >= TRT_ColumnsRect) + { + if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect) + continue; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, rect_n, column_n); + ImFormatString(buf, IM_COUNTOF(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); + Selectable(buf); + if (IsItemHovered()) + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, rect_n, -1); + ImFormatString(buf, IM_COUNTOF(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); + Selectable(buf); + if (IsItemHovered()) + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + } + } + Unindent(); + } + } + Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data + + SeparatorText("Validate"); + + Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop); + SameLine(); + MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running."); + + Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer); + SameLine(); + MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct."); + if (cfg->ShowTextEncodingViewer) + { + static char buf[64] = ""; + SetNextItemWidth(-FLT_MIN); + InputText("##DebugTextEncodingBuf", buf, IM_COUNTOF(buf)); + if (buf[0] != 0) + DebugTextEncoding(buf); + } + + TreePop(); + } + + // Windows + if (TreeNode("Windows", "Windows (%d)", g.Windows.Size)) + { + //SetNextItemOpen(true, ImGuiCond_Once); + DebugNodeWindowsList(&g.Windows, "By display order"); + DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)"); + if (TreeNode("By submission order (begin stack)")) + { + // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship! + ImVector& temp_buffer = g.WindowsTempSortBuffer; + temp_buffer.resize(0); + for (ImGuiWindow* window : g.Windows) + if (window->LastFrameActive + 1 >= g.FrameCount) + temp_buffer.push_back(window); + struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } }; + ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder); + DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL); + TreePop(); + } + + TreePop(); + } + + // DrawLists + int drawlist_count = 0; + for (ImGuiViewportP* viewport : g.Viewports) + drawlist_count += viewport->DrawDataP.CmdLists.Size; + if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count)) + { + Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); + Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); + for (ImGuiViewportP* viewport : g.Viewports) + { + bool viewport_has_drawlist = false; + for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists) + { + if (!viewport_has_drawlist) + Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID); + viewport_has_drawlist = true; + DebugNodeDrawList(NULL, viewport, draw_list, "DrawList"); + } + } + TreePop(); + } + + // Viewports + if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size)) + { + cfg->HighlightMonitorIdx = -1; + bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size); + SameLine(); + MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors."); + if (open) + { + for (int i = 0; i < g.PlatformIO.Monitors.Size; i++) + { + DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i); + if (IsItemHovered()) + cfg->HighlightMonitorIdx = i; + } + DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0); + TreePop(); + } + + SetNextItemOpen(true, ImGuiCond_Once); + if (TreeNode("Windows Minimap")) + { + RenderViewportsThumbnails(); + TreePop(); + } + cfg->HighlightViewportID = 0; + + BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); + if (TreeNode("Inferred Z order (front-to-back)")) + { + static ImVector viewports; + viewports.resize(g.Viewports.Size); + memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes()); + if (viewports.Size > 1) + ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount); + for (ImGuiViewportP* viewport : viewports) + { + BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"", + viewport->Idx, viewport->ID, viewport->LastFocusedStampCount, + (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A", + viewport->Window ? viewport->Window->Name : "N/A"); + if (IsItemHovered()) + cfg->HighlightViewportID = viewport->ID; + } + TreePop(); + } + + for (ImGuiViewportP* viewport : g.Viewports) + DebugNodeViewport(viewport); + TreePop(); + } + + // Details for Fonts + for (ImFontAtlas* atlas : g.FontAtlases) + if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size)) + { + ShowFontAtlas(atlas); + TreePop(); + } + + // Details for Popups + if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) + { + for (const ImGuiPopupData& popup_data : g.OpenPopupStack) + { + // As it's difficult to interact with tree nodes while popups are open, we display everything inline. + ImGuiWindow* window = popup_data.Window; + BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'", + popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "", + popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL"); + } + TreePop(); + } + + // Details for TabBars + if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount())) + { + for (int n = 0; n < g.TabBars.GetMapSize(); n++) + if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n)) + { + PushID(tab_bar); + DebugNodeTabBar(tab_bar, "TabBar"); + PopID(); + } + TreePop(); + } + + // Details for Tables + if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount())) + { + for (int n = 0; n < g.Tables.GetMapSize(); n++) + if (ImGuiTable* table = g.Tables.TryGetMapData(n)) + DebugNodeTable(table); + TreePop(); + } + + // Details for InputText + if (TreeNode("InputText")) + { + DebugNodeInputTextState(&g.InputTextState); + TreePop(); + } + + // Details for TypingSelect + if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0)) + { + DebugNodeTypingSelectState(&g.TypingSelectState); + TreePop(); + } + + // Details for MultiSelect + if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount())) + { + ImGuiBoxSelectState* bs = &g.BoxSelectState; + BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive); + for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++) + if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n)) + DebugNodeMultiSelectState(state); + TreePop(); + } + + // Details for Docking +#ifdef IMGUI_HAS_DOCK + if (TreeNode("Docking")) + { + static bool root_nodes_only = true; + ImGuiDockContext* dc = &g.DockContext; + Checkbox("List root nodes", &root_nodes_only); + Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes); + if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } + SameLine(); + if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (!root_nodes_only || node->IsRootNode()) + DebugNodeDockNode(node, "Node"); + TreePop(); + } +#endif // #ifdef IMGUI_HAS_DOCK + + // Settings + if (TreeNode("Settings")) + { + if (SmallButton("Clear")) + ClearIniSettings(); + SameLine(); + if (SmallButton("Save to memory")) + SaveIniSettingsToMemory(); + SameLine(); + if (SmallButton("Save to disk")) + SaveIniSettingsToDisk(g.IO.IniFilename); + SameLine(); + if (g.IO.IniFilename) + Text("\"%s\"", g.IO.IniFilename); + else + TextUnformatted(""); + Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings); + Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); + if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) + { + for (ImGuiSettingsHandler& handler : g.SettingsHandlers) + BulletText("\"%s\"", handler.TypeName); + TreePop(); + } + if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) + { + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + DebugNodeWindowSettings(settings); + TreePop(); + } + + if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) + { + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + DebugNodeTableSettings(settings); + TreePop(); + } + +#ifdef IMGUI_HAS_DOCK + if (TreeNode("SettingsDocking", "Settings packed data: Docking")) + { + ImGuiDockContext* dc = &g.DockContext; + Text("In SettingsWindows:"); + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId != 0) + BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder); + Text("In SettingsNodes:"); + for (int n = 0; n < dc->NodesSettings.Size; n++) + { + ImGuiDockNodeSettings* settings = &dc->NodesSettings[n]; + const char* selected_tab_name = NULL; + if (settings->SelectedTabId) + { + if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId)) + selected_tab_name = window->Name; + else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId)) + selected_tab_name = window_settings->GetName(); + } + BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : ""); + } + TreePop(); + } +#endif // #ifdef IMGUI_HAS_DOCK + + if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + { + InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); + TreePop(); + } + TreePop(); + } + + // Settings + if (TreeNode("Memory allocations")) + { + ImGuiDebugAllocInfo* info = &g.DebugAllocInfo; + Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount); + if (SmallButton("GC now")) { g.GcCompactAll = true; } + Text("Recent frames with allocations:"); + int buf_size = IM_COUNTOF(info->LastEntriesBuf); + for (int n = buf_size - 1; n >= 0; n--) + { + ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size]; + BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount); + if (n == 0) + { + SameLine(); + Text("<- %d frames ago", g.FrameCount - entry->FrameCount); + } + } + TreePop(); + } + + if (TreeNode("Inputs")) + { + Text("KEYBOARD/GAMEPAD/MOUSE KEYS"); + { + // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END. + Indent(); + Text("Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); } + Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); } + Text("Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); } + Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "Ctrl " : "", io.KeyShift ? "Shift " : "", io.KeyAlt ? "Alt " : "", io.KeySuper ? "Super " : ""); + Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. + DebugRenderKeyboardPreview(GetWindowDrawList()); + Unindent(); + } + + Text("MOUSE STATE"); + { + Indent(); + if (IsMousePosValid()) + Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y); + else + Text("Mouse pos: "); + Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); + int count = IM_COUNTOF(io.MouseDown); + Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); } + Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); } + Text("Mouse wheel: %.1f", io.MouseWheel); + Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer); + Text("Mouse source: %s", GetMouseSourceName(io.MouseSource)); + Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused + Unindent(); + } + + Text("MOUSE WHEELING"); + { + Indent(); + Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL"); + Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer); + Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : ""); + Unindent(); + } + + Text("KEY OWNERS"); + { + Indent(); + if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings)) + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) + { + ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); + if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner) + continue; + Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr, + owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : ""); + DebugLocateItemOnHover(owner_data->OwnerCurr); + } + EndChild(); + Unindent(); + } + Text("SHORTCUT ROUTING"); + SameLine(); + MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches."); + { + Indent(); + if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings)) + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) + { + ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable; + for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; ) + { + ImGuiKeyRoutingData* routing_data = &rt->Entries[idx]; + ImGuiKeyChord key_chord = key | routing_data->Mods; + Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore); + DebugLocateItemOnHover(routing_data->RoutingCurr); + if (g.IO.ConfigDebugIsDebuggerPresent) + { + SameLine(); + if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord")) + g.DebugBreakInShortcutRouting = key_chord; + } + idx = routing_data->NextEntryIndex; + } + } + EndChild(); + Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask); + Unindent(); + } + TreePop(); + } + + if (TreeNode("Internal state")) + { + Text("WINDOWING"); + Indent(); + Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL"); + Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); + Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0); + Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); + Unindent(); + + Text("ITEMS"); + Indent(); + Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource)); + DebugLocateItemOnHover(g.ActiveId); + Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); + Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask); + Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame + Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer); + Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + DebugLocateItemOnHover(g.DragDropPayload.SourceId); + Unindent(); + + Text("NAV,FOCUS"); + Indent(); + Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); + Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); + DebugLocateItemOnHover(g.NavId); + Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource)); + Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData); + Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); + Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId); + Text("NavActivateFlags: %04X", g.NavActivateFlags); + Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav); + Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); + Text("NavFocusRoute[] = "); + for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--) + { + const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n]; + SameLine(0.0f, 0.0f); + Text("0x%08X/", focus_scope.ID); + SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name); + } + Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); + Unindent(); + + TreePop(); + } + + // Overlay: Display windows Rectangles and Begin Order + if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder) + { + for (ImGuiWindow* window : g.Windows) + { + if (!window->WasActive) + continue; + ImDrawList* draw_list = GetForegroundDrawList(window); + if (cfg->ShowWindowsRects) + { + ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); + } + if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow)) + { + char buf[32]; + ImFormatString(buf, IM_COUNTOF(buf), "%d", window->BeginOrderWithinContext); + float font_size = GetFontSize(); + draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); + draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); + } + } + } + + // Overlay: Display Tables Rectangles + if (cfg->ShowTablesRects) + { + for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++) + { + ImGuiTable* table = g.Tables.TryGetMapData(table_n); + if (table == NULL || table->LastFrameActive < g.FrameCount - 1) + continue; + ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow); + if (cfg->ShowTablesRectsType >= TRT_ColumnsRect) + { + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n); + ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255); + float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f; + draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); + } + } + } + +#ifdef IMGUI_HAS_DOCK + // Overlay: Display Docking info + if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode) + { + char buf[64] = ""; + char* p = buf; + ImGuiDockNode* node = g.DebugHoveredDockNode; + ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + p += ImFormatString(p, buf + IM_COUNTOF(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); + p += ImFormatString(p, buf + IM_COUNTOF(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); + p += ImFormatString(p, buf + IM_COUNTOF(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); + p += ImFormatString(p, buf + IM_COUNTOF(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); + int depth = DockNodeGetDepth(node); + overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); + ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; + overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); + overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); + } +#endif // #ifdef IMGUI_HAS_DOCK + + End(); +} + +void ImGui::DebugBreakClearData() +{ + // Those fields are scattered in their respective subsystem to stay in hot-data locations + ImGuiContext& g = *GImGui; + g.DebugBreakInWindow = 0; + g.DebugBreakInTable = 0; + g.DebugBreakInShortcutRouting = ImGuiKey_None; +} + +void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location) +{ + if (!BeginItemTooltip()) + return; + Text("To call IM_DEBUG_BREAK() %s:", description_of_location); + Separator(); + TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space."); + Separator(); + TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!"); + EndTooltip(); +} + +// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc. +// In order to reduce interferences with the contents we are trying to debug into. +bool ImGui::DebugBreakButton(const char* label, const char* description_of_location) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset); + ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y); + + const ImRect bb(pos, pos + size); + ItemSize(size, 0.0f); + if (!ItemAdd(bb, id)) + return false; + + // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects. + bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags); + bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id); + DebugBreakButtonTooltip(false, description_of_location); + + ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImVec4 hsv; + ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z); + ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z); + + RenderNavCursor(bb, id); + RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding); + RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +// [DEBUG] Display contents of Columns +void ImGui::DebugNodeColumns(ImGuiOldColumns* columns) +{ + if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) + return; + BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); + for (ImGuiOldColumnData& column : columns->Columns) + BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm)); + TreePop(); +} + +static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled) +{ + using namespace ImGui; + PushID(label); + PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + Text("%s:", label); + if (!enabled) + BeginDisabled(); + CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize); + CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX); + CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY); + CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar); + CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar); + CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton); + CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton); + CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute); + CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags + CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit); + CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther); + CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe); + CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther); + CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty); + CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking); + if (!enabled) + EndDisabled(); + PopStyleVar(); + PopID(); +} + +// [DEBUG] Display contents of ImDockNode +void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label) +{ + ImGuiContext& g = *GImGui; + const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly + const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted + if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open; + ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (node->Windows.Size > 0) + open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + else + open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + if (!is_alive) { PopStyleColor(); } + if (is_active && IsItemHovered()) + if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow) + GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); + if (open) + { + IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); + IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); + BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", + node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); + DebugNodeWindow(node->HostWindow, "HostWindow"); + DebugNodeWindow(node->VisibleWindow, "VisibleWindow"); + BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId); + BulletText("Misc:%s%s%s%s%s%s%s", + node->IsDockSpace() ? " IsDockSpace" : "", + node->IsCentralNode() ? " IsCentralNode" : "", + is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "", + node->WantLockSizeOnce ? " WantLockSizeOnce" : "", + node->HasCentralNodeChild ? " HasCentralNodeChild" : ""); + if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags)) + { + if (BeginTable("flags", 4)) + { + TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false); + TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true); + TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false); + TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true); + EndTable(); + } + TreePop(); + } + if (node->ParentNode) + DebugNodeDockNode(node->ParentNode, "ParentNode"); + if (node->ChildNodes[0]) + DebugNodeDockNode(node->ChildNodes[0], "Child[0]"); + if (node->ChildNodes[1]) + DebugNodeDockNode(node->ChildNodes[1], "Child[1]"); + if (node->TabBar) + DebugNodeTabBar(node->TabBar, "TabBar"); + DebugNodeWindowsList(&node->Windows, "Windows"); + + TreePop(); + } +} + +// [DEBUG] Display contents of ImDrawList +// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. +void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label) +{ + ImGuiContext& g = *GImGui; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + int cmd_count = draw_list->CmdBuffer.Size; + if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) + cmd_count--; + bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count); + if (draw_list == GetWindowDrawList()) + { + SameLine(); + TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) + TreePop(); + return; + } + + ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list + if (window && IsItemHovered() && fg_draw_list) + fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!node_open) + return; + + if (window && !window->WasActive) + TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); + + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) + { + if (pcmd->UserCallback) + { + BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + + char texid_desc[30]; + FormatTextureRefForDebugDisplay(texid_desc, IM_COUNTOF(texid_desc), pcmd->TexRef); + char buf[300]; + ImFormatString(buf, IM_COUNTOF(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); + if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes); + if (!pcmd_node_open) + continue; + + // Calculate approximate coverage area (touched pixel count) + // This will be in pixels squared as long there's no post-scaling happening to the renderer output. + const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; + float total_area = 0.0f; + for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; ) + { + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; + total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); + } + + // Display vertex information summary. Hover to get all triangles drawn in wire-frame + ImFormatString(buf, IM_COUNTOF(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); + Selectable(buf); + if (IsItemHovered() && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false); + + // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. + ImGuiListClipper clipper; + clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) + { + char* buf_p = buf, * buf_end = buf + IM_COUNTOF(buf); + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_i++) + { + const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; + triangle[n] = v.pos; + buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", + (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + + Selectable(buf, false); + if (fg_draw_list && IsItemHovered()) + { + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); + fg_draw_list->Flags = backup_flags; + } + } + TreePop(); + } + TreePop(); +} + +// [DEBUG] Display mesh/aabb of a ImDrawCmd +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb) +{ + IM_ASSERT(show_mesh || show_aabb); + + // Draw wire-frame version of all triangles + ImRect clip_rect = draw_cmd->ClipRect; + ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + ImDrawListFlags backup_flags = out_draw_list->Flags; + out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; ) + { + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list + ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; + + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); + if (show_mesh) + out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles + } + // Draw bounding boxes + if (show_aabb) + { + out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU + out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles + } + out_draw_list->Flags = backup_flags; +} + +// [DEBUG] Compute mask of inputs with the same codepoint. +static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint) +{ + int mask = 0, count = 0; + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint)) + continue; + mask |= (1 << src_n); + count++; + } + return count > 1 ? mask : 0; +} + +// [DEBUG] Display details for a single font, called by ShowStyleEditor(). +void ImGui::DebugNodeFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + ImFontAtlas* atlas = font->OwnerAtlas; + bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size); + + // Display preview text + if (!opened) + Indent(); + Indent(); + if (cfg->ShowFontPreview) + { + PushFont(font, 0.0f); + Text("The quick brown fox jumps over the lazy dog"); + PopFont(); + } + if (!opened) + { + Unindent(); + Unindent(); + return; + } + if (SmallButton("Set as default")) + GetIO().FontDefault = font; + SameLine(); + BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked); + if (SmallButton("Remove")) + atlas->RemoveFont(font); + EndDisabled(); + SameLine(); + if (SmallButton("Clear bakes")) + ImFontAtlasFontDiscardBakes(atlas, font, 0); + SameLine(); + if (SmallButton("Clear unused")) + ImFontAtlasFontDiscardBakes(atlas, font, 2); + + // Display details +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + SetNextItemWidth(GetFontSize() * 8); + DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); + /*SameLine(); MetricsHelpMarker( + "Note that the default embedded font is NOT meant to be scaled.\n\n" + "Font are currently rendered into bitmaps at a given size at the time of building the atlas. " + "You may oversample them to get some flexibility with scaling. " + "You can also render at multiple sizes and select which one to use at runtime.\n\n" + "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/ +#endif + + char c_str[5]; + ImTextCharToUtf8(c_str, font->FallbackChar); + Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar); + ImTextCharToUtf8(c_str, font->EllipsisChar); + Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar); + + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); + + //if (DragFloat("ExtraSizeScale", &src->ExtraSizeScale, 0.01f, 0.10f, 2.0f)) + // ImFontAtlasFontRebuildOutput(atlas, font); +#ifdef IMGUI_ENABLE_FREETYPE + if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) + { + unsigned int loader_flags = src->FontLoaderFlags; + Text("FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) + { + ImFontAtlasFontDestroyOutput(atlas, font); + src->FontLoaderFlags = loader_flags; + ImFontAtlasFontInitOutput(atlas, font); + } + } +#endif + TreePop(); + } + } + if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool")) + { + TextWrapped("- First Input that contains the glyph is used.\n" + "- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- Prefer using a small number of ranges as the list is scanned every time a new glyph is loaded,\n - e.g. GlyphExcludeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };\n- This tool doesn't cache results and is slow, don't keep it open!"); + if (BeginTable("table", 2)) + { + for (unsigned int c = 0; c < 0x10000; c++) + if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c)) + { + unsigned int c_end = c + 1; + while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask) + c_end++; + if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask))) + { + char utf8_buf[5]; + for (unsigned int n = c; n < c_end; n++) + { + ImTextCharToUtf8(utf8_buf, n); + BulletText("Codepoint U+%04X (%s)", n, utf8_buf); + } + TreePop(); + } + TableNextColumn(); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + if (overlap_mask & (1 << src_n)) + { + Text("%d ", src_n); + SameLine(); + } + c = c_end - 1; + } + EndTable(); + } + TreePop(); + } + + // Display all glyphs of the fonts in separate pages of 256 characters + for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; + if (baked->OwnerFont != font) + continue; + PushID(baked_n); + if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) + { + if (SmallButton("Load all")) + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) + baked->FindGlyph((ImWchar)base); + + const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface); + Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent); + Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); + BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); + } + + DebugNodeFontGlyphesForSrcMask(font, baked, ~0); + TreePop(); + } + PopID(); + } + TreePop(); + Unindent(); +} + +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask) +{ + ImDrawList* draw_list = GetWindowDrawList(); + const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); + const float cell_size = baked->Size * 1; + const float cell_spacing = GetStyle().ItemSpacing.y; + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) + { + base += 8192 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL) + if (src_mask & (1 << glyph->SourceIdx)) + count++; + if (count <= 0) + continue; + if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + + // Draw a 16x16 grid of glyphs + ImVec2 base_pos = GetCursorScreenPos(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0) + continue; + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) + { + DebugNodeFontGlyph(font, glyph); + EndTooltip(); + } + } + Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + TreePop(); + } +} + +void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) +{ + Text("Codepoint: U+%04X", glyph->Codepoint); + Separator(); + Text("Visible: %d", glyph->Visible); + Text("AdvanceX: %.1f", glyph->AdvanceX); + Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + if (glyph->PackId >= 0) + { + ImTextureRect* r = ImFontAtlasPackGetRect(font->OwnerAtlas, glyph->PackId); + Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); + } + Text("SourceIdx: %d", glyph->SourceIdx); +} + +// [DEBUG] Display contents of ImGuiStorage +void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label) +{ + if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) + return; + for (const ImGuiStoragePair& p : storage->Data) + { + BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. + DebugLocateItemOnHover(p.key); + } + TreePop(); +} + +// [DEBUG] Display contents of ImGuiTabBar +void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label) +{ + // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. + char buf[256]; + char* p = buf; + const char* buf_end = buf + IM_COUNTOF(buf); + const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2); + p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); + for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab)); + } + p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode(label, "%s", buf); + if (!is_active) { PopStyleColor(); } + if (is_active && IsItemHovered()) + { + ImDrawList* draw_list = GetForegroundDrawList(tab_bar->Window); + draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + } + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + PushID(tab); + if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2); + if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine(); + Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f", + tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth); + PopID(); + } + TreePop(); + } +} + +void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + SetNextItemOpen(true, ImGuiCond_Once); + bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"); + if (IsItemHovered()) + g.DebugMetricsConfig.HighlightViewportID = viewport->ID; + if (open) + { + ImGuiWindowFlags flags = viewport->Flags; + BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nFrameBufferScale: (%.2f,%.2f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%", + viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, + viewport->FramebufferScale.x, viewport->FramebufferScale.y, + viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y, + viewport->PlatformMonitor, viewport->DpiScale * 100.0f); + if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } } + BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags, + //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard + (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", + (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "", + (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "", + (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "", + (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", + (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "", + (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", + (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "", + (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", + (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", + (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "", + (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "", + (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : ""); + for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists) + DebugNodeDrawList(NULL, viewport, draw_list, "DrawList"); + TreePop(); + } +} + +void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx) +{ + BulletText("%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)", + label, idx, monitor->DpiScale * 100.0f, + monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y, + monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y); +} + +void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) +{ + if (window == NULL) + { + BulletText("%s: NULL", label); + return; + } + + ImGuiContext& g = *GImGui; + const bool is_active = window->WasActive; + ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (IsItemHovered() && is_active) + GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!open) + return; + + if (window->MemoryCompacted) + TextDisabled("Note: some memory buffers have been compacted/freed."); + + if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()")) + g.DebugBreakInWindow = window->ID; + + ImGuiWindowFlags flags = window->Flags; + DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList"); + BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y); + BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, + (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", + (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", + (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + if (flags & ImGuiWindowFlags_ChildWindow) + BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags, + (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "", + (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "", + (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "", + (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : ""); + BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId); + BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); + BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); + BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); + for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++) + { + ImRect r = window->NavRectRel[layer]; + if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y) + BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]); + else + BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y); + DebugLocateItemOnHover(window->NavLastIds[layer]); + } + const ImVec2* pr = window->NavPreferredScoringPosRel; + for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++) + BulletText("NavPreferredScoringPosRel[%d] = (%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater. + BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); + + BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y); + BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1); + BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible); + if (window->DockNode || window->DockNodeAsHost) + DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode"); + + if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } + if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); } + if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); } + if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); } + if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); } + if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) + { + for (ImGuiOldColumns& columns : window->ColumnsStorage) + DebugNodeColumns(&columns); + TreePop(); + } + DebugNodeStorage(&window->StateStorage, "Storage"); + TreePop(); +} + +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings) +{ + if (settings->WantDelete) + BeginDisabled(); + Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", + settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); + if (settings->WantDelete) + EndDisabled(); +} + +void ImGui::DebugNodeWindowsList(ImVector* windows, const char* label) +{ + if (!TreeNode(label, "%s (%d)", label, windows->Size)) + return; + for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back + { + PushID((*windows)[i]); + DebugNodeWindow((*windows)[i], "Window"); + PopID(); + } + TreePop(); +} + +// FIXME-OPT: This is technically suboptimal, but it is simpler this way. +void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack) +{ + for (int i = 0; i < windows_size; i++) + { + ImGuiWindow* window = windows[i]; + if (window->ParentWindowInBeginStack != parent_in_begin_stack) + continue; + char buf[20]; + ImFormatString(buf, IM_COUNTOF(buf), "[%04d] Window", window->BeginOrderWithinContext); + //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name); + DebugNodeWindow(window, buf); + TreePush(buf); + DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window); + TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DEBUG LOG WINDOW +//----------------------------------------------------------------------------- + +void ImGui::DebugLog(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + DebugLogV(fmt, args); + va_end(args); +} + +void ImGui::DebugLogV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + const int old_size = g.DebugLogBuf.size(); + if (g.ContextName[0] != 0) + g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount); + else + g.DebugLogBuf.appendf("[%05d] ", g.FrameCount); + g.DebugLogBuf.appendfv(fmt, args); + g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size()); + + const char* str = g.DebugLogBuf.begin() + old_size; + if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY) + IMGUI_DEBUG_PRINTF("%s", str); +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) + if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToDebugger) + { + ::OutputDebugStringA("[imgui] "); + ::OutputDebugStringA(str); + } +#endif +#ifdef IMGUI_ENABLE_TEST_ENGINE + // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically + const int new_size = g.DebugLogBuf.size(); + const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n'); + if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine) + IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), str); +#endif +} + +// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout. +static void SameLineOrWrap(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y); + if (window->WorkRect.Contains(ImRect(pos, pos + size))) + ImGui::SameLine(); +} + +static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags) +{ + ImGuiContext& g = *GImGui; + ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight()); + SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout. + + bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0); + if (highlight_errors) + ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f)); + if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0) + { + g.DebugLogAutoDisableFrames = 2; + g.DebugLogAutoDisableFlags |= flags; + } + if (highlight_errors) + { + ImGui::PopStyleColor(); + ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors); + } + else + { + ImGui::SetItemTooltip("Hold Shift when clicking to enable for 2 frames only (useful for spammy log entries)"); + } +} + +void ImGui::ShowDebugLogWindow(bool* p_open) +{ + ImGuiContext& g = *GImGui; + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0) + SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver); + if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1) + { + End(); + return; + } + + ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting; + CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags); + SetItemTooltip("(except InputRouting which is spammy)"); + + ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError); + ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId); + ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper); + ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking); + ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus); + ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO); + ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont); + ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav); + ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup); + ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); + ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport); + ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting); + + if (SmallButton("Clear")) + { + g.DebugLogBuf.clear(); + g.DebugLogIndex.clear(); + g.DebugLogSkippedErrors = 0; + } + SameLine(); + if (SmallButton("Copy")) + SetClipboardText(g.DebugLogBuf.c_str()); + SameLine(); + if (SmallButton("Configure Outputs..")) + OpenPopup("Outputs"); + if (BeginPopup("Outputs")) + { + CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY); + CheckboxFlags("OutputToDebugger", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToDebugger); +#ifndef IMGUI_ENABLE_TEST_ENGINE + BeginDisabled(); +#endif + CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine); +#ifndef IMGUI_ENABLE_TEST_ENGINE + EndDisabled(); +#endif + EndPopup(); + } + + BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + + const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags; + g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper; + + ImGuiListClipper clipper; + clipper.Begin(g.DebugLogIndex.size()); + while (clipper.Step()) + for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) + DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no)); + g.DebugLogFlags = backup_log_flags; + if (GetScrollY() >= GetScrollMaxY()) + SetScrollHereY(1.0f); + EndChild(); + + End(); +} + +// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered. +void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end) +{ + TextUnformatted(line_begin, line_end); + if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + return; + ImGuiContext& g = *GImGui; + ImRect text_rect = g.LastItemData.Rect; + for (const char* p = line_begin; p <= line_end - 10; p++) + { + ImGuiID id = 0; + if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10])) + continue; + ImVec2 p0 = CalcTextSize(line_begin, p); + ImVec2 p1 = CalcTextSize(p, p + 10); + g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y)); + if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true)) + DebugLocateItemOnHover(id); + p += 10; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +//----------------------------------------------------------------------------- + +// Draw a small cross at current CursorPos in current window's DrawList +void ImGui::DebugDrawCursorPos(ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImVec2 pos = window->DC.CursorPos; + window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f); + window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f); +} + +// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList +void ImGui::DebugDrawLineExtents(ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float curr_x = window->DC.CursorPos.x; + float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y); + float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y); + window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f); + window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f); + window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f); +} + +// Draw last item rect in ForegroundDrawList (so it is always visible) +void ImGui::DebugDrawItemRect(ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col); +} + +// [DEBUG] Locate item position/rectangle given an ID. +static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green + +void ImGui::DebugLocateItem(ImGuiID target_id) +{ + ImGuiContext& g = *GImGui; + g.DebugLocateId = target_id; + g.DebugLocateFrames = 2; + g.DebugBreakInLocateId = false; +} + +// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow. +void ImGui::DebugLocateItemOnHover(ImGuiID target_id) +{ + if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + return; + ImGuiContext& g = *GImGui; + DebugLocateItem(target_id); + GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR); + + // Can't easily use a context menu here because it will mess with focus, active id etc. + if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f) + { + DebugBreakButtonTooltip(false, "in ItemAdd()"); + if (IsKeyChordPressed(g.DebugBreakKeyChord)) + g.DebugBreakInLocateId = true; + } +} + +void ImGui::DebugLocateItemResolveWithLastItem() +{ + ImGuiContext& g = *GImGui; + + // [DEBUG] Debug break requested by user + if (g.DebugBreakInLocateId) + IM_DEBUG_BREAK(); + + ImGuiLastItemData item_data = g.LastItemData; + g.DebugLocateId = 0; + ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow); + ImRect r = item_data.Rect; + r.Expand(3.0f); + ImVec2 p1 = g.IO.MousePos; + ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y); + draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR); + draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR); +} + +void ImGui::DebugStartItemPicker() +{ + ImGuiContext& g = *GImGui; + g.DebugItemPickerActive = true; +} + +// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. +void ImGui::UpdateDebugToolItemPicker() +{ + ImGuiContext& g = *GImGui; + g.DebugItemPickerBreakId = 0; + if (!g.DebugItemPickerActive) + return; + + const ImGuiID hovered_id = g.HoveredIdPreviousFrame; + SetMouseCursor(ImGuiMouseCursor_Hand); + if (IsKeyPressed(ImGuiKey_Escape)) + g.DebugItemPickerActive = false; + const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift); + if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id) + { + g.DebugItemPickerBreakId = hovered_id; + g.DebugItemPickerActive = false; + } + for (int mouse_button = 0; mouse_button < 3; mouse_button++) + if (change_mapping && IsMouseClicked(mouse_button)) + g.DebugItemPickerMouseButton = (ImU8)mouse_button; + SetNextWindowBgAlpha(0.70f); + if (!BeginTooltip()) + return; + Text("HoveredId: 0x%08X", hovered_id); + Text("Press ESC to abort picking."); + const char* mouse_button_names[] = { "Left", "Right", "Middle" }; + if (change_mapping) + Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button."); + else + TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]); + EndTooltip(); +} + +// Update queries. The steps are: -1: query Stack, >= 0: query each stack item +// We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time +static ImGuiID DebugItemPathQuery_UpdateAndGetHookId(ImGuiDebugItemPathQuery* query, ImGuiID id) +{ + // Update query. Clear hook when no active query + if (query->MainID != id) + { + query->MainID = id; + query->Step = -1; + query->Complete = false; + query->Results.resize(0); + query->ResultsDescBuf.resize(0); + } + query->Active = false; + if (id == 0) + return 0; + + // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) + if (query->Step >= 0 && query->Step < query->Results.Size) + if (query->Results[query->Step].QuerySuccess || query->Results[query->Step].QueryFrameCount > 2) + query->Step++; + + // Update status and hook + query->Complete = (query->Step == query->Results.Size); + if (query->Step == -1) + { + query->Active = true; + return id; + } + else if (query->Step >= 0 && query->Step < query->Results.Size) + { + query->Results[query->Step].QueryFrameCount++; + query->Active = true; + return query->Results[query->Step].ID; + } + return 0; +} + +// [DEBUG] ID Stack Tool: update query. Called by NewFrame() +void ImGui::UpdateDebugToolItemPathQuery() +{ + ImGuiContext& g = *GImGui; + ImGuiID id = 0; + if (g.DebugIDStackTool.LastActiveFrame + 1 == g.FrameCount) + id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; + g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(&g.DebugItemPathQuery, id); +} + +// [DEBUG] ID Stack tool: hooks called by GetID() family functions +void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end) +{ + ImGuiContext& g = *GImGui; + ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery; + if (query->Active == false) + { + IM_ASSERT(id == 0); + return; + } + ImGuiWindow* window = g.CurrentWindow; + + // Step -1: stack query + // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. + if (query->Step == -1) + { + IM_ASSERT(query->Results.Size == 0); + query->Step++; + query->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo()); + for (int n = 0; n < window->IDStack.Size + 1; n++) + query->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id; + return; + } + + // Step 0+: query for individual level + IM_ASSERT(query->Step >= 0); + if (query->Step != window->IDStack.Size) + return; + ImGuiStackLevelInfo* info = &query->Results[query->Step]; + IM_ASSERT(info->ID == id && info->QueryFrameCount > 0); + + if (info->DescOffset == -1) + { + const char* result = NULL; + const char* result_end = NULL; + switch (data_type) + { + case ImGuiDataType_S32: + ImFormatStringToTempBuffer(&result, &result_end, "%d", (int)(intptr_t)data_id); + break; + case ImGuiDataType_String: + ImFormatStringToTempBuffer(&result, &result_end, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id); + break; + case ImGuiDataType_Pointer: + ImFormatStringToTempBuffer(&result, &result_end, "(void*)0x%p", data_id); + break; + case ImGuiDataType_ID: + // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. + ImFormatStringToTempBuffer(&result, &result_end, "0x%08X [override]", id); + break; + default: + IM_ASSERT(0); + } + info->DescOffset = query->ResultsDescBuf.size(); + query->ResultsDescBuf.append(result, result_end + 1); // Include zero terminator + } + info->QuerySuccess = true; + if (info->DataType == -1) + info->DataType = (ImS8)data_type; +} + +static int DebugItemPathQuery_FormatLevelInfo(ImGuiDebugItemPathQuery* query, int n, bool format_for_ui, char* buf, size_t buf_size) +{ + ImGuiStackLevelInfo* info = &query->Results[n]; + ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; + if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name)); + if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&query->ResultsDescBuf.Buf[info->DescOffset])); + if (query->Step < query->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. + return (*buf = 0); +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() + return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label)); +#endif + return ImFormatString(buf, buf_size, "???"); +} + +static const char* DebugItemPathQuery_GetResultAsPath(ImGuiDebugItemPathQuery* query, bool hex_encode_non_ascii_chars) +{ + ImGuiTextBuffer* buf = &query->ResultPathBuf; + buf->resize(0); + for (int stack_n = 0; stack_n < query->Results.Size; stack_n++) + { + char level_desc[256]; + DebugItemPathQuery_FormatLevelInfo(query, stack_n, false, level_desc, IM_COUNTOF(level_desc)); + buf->append(stack_n == 0 ? "//" : "/"); + for (const char* p = level_desc; *p != 0; ) + { + unsigned int c; + const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL); + if (c == '/') + buf->append("\\"); + if (c < 256 || !hex_encode_non_ascii_chars) + buf->append(p, p_next); + else for (; p < p_next; p++) + buf->appendf("\\x%02x", (unsigned char)*p); + p = p_next; + } + } + return buf->c_str(); +} + +// ID Stack Tool: Display UI +void ImGui::ShowIDStackToolWindow(bool* p_open) +{ + ImGuiContext& g = *GImGui; + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0) + SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver); + if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1) + { + End(); + return; + } + + ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery; + ImGuiIDStackTool* tool = &g.DebugIDStackTool; + tool->LastActiveFrame = g.FrameCount; + const char* result_path = DebugItemPathQuery_GetResultAsPath(query, tool->OptHexEncodeNonAsciiChars); + Text("0x%08X", query->MainID); + SameLine(); + MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details."); + + // Ctrl+C to copy path + const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime; + PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); + Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars); + SameLine(); + Checkbox("Ctrl+C: copy path", &tool->OptCopyToClipboardOnCtrlC); + PopStyleVar(); + SameLine(); + TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*"); + if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) + { + tool->CopyToClipboardLastTime = (float)g.Time; + SetClipboardText(result_path); + } + + Text("- Path \"%s\"", query->Complete ? result_path : ""); +#ifdef IMGUI_ENABLE_TEST_ENGINE + Text("- Label \"%s\"", query->MainID ? ImGuiTestEngine_FindItemDebugLabel(&g, query->MainID) : ""); +#endif + Separator(); + + // Display decorated stack + if (query->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders)) + { + const float id_width = CalcTextSize("0xDDDDDDDD").x; + TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width); + TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch); + TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width); + TableHeadersRow(); + for (int n = 0; n < query->Results.Size; n++) + { + ImGuiStackLevelInfo* info = &query->Results[n]; + TableNextColumn(); + Text("0x%08X", (n > 0) ? query->Results[n - 1].ID : 0); + TableNextColumn(); + DebugItemPathQuery_FormatLevelInfo(query, n, true, g.TempBuffer.Data, g.TempBuffer.Size); + TextUnformatted(g.TempBuffer.Data); + TableNextColumn(); + Text("0x%08X", info->ID); + if (n == query->Results.Size - 1) + TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header)); + } + EndTable(); + } + End(); +} + +#else + +void ImGui::ShowMetricsWindow(bool*) {} +void ImGui::ShowFontAtlas(ImFontAtlas*) {} +void ImGui::DebugNodeColumns(ImGuiOldColumns*) {} +void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {} +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} +void ImGui::DebugNodeFont(ImFont*) {} +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {} +void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} +void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} +void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} +void ImGui::DebugNodeWindowsList(ImVector*, const char*) {} +void ImGui::DebugNodeViewport(ImGuiViewportP*) {} + +void ImGui::ShowDebugLogWindow(bool*) {} +void ImGui::ShowIDStackToolWindow(bool*) {} +void ImGui::DebugStartItemPicker() {} +void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {} + +#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS + +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) +// Demo helper function to select among loaded fonts. +// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. +void ImGui::ShowFontSelector(const char* label) +{ + ImGuiIO& io = GetIO(); + ImFont* font_current = GetFont(); + if (BeginCombo(label, font_current->GetDebugName())) + { + for (ImFont* font : io.Fonts->Fonts) + { + PushID((void*)font); + if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav)) + io.FontDefault = font; + if (font == font_current) + SetItemDefaultFocus(); + PopID(); + } + EndCombo(); + } + SameLine(); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- Read FAQ and docs/FONTS.md for more details."); + else + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" + "- Read FAQ and docs/FONTS.md for more details.\n" + "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); +} +#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) + +//----------------------------------------------------------------------------- + +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui.h b/libs/imgui/imgui.h new file mode 100644 index 0000000..1d511bf --- /dev/null +++ b/libs/imgui/imgui.h @@ -0,0 +1,4473 @@ +// dear imgui, v1.92.6 WIP +// (headers) + +// Help: +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// - Read top of imgui.cpp for more details, links and comments. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including imgui.h (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. + +// Resources: +// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) +// - Homepage ................... https://github.com/ocornut/imgui +// - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) +// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) +// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) +// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) +// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui +// - Issues & support ........... https://github.com/ocornut/imgui/issues +// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +// - Web version of the Demo .... https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html (w/ source code browser) + +// For FIRST-TIME users having issues compiling/linking/running: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. +// EVERYTHING ELSE should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// Since 1.92, we encourage font loading questions to also be posted in 'Issues'. + +// Library Version +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') +#define IMGUI_VERSION "1.92.6 WIP" +#define IMGUI_VERSION_NUM 19259 +#define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 +#define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 +#define IMGUI_HAS_VIEWPORT // In 'docking' WIP branch. +#define IMGUI_HAS_DOCK // In 'docking' WIP branch. + +/* + +Index of this file: +// [SECTION] Header mess +// [SECTION] Forward declarations and basic types +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +// [SECTION] Dear ImGui end-user API functions +// [SECTION] Flags & Enumerations +// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +// [SECTION] Helpers: Debug log, Memory allocations macros, ImVector<> +// [SECTION] ImGuiStyle +// [SECTION] ImGuiIO +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload) +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) +// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +// [SECTION] Obsolete functions and types + +*/ + +#pragma once + +// Configuration file with compile-time options +// (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system) +#ifdef IMGUI_USER_CONFIG +#include IMGUI_USER_CONFIG +#endif +#include "imconfig.h" + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +// Includes +#include // FLT_MIN, FLT_MAX +#include // va_list, va_start, va_end +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) +// Using dear imgui via a shared library is not recommended: we don't guarantee backward nor forward ABI compatibility + this is a call-heavy library and function call overhead adds up. +#ifndef IMGUI_API +#define IMGUI_API +#endif +#ifndef IMGUI_IMPL_API +#define IMGUI_IMPL_API IMGUI_API +#endif + +// Helper Macros +// (note: compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes.) +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h +#endif +#define IM_COUNTOF(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_STRINGIFY_HELPER(_EXPR) #_EXPR +#define IM_STRINGIFY(_EXPR) IM_STRINGIFY_HELPER(_EXPR) // Preprocessor idiom to stringify e.g. an integer or a macro. + +// Check that version and structures layouts are matching between compiled imgui code and caller. Read comments above DebugCheckVersionAndDataLayout() for details. +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) + +// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. +// (MSVC provides an equivalent mechanism via SAL Annotations but it requires the macros in a different +// location. e.g. #include + void myprintf(_Printf_format_string_ const char* format, ...), +// and only works when using Code Analysis, rather than just normal compiling). +// (see https://github.com/ocornut/imgui/issues/8871 for a patch to enable this for MSVC's Code Analysis) +#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) +#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) +#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif + +// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) +#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID) +#define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) +#define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) +#else +#define IM_MSVC_RUNTIME_CHECKS_OFF +#define IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Warnings +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#endif +#if defined(__clang__) +#pragma clang diagnostic push +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant +#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations and basic types +//----------------------------------------------------------------------------- + +// Scalar data types +typedef unsigned int ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string) +typedef signed char ImS8; // 8-bit signed integer +typedef unsigned char ImU8; // 8-bit unsigned integer +typedef signed short ImS16; // 16-bit signed integer +typedef unsigned short ImU16; // 16-bit unsigned integer +typedef signed int ImS32; // 32-bit signed integer == int +typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) +typedef signed long long ImS64; // 64-bit signed integer +typedef unsigned long long ImU64; // 64-bit unsigned integer + +// Forward declarations: ImDrawList, ImFontAtlas layer +struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) +struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. +struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) +struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader +struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas +struct ImFontAtlasRect; // Output of ImFontAtlas::GetCustomRect() when using custom rectangles. +struct ImFontBaked; // Baked data for a ImFont at a given size. +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) +struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). +struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. +struct ImTextureRect; // Coordinates of a rectangle within a texture. +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) + +// Forward declarations: ImGui layer +struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) +struct ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO) +struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) +struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block +struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame +struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME, Multi-Viewport support). Extends ImGuiIO. +struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. +struct ImGuiPlatformMonitor; // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors +struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. +struct ImGuiSelectionExternalStorage;//Optional helper to apply multi-selection requests to existing randomly accessible storage. +struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) +struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) +struct ImGuiStorage; // Helper for key->value storage (container sorted by key) +struct ImGuiStoragePair; // Helper for key->value storage (pair) +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table +struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) +struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") +struct ImGuiViewport; // A Platform Window (always 1 unless multi-viewport are enabled. One per platform window to output to). In the future may represent Platform Monitor +struct ImGuiWindowClass; // Window class (rare/advanced uses: provide hints to the platform backend via altered viewport flags and parent/child info) + +// Enumerations +// - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. +enum ImGuiDir : int; // -> enum ImGuiDir // Enum: A cardinal direction (Left, Right, Up, Down) +enum ImGuiKey : int; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) +enum ImGuiMouseSource : int; // -> enum ImGuiMouseSource // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen) +enum ImGuiSortDirection : ImU8; // -> enum ImGuiSortDirection // Enum: A sorting direction (ascending or descending) +typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions +typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type +typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) +typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor shape +typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() + +// Flags (declared as int to allow using as flags without overhead, and to not pollute the top of this file) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. +typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance +typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use! +typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas +typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() +typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild() +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. +typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags +typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDockNodeFlags; // -> enum ImGuiDockNodeFlags_ // Flags: for DockSpace() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() +typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() +typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: for Shortcut(), SetNextItemShortcut() +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() +typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items +typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. +typedef int ImGuiListClipperFlags; // -> enum ImGuiListClipperFlags_// Flags: for ImGuiListClipper +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() +typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect() +typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() +typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() +typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() +typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() + +// Character types +// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) +typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. +typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. +#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] +typedef ImWchar32 ImWchar; +#else +typedef ImWchar16 ImWchar; +#endif + +// Multi-Selection item index or identifier when using BeginMultiSelect() +// - Used by SetNextItemSelectionUserData() + and inside ImGuiMultiSelectIO structure. +// - Most users are likely to use this store an item INDEX but this may be used to store a POINTER/ID as well. Read comments near ImGuiMultiSelectIO for details. +typedef ImS64 ImGuiSelectionUserData; + +// Callback and functions types +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() +typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() +typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() + +// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] +// - This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec2 +{ + float x, y; + constexpr ImVec2() : x(0.0f), y(0.0f) { } + constexpr ImVec2(float _x, float _y) : x(_x), y(_y) { } + float& operator[] (size_t idx) { IM_ASSERT(idx == 0 || idx == 1); return ((float*)(void*)(char*)this)[idx]; } // We very rarely use this [] operator, so the assert overhead is fine. + float operator[] (size_t idx) const { IM_ASSERT(idx == 0 || idx == 1); return ((const float*)(const void*)(const char*)this)[idx]; } +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. +#endif +}; + +// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] +struct ImVec4 +{ + float x, y, z, w; + constexpr ImVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { } + constexpr ImVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. +#endif +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +//----------------------------------------------------------------------------- + +// ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system. +// [Compile-time configurable type] +// - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. +// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; +// Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). +// - User may submit their own textures to e.g. ImGui::Image() function by passing this value. +// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a +// ImTextureRef, which is stored inside a ImDrawCmd. +// - Compile-time type configuration: +// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ entry about textures for details. +// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various +// constructors if you like. You will need to implement ==/!= operators. +// History: +// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requiring 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. +// - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef +#ifndef ImTextureID +typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. +#endif + +// Define this if you need 0 to be a valid ImTextureID for your backend. +#ifndef ImTextureID_Invalid +#define ImTextureID_Invalid ((ImTextureID)0) +#endif + +// ImTextureRef = higher-level identifier for a texture. Store a ImTextureID _or_ a ImTextureData*. +// The identifier is valid even before the texture has been uploaded to the GPU/graphics system. +// This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. +// This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. +// - When a texture is created by user code (e.g. custom images), we directly store the low-level ImTextureID. +// Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. +// - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection +// to extract the ImTextureID value during rendering, after texture upload has happened. +// - To create a ImTextureRef from a ImTextureData you can use ImTextureData::GetTexRef(). +// We intentionally do not provide an ImTextureRef constructor for this: we don't expect this +// to be frequently useful to the end-user, and it would be erroneously called by many legacy code. +// - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. +// - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. +// inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } +// In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef. +// We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImTextureRef +{ + ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; } + ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } +#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) + ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID +#endif + + inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. + + // Members (either are set, never both!) + ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls. +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] Dear ImGui end-user API functions +// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Context creation and access + // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. + IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Main + IMGUI_API ImGuiIO& GetIO(); // access the ImGuiIO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // access the ImGuiPlatformIO structure (mostly hooks/functions to connect to platform/renderer and OS Clipboard, IME etc.) + IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleColor(), PushStyleVar() to modify style mid-frame! + IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). Call ImGui_ImplXXXX_RenderDrawData() function in your Renderer Backend to render. + + // Demo, Debug, Information + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. + IMGUI_API void ShowDebugLogWindow(bool* p_open = NULL); // create Debug Log window. display a simplified log of important dear imgui events. + IMGUI_API void ShowIDStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) + + // Styles + IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) + IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font + IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style + + // Windows + // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. + // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, + // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). + // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting + // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! + // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions + // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding + // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + // - Note that the bottom of window stack always contains a window called "Debug". + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API void End(); + + // Child Windows + // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. + // - Before 1.90 (November 2023), the "ImGuiChildFlags child_flags = 0" parameter was "bool border = false". + // This API is backward compatible with old code, as we guarantee that ImGuiChildFlags_Borders == true. + // Consider updating your old code: + // BeginChild("Name", size, false) -> Begin("Name", size, 0); or Begin("Name", size, ImGuiChildFlags_None); + // BeginChild("Name", size, true) -> Begin("Name", size, ImGuiChildFlags_Borders); + // - Manual sizing (each axis can use a different setting e.g. ImVec2(0.0f, 400.0f)): + // == 0.0f: use remaining parent window size for this axis. + // > 0.0f: use specified size for this axis. + // < 0.0f: right/bottom-align to specified distance from available content boundaries. + // - Specifying ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY makes the sizing automatic based on child contents. + // Combining both ImGuiChildFlags_AutoResizeX _and_ ImGuiChildFlags_AutoResizeY defeats purpose of a scrolling region and is NOT recommended. + // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting + // anything to the window. Always call a matching EndChild() for each BeginChild() call, regardless of its return value. + // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions + // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding + // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); + IMGUI_API void EndChild(); + + // Windows Utilities + // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. + IMGUI_API bool IsWindowAppearing(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives + IMGUI_API float GetWindowDpiScale(); // get DPI scale currently associated to the current window's viewport. + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API ImVec2 GetWindowSize(); // get current window size (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API float GetWindowWidth(); // get current window width (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().x. + IMGUI_API float GetWindowHeight(); // get current window height (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().y. + IMGUI_API ImGuiViewport*GetWindowViewport(); // get viewport currently associated to the current window. + + // Window manipulation + // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use 0.0f or FLT_MAX if you don't want limits. Use -1 for both min and max of same axis to preserve current size (which itself is a constraint). Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() + IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. + IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. + + // Windows Scrolling + // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). + // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). + IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y + IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + + // Parameters stacks (font) + // - PushFont(font, 0.0f) // Change font and keep current size + // - PushFont(NULL, 20.0f) // Keep font and change current size + // - PushFont(font, 20.0f) // Change font and set size to 20.0f + // - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. + // - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior. + // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. + // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition. + // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function. + // *IMPORTANT* global scale factors are applied over the provided size. + // - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. + // - If you want to apply a factor to the _current_ font size: + // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing + // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger + // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! + // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! + IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. + IMGUI_API void PopFont(); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER global scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before global scale factors. + IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) + + // Parameters stacks (shared) + IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame()! + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. " + IMGUI_API void PushStyleVarX(ImGuiStyleVar idx, float val_x); // modify X component of a style ImVec2 variable. " + IMGUI_API void PushStyleVarY(ImGuiStyleVar idx, float val_y); // modify Y component of a style ImVec2 variable. " + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) + IMGUI_API void PopItemFlag(); + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). + IMGUI_API void PopItemWidth(); + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. + IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + + // Style read access + // - Use the ShowStyleEditor() function to interactively see/edit the colors. + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(ImU32 col, float alpha_mul = 1.0f); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. + + // Layout cursor positioning + // - By "cursor" we mean the current output position. + // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. + // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). + // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: + // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. + // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), PushTextWrapPos() + // - Window-local coordinates: GetContentRegionMax(), GetWindowContentRegionMin(), GetWindowContentRegionMax() --> all obsoleted. YOU DON'T NEED THEM. + // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. Try not to use it. + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND. + IMGUI_API ImVec2 GetContentRegionAvail(); // available space from current position. THIS IS YOUR BEST FRIEND. + IMGUI_API ImVec2 GetCursorPos(); // [window-local] cursor position in window-local coordinates. This is not your best friend. + IMGUI_API float GetCursorPosX(); // [window-local] " + IMGUI_API float GetCursorPosY(); // [window-local] " + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // [window-local] " + IMGUI_API void SetCursorPosX(float local_x); // [window-local] " + IMGUI_API void SetCursorPosY(float local_y); // [window-local] " + IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window-local coordinates. Call GetCursorScreenPos() after Begin() to get the absolute coordinates version. + + // Other layout functions + IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. + IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. + IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in a horizontal-layout context. + IMGUI_API void Spacing(); // add vertical spacing. + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) + IMGUI_API float GetTextLineHeight(); // ~ FontSize + IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) + IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 + IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) + + // ID stack/scopes + // Read the FAQ (docs/FAQ.md or http://dearimgui.com/faq) for more details about how ID are handled in dear imgui. + // - Those questions are answered and impacted by understanding of the ID stack system: + // - "Q: Why is my widget not reacting when I click on it?" + // - "Q: How can I have widgets with an empty label?" + // - "Q: How can I have multiple widgets with the same label?" + // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely + // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. + // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. + // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, + // whereas "str_id" denote a string that is only used as an ID and not normally displayed. + IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). + IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). + IMGUI_API void PopID(); // pop from the ID stack. + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + IMGUI_API ImGuiID GetID(int int_id); + + // Widgets: Text + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. + IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text + IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void SeparatorText(const char* label); // currently: formatted text with a horizontal line + + // Widgets: Main + // - Most widgets return true when the value has been changed or when pressed/selected + // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button + IMGUI_API bool SmallButton(const char* label); // button with (FramePadding.y == 0) to easily embed within text + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); + IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API bool TextLink(const char* label); // hyperlink text button, return true when clicked + IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked + + // Widgets: Images + // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. + // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. + // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. + // - An obsolete version of Image(), before 1.91.9 (March 2025), had a 'tint_col' parameter which is now supported by the ImageWithBg() function. + IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); + IMGUI_API void ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + IMGUI_API bool ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + + // Widgets: Combo Box (Dropdown) + // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. + // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. + IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! + IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" + IMGUI_API bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1); + + // Widgets: Drag Sliders + // - Ctrl+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that a 'float v[X]' function argument is the same as 'float* v', + // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For keyboard/gamepad navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + // - Use v_min < v_max to clamp edits to given limits. Note that Ctrl+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. + // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders + // - Ctrl+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Input with Keyboard + // - If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! + // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. + IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. + + // Widgets: Trees + // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. + IMGUI_API bool TreeNode(const char* label); + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorrelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const void* ptr_id); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopID() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. + IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API void SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). + + // Widgets: Selectables + // - A selectable highlights when hovered, and can display another color when selected. + // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + + // Multi-selection system for Selectable(), Checkbox(), TreeNode() functions [BETA] + // - This enables standard multi-selection/range-selection idioms (Ctrl+Mouse/Keyboard, Shift+Mouse/Keyboard, etc.) in a way that also allow a clipper to be used. + // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). + // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. + // - TreeNode() is technically supported but... using this correctly is more complicated. You need some sort of linear/random access to your tree, + // which is suited to advanced trees setups already implementing filters and clipper. We will work simplifying the current demo. + // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. + IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size = -1, int items_count = -1); + IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); + IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); + IMGUI_API bool IsItemToggledSelection(); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. + + // Widgets: List Boxes + // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. + // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result. + // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. + // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analogous to how Combos are created. + // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth + // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items + IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region + IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items = -1); + + // Widgets: Data Plotting + // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + + // Widgets: Value() Helpers. + // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + + // Widgets: Menus + // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. + // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. + // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. + // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). + IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. + IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Tooltips + // - Tooltips are windows following the mouse. They do not take focus away. + // - A tooltip window can contain items of any types. + // - SetTooltip() is more or less a shortcut for the 'if (BeginTooltip()) { Text(...); EndTooltip(); }' idiom (with a subtlety that it discard any previously submitted tooltip) + IMGUI_API bool BeginTooltip(); // begin/append a tooltip window. + IMGUI_API void EndTooltip(); // only call EndTooltip() if BeginTooltip()/BeginItemTooltip() returns true! + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip. Often used after a ImGui::IsItemHovered() check. Override any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Tooltips: helpers for showing a tooltip when hovering an item + // - BeginItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip) && BeginTooltip())' idiom. + // - SetItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip)) { SetTooltip(...); }' idiom. + // - Where 'ImGuiHoveredFlags_ForTooltip' itself is a shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on active input type. For mouse it defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. + IMGUI_API bool BeginItemTooltip(); // begin/append a tooltip window if preceding item was hovered. + IMGUI_API void SetItemTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip if preceding item was hovered. override any previous call to SetTooltip(). + IMGUI_API void SetItemTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Popups, Modals + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards if returned true. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + + // Popups: open/close functions + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks + IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + + // Popups: Open+Begin popup combined functions helpers to create context menus. + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: + // - Before this version, OpenPopupOnItemClick(), BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid() had 'a ImGuiPopupFlags popup_flags = 1' default value in their function signature. + // - Before: Explicitly passing a literal 0 meant ImGuiPopupFlags_MouseButtonLeft. The default = 1 meant ImGuiPopupFlags_MouseButtonRight. + // - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 1 also means ImGuiPopupFlags_MouseButtonRight (if legacy behavior are enabled) or will assert (if legacy behavior are disabled). + // - TL;DR: if you don't want to use right mouse button for popups, always specify it explicitly using a named ImGuiPopupFlags_MouseButtonXXXX value. + // - Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157 for all details. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked in void (where there are no windows). + + // Popups: query functions + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. + + // Tables + // - Full-featured replacement for old Columns API. + // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. + // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. + // The typical call flow is: + // - 1. Call BeginTable(), early out if returning false. + // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. + // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. + // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. + // - 5. Populate contents: + // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. + // - If you are using tables as a sort of grid, where every column is holding the same type of contents, + // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). + // TableNextColumn() will automatically wrap-around into the next row if needed. + // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! + // - Summary of possible call flow: + // - TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // - TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // - TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // - TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! + // - 5. Call EndTable() + IMGUI_API bool BeginTable(const char* str_id, int columns, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! + IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. 'min_row_height' include the minimum top and bottom padding aka CellPadding.y * 2.0f. + IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. + IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. + + // Tables: Headers & Columns declaration + // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. + // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. + // Headers are required to perform: reordering, sorting, and opening the context menu. + // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. + // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in + // some advanced use cases (e.g. adding custom widgets in header row). + // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0); + IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) + IMGUI_API void TableHeadersRow(); // submit a row with headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableAngledHeadersRow(); // submit a row with angled headers for every column with the ImGuiTableColumnFlags_AngledHeader flag. MUST BE FIRST ROW. + + // Tables: Sorting & Miscellaneous functions + // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. + // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have + // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, + // else you may wastefully sort your data every frame! + // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. + IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) + IMGUI_API int TableGetColumnIndex(); // return current column index. + IMGUI_API int TableGetRowIndex(); // return current row index (header rows are accounted for) + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. + IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) + IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. Can also use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. + + // Legacy Columns API (prefer using Tables!) + // - You can also use SameLine(pos_x) to mimic simplified columns. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool borders = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); + + // Tab Bars, Tabs + // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. + IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar + IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! + IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. + IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + + // Docking + // - Read https://github.com/ocornut/imgui/wiki/Docking for details. + // - Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. + // - You can use many Docking facilities without calling any API. + // - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking. + // - Drag from window menu button (upper-left button) to undock an entire node (all windows). + // - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to enable docking. + // - DockSpaceOverViewport: + // - This is a helper to create an invisible window covering a viewport, then submit a DockSpace() into it. + // - Most applications can simply call DockSpaceOverViewport() once to allow docking windows into e.g. the edge of your screen. + // e.g. ImGui::NewFrame(); ImGui::DockSpaceOverViewport(); // Create a dockspace in main viewport. + // or: ImGui::NewFrame(); ImGui::DockSpaceOverViewport(0, nullptr, ImGuiDockNodeFlags_PassthruCentralNode); // Create a dockspace in main viewport, central node is transparent. + // - Dockspaces: + // - A dockspace is an explicit dock node within an existing window. + // - IMPORTANT: Dockspaces need to be submitted _before_ any window they can host. Submit them early in your frame! + // - IMPORTANT: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. + // If you have e.g. multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. + // - See 'Demo->Examples->Dockspace' or 'Demo->Examples->Documents' for more detailed demos. + // - Programmatic docking: + // - There is no public API yet other than the very limited SetNextWindowDockID() function. Sorry for that! + // - Read https://github.com/ocornut/imgui/wiki/Docking for examples of how to use current internal API. + IMGUI_API ImGuiID DockSpace(ImGuiID dockspace_id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id + IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (control docking compatibility + provide hints to platform backend via custom viewport flags and platform parent/child relationship) + IMGUI_API ImGuiID GetWindowDockID(); // get dock id of current window, or 0 if not associated to any docking node. + IMGUI_API bool IsWindowDocked(); // is current window docked into another window? + + // Logging/Capture + // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) + IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) + IMGUI_API void LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Drag and Drop + // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). + // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) + // - An item can be both drag source and drop target. + IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. + IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! + IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! + IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. + + // Disabling [BETA API] + // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) + // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) + // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. + // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) + IMGUI_API void BeginDisabled(bool disabled = true); + IMGUI_API void EndDisabled(); + + // Clipping + // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Focus, Activation + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a newly appearing window. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. + + // Keyboard/Gamepad Navigation + IMGUI_API void SetNavCursorVisible(bool visible); // alter visibility of keyboard/gamepad cursor. by default: show when using an arrow key, hide when clicking with mouse. + + // Overlapping mode + IMGUI_API void SetNextItemAllowOverlap(); // allow next item to be overlapped by a subsequent item. Useful with invisible buttons, selectable, treenode covering an area where subsequent items may need to be added. Note that both Selectable() and TreeNode() have dedicated flags doing this. + + // Item/Widgets Utilities and Query Functions + // - Most of the functions are referring to the previous Item that has been submitted. + // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. + IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. + IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) + IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? + IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. + IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) + IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). + IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. + IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). + IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). + IMGUI_API bool IsAnyItemHovered(); // is any item hovered? + IMGUI_API bool IsAnyItemActive(); // is any item active? + IMGUI_API bool IsAnyItemFocused(); // is any item focused? + IMGUI_API ImGuiID GetItemID(); // get ID of last item (~~ often same ImGui::GetID(label) beforehand) + IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectSize(); // get size of last item + IMGUI_API ImGuiItemFlags GetItemFlags(); // get generic flags of last item + + // Viewports + // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. + // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. + // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. + IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. + + // Background/Foreground Draw Lists + IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport = NULL); // get background draw list for the given viewport or viewport associated to the current window. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport = NULL); // get foreground draw list for the given viewport or viewport associated to the current window. this draw list will be the top-most rendered one. Useful to quickly draw shapes/text over dear imgui contents. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. + IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). + IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + + // Text Utilities + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + + // Color Utilities + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs Utilities: Raw Keyboard/Mouse/Gamepad Access + // - Consider using the Shortcut() function instead of IsKeyPressed()/IsKeyChordPressed()! Shortcut() is easier to use and better featured (can do focus routing check). + // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). + // - (legacy: before v1.87 (2022-02), we used ImGuiKey < 512 values to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921) + IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. + IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? Repeat rate uses io.KeyRepeatDelay / KeyRepeatRate. + IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? + IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead. + IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate + IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. + IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. + + // Inputs Utilities: Shortcut Testing & Routing + // - Typical use is e.g.: 'if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_S)) { ... }'. + // - Flags: Default route use ImGuiInputFlags_RouteFocused, but see ImGuiInputFlags_RouteGlobal and other options in ImGuiInputFlags_! + // - Flags: Use ImGuiInputFlags_Repeat to support repeat. + // - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super. + // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments + // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments + // only ImGuiMod_XXX values are legal to combine with an ImGuiKey. You CANNOT combine two ImGuiKey values. + // - The general idea is that several callers may register interest in a shortcut, and only one owner gets it. + // Parent -> call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut. + // Child1 -> call Shortcut(Ctrl+S) // When Child1 is focused, Child1 gets the shortcut (Child1 overrides Parent shortcuts) + // Child2 -> no call // When Child2 is focused, Parent gets the shortcut. + // The whole system is order independent, so if Child1 makes its calls before Parent, results will be identical. + // This is an important property as it facilitate working with foreign code or larger codebase. + // - To understand the difference: + // - IsKeyChordPressed() compares mods and call IsKeyPressed() + // -> the function has no side-effect. + // - Shortcut() submits a route, routes are resolved, if it currently can be routed it calls IsKeyChordPressed() + // -> the function has (desirable) side-effects as it can prevents another call from getting the route. + // - Visualize registered routes in 'Metrics/Debugger->Inputs'. + IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); + IMGUI_API void SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); + + // Inputs Utilities: Key/Input Ownership [BETA] + // - One common use case would be to allow your items to disable standard inputs behaviors such + // as Tab or Alt key handling, Mouse Wheel scrolling, etc. + // e.g. Button(...); SetItemKeyOwner(ImGuiKey_MouseWheelY); to make hovering/activating a button disable wheel for scrolling. + // - Reminder ImGuiKey enum include access to mouse buttons and gamepad, so key ownership can apply to them. + // - Many related features are still in imgui_internal.h. For instance, most IsKeyXXX()/IsMouseXXX() functions have an owner-id-aware version. + IMGUI_API void SetItemKeyOwner(ImGuiKey key); // Set key owner to last item ID if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. + + // Inputs Utilities: Mouse + // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. + // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. + // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') + IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? + IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. + IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) + IMGUI_API bool IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay); // delayed mouse release (use very sparingly!). Generally used with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount==1' test. This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename. + IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available + IMGUI_API bool IsAnyMouseDown(); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) + IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) + IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) + IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instructs your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + + // Clipboard Utilities + // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Settings/.Ini Utilities + // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). + // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. + // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). + IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. + + // Debug Utilities + // - Your main debugging friend is the ShowMetricsWindow() function. + // - Interactive tools are all accessible from the 'Dear ImGui Demo->Tools' menu. + // - Read https://github.com/ocornut/imgui/wiki/Debug-Tools for a description of all available debug tools. + IMGUI_API void DebugTextEncoding(const char* text); + IMGUI_API void DebugFlashStyleColor(ImGuiCol idx); + IMGUI_API void DebugStartItemPicker(); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + IMGUI_API void DebugLog(const char* fmt, ...) IM_FMTARGS(1); // Call via IMGUI_DEBUG_LOG() for maximum stripping in caller code! + IMGUI_API void DebugLogV(const char* fmt, va_list args) IM_FMTLIST(1); +#endif + + // Memory Allocators + // - Those functions are not reliant on the current context. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. + IMGUI_API void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL); + IMGUI_API void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + + // (Optional) Platform/OS interface for multi-viewport support + // Read comments around the ImGuiPlatformIO structure for more details. + // Note: You may use GetWindowViewport() to get the current viewport of the current window. + IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport. + IMGUI_API void RenderPlatformWindowsDefault(void* platform_render_arg = NULL, void* renderer_render_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs. + IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from backend Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext(). + IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID viewport_id); // this is a helper for backends. + IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.) + +} // namespace ImGui + +//----------------------------------------------------------------------------- +// [SECTION] Flags & Enumerations +//----------------------------------------------------------------------------- + +// Flags for ImGui::Begin() +// (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) +enum ImGuiWindowFlags_ +{ + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_NoNavInputs = 1 << 16, // No keyboard/gamepad navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 17, // No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) + ImGuiWindowFlags_UnsavedDocument = 1 << 18, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiWindowFlags_NoDocking = 1 << 19, // Disable docking of this window + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + + // [Internal] + ImGuiWindowFlags_DockNodeHost = 1 << 23, // Don't use! For internal use by Begin()/NewFrame() + ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: moved to ImGuiChildFlags. BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) + //ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: moved to ImGuiChildFlags. BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) +#endif +}; + +// Flags for ImGui::BeginChild() +// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'.) +// About using AutoResizeX/AutoResizeY flags: +// - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints"). +// - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing. +// - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. +// While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. +// - You may also use ImGuiChildFlags_AlwaysAutoResize to force an update even when child window is not in view. +// HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. +enum ImGuiChildFlags_ +{ + ImGuiChildFlags_None = 0, + ImGuiChildFlags_Borders = 1 << 0, // Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) + ImGuiChildFlags_AlwaysUseWindowPadding = 1 << 1, // Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) + ImGuiChildFlags_ResizeX = 1 << 2, // Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) + ImGuiChildFlags_ResizeY = 1 << 3, // Allow resize from bottom border (layout direction). " + ImGuiChildFlags_AutoResizeX = 1 << 4, // Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. + ImGuiChildFlags_AutoResizeY = 1 << 5, // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. + ImGuiChildFlags_AlwaysAutoResize = 1 << 6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. + ImGuiChildFlags_FrameStyle = 1 << 7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + ImGuiChildFlags_NavFlattened = 1 << 8, // [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. +#endif +}; + +// Flags for ImGui::PushItemFlag() +// (Those are shared by all submitted items) +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_None = 0, // (Default) + ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags_NoNav. + ImGuiItemFlags_NoNav = 1 << 1, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls). + ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, // false // Disable item being a candidate for default focus (e.g. used by title bar items). + ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. + ImGuiItemFlags_AutoClosePopups = 1 << 4, // true // MenuItem()/Selectable() automatically close their parent popup window. + ImGuiItemFlags_AllowDuplicateId = 1 << 5, // false // Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. + ImGuiItemFlags_Disabled = 1 << 6, // false // [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). +}; + +// Flags for ImGui::InputText() +// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) +enum ImGuiInputTextFlags_ +{ + // Basic filters (also see ImGuiInputTextFlags_CallbackCharFilter) + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsScientific = 1 << 2, // Allow 0123456789.+-*/eE (Scientific notation input) + ImGuiInputTextFlags_CharsUppercase = 1 << 3, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 4, // Filter out spaces, tabs + + // Inputs + ImGuiInputTextFlags_AllowTabInput = 1 << 5, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 6, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider using IsItemDeactivatedAfterEdit() instead! + ImGuiInputTextFlags_EscapeClearsAll = 1 << 7, // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 8, // In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). + + // Other options + ImGuiInputTextFlags_ReadOnly = 1 << 9, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 10, // Password mode, display all characters as '*', disable copy + ImGuiInputTextFlags_AlwaysOverwrite = 1 << 11, // Overwrite mode + ImGuiInputTextFlags_AutoSelectAll = 1 << 12, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_ParseEmptyRefVal = 1 << 13, // InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. + ImGuiInputTextFlags_DisplayEmptyRefVal = 1 << 14, // InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags_ParseEmptyRefVal. + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 15, // Disable following the cursor horizontally + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). + + // Elide display / Alignment + ImGuiInputTextFlags_ElideLeft = 1 << 17, // When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! + + // Callback features + ImGuiInputTextFlags_CallbackCompletion = 1 << 18, // Callback on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 19, // Callback on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 20, // Callback on each iteration. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + ImGuiInputTextFlags_CallbackResize = 1 << 22, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + ImGuiInputTextFlags_CallbackEdit = 1 << 23, // Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. + + // Multi-line Word-Wrapping [BETA] + // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237. + // - Wrapping style is not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. + // - Wrapping width needs to always account for the possibility of a vertical scrollbar. + // - It is much slower than regular text fields. + // Ballpark estimate of cost on my 2019 desktop PC: for a 100 KB text buffer: +~0.3 ms (Optimized) / +~1.0 ms (Debug build). + // The CPU cost is very roughly proportional to text length, so a 10 KB buffer should cost about ten times less. + ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultiline(): word-wrap lines that are too long. + + // Obsolete names + //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! + ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. + ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. + ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (cover the indent area). + ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text. + ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) + ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, + + // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn + ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0 + ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7 + //ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 +#endif +}; + +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 1 << 2, // For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! + ImGuiPopupFlags_MouseButtonRight = 2 << 2, // For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) + ImGuiPopupFlags_MouseButtonMiddle = 3 << 2, // For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! + ImGuiPopupFlags_NoReopen = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) + //ImGuiPopupFlags_NoReopenAlwaysNavInit = 1 << 6, // For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 7, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 8, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + ImGuiPopupFlags_AnyPopupId = 1 << 10, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 11, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, + ImGuiPopupFlags_MouseButtonShift_ = 2, // [Internal] + ImGuiPopupFlags_MouseButtonMask_ = 0x0C, // [Internal] + ImGuiPopupFlags_InvalidMask_ = 0x03, // [Internal] Reserve legacy bits 0-1 to detect incorrectly passing 1 or 2 to the function. +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_NoAutoClosePopups = 1 << 0, // Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Frame will span all columns of its container table (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too + ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text + ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one + ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered + ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 + //ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 +#endif +}; + +// Flags for ImGui::BeginCombo() +enum ImGuiComboFlags_ +{ + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default + ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) + ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible + ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible + ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button + ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button + ImGuiComboFlags_WidthFitPreview = 1 << 7, // Width dynamically calculated from preview contents + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, +}; + +// Flags for ImGui::BeginTabBar() +enum ImGuiTabBarFlags_ +{ + ImGuiTabBarFlags_None = 0, + ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) + ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab + ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab + + // Fitting/Resize policy + ImGuiTabBarFlags_FittingPolicyMixed = 1 << 7, // Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling buttons. + ImGuiTabBarFlags_FittingPolicyShrink = 1 << 8, // Shrink down tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 9, // Enable scrolling buttons when tabs don't fit + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyMixed | ImGuiTabBarFlags_FittingPolicyShrink | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyMixed, + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiTabBarFlags_FittingPolicyResizeDown = ImGuiTabBarFlags_FittingPolicyShrink, // Renamed in 1.92.2 +#endif +}; + +// Flags for ImGui::BeginTabItem() +enum ImGuiTabItemFlags_ +{ + ImGuiTabItemFlags_None = 0, + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. + ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab + ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) + ImGuiTabItemFlags_Trailing = 1 << 7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) + ImGuiTabItemFlags_NoAssumedClosure = 1 << 8, // Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. +}; + +// Flags for ImGui::IsWindowFocused() +enum ImGuiFocusedFlags_ +{ + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, // Return true if any children of the window is focused + ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, +}; + +// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() +// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. +enum ImGuiHoveredFlags_ +{ + ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + ImGuiHoveredFlags_AllowWhenOverlappedByItem = 1 << 8, // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. + ImGuiHoveredFlags_AllowWhenOverlappedByWindow = 1 << 9, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 10, // IsItemHovered() only: Return true even if the item is disabled + ImGuiHoveredFlags_NoNavOverride = 1 << 11, // IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse + ImGuiHoveredFlags_AllowWhenOverlapped = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow, + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, + + // Tooltips mode + // - typically used in IsItemHovered() + SetTooltip() sequence. + // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. + // e.g. 'HoverFlagsForTooltipMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled'. + // - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often. + // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. + ImGuiHoveredFlags_ForTooltip = 1 << 12, // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. + + // (Advanced) Mouse Hovering delays. + // - generally you can use ImGuiHoveredFlags_ForTooltip to use application-standardized flags. + // - use those if you need specific overrides. + ImGuiHoveredFlags_Stationary = 1 << 13, // Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. + ImGuiHoveredFlags_DelayNone = 1 << 14, // IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. + ImGuiHoveredFlags_DelayShort = 1 << 15, // IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + ImGuiHoveredFlags_DelayNormal = 1 << 16, // IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + ImGuiHoveredFlags_NoSharedDelay = 1 << 17, // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) +}; + +// Flags for ImGui::DockSpace(), shared/inherited by child nodes. +// (Some flags can be applied to individual nodes directly) +// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. +enum ImGuiDockNodeFlags_ +{ + ImGuiDockNodeFlags_None = 0, + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingOverCentralNode = 1 << 2, // // Disable docking over the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_NoDockingSplit = 1 << 4, // // Disable other windows/nodes from splitting this node. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Saved // Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6, // // Tab bar will automatically hide when there is a single window in the dock node. + ImGuiDockNodeFlags_NoUndocking = 1 << 7, // // Disable undocking this node. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiDockNodeFlags_NoSplit = ImGuiDockNodeFlags_NoDockingSplit, // Renamed in 1.90 + ImGuiDockNodeFlags_NoDockingInCentralNode = ImGuiDockNodeFlags_NoDockingOverCentralNode, // Renamed in 1.90 +#endif +}; + +// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() +enum ImGuiDragDropFlags_ +{ + ImGuiDragDropFlags_None = 0, + // BeginDragDropSource() flags + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_PayloadAutoExpire = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + ImGuiDragDropFlags_PayloadNoCrossContext = 1 << 6, // Hint to specify that the payload may not be copied outside current dear imgui context. + ImGuiDragDropFlags_PayloadNoCrossProcess = 1 << 7, // Hint to specify that the payload may not be copied outside current process. + // AcceptDragDropPayload() flags + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptDrawAsHovered = 1 << 13, // Accepting item will render as if hovered. Useful for e.g. a Button() used as a drop target. + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiDragDropFlags_SourceAutoExpirePayload = ImGuiDragDropFlags_PayloadAutoExpire, // Renamed in 1.90.9 +#endif +}; + +// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. +#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. + +// A primary data type +enum ImGuiDataType_ +{ + ImGuiDataType_S8, // signed char / char (with sensible compilers) + ImGuiDataType_U8, // unsigned char + ImGuiDataType_S16, // short + ImGuiDataType_U16, // unsigned short + ImGuiDataType_S32, // int + ImGuiDataType_U32, // unsigned int + ImGuiDataType_S64, // long long / __int64 + ImGuiDataType_U64, // unsigned long long / unsigned __int64 + ImGuiDataType_Float, // float + ImGuiDataType_Double, // double + ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets) + ImGuiDataType_String, // char* (provided for user convenience, not supported by scalar widgets) + ImGuiDataType_COUNT +}; + +// A cardinal direction +enum ImGuiDir : int +{ + ImGuiDir_None = -1, + ImGuiDir_Left = 0, + ImGuiDir_Right = 1, + ImGuiDir_Up = 2, + ImGuiDir_Down = 3, + ImGuiDir_COUNT +}; + +// A sorting direction +enum ImGuiSortDirection : ImU8 +{ + ImGuiSortDirection_None = 0, + ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. + ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. +}; + +// A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values. +// All our named keys are >= 512. Keys value 0 to 511 are left unused and were legacy native/opaque key values (< 1.87). +// Support for legacy keys was completely removed in 1.91.5. +// Read details about the 1.87+ transition : https://github.com/ocornut/imgui/issues/4921 +// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the latter are submitted via io.AddInputCharacter(). +// The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps. +enum ImGuiKey : int +{ + // Keyboard + ImGuiKey_None = 0, + ImGuiKey_NamedKey_BEGIN = 512, // First valid key value (other than 0) + + ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Insert, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Space, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, // Also see ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiMod_Alt, ImGuiMod_Super below! + ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, + ImGuiKey_Menu, + ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, + ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, + ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, + ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, + ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, + ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, + ImGuiKey_F13, ImGuiKey_F14, ImGuiKey_F15, ImGuiKey_F16, ImGuiKey_F17, ImGuiKey_F18, + ImGuiKey_F19, ImGuiKey_F20, ImGuiKey_F21, ImGuiKey_F22, ImGuiKey_F23, ImGuiKey_F24, + ImGuiKey_Apostrophe, // ' + ImGuiKey_Comma, // , + ImGuiKey_Minus, // - + ImGuiKey_Period, // . + ImGuiKey_Slash, // / + ImGuiKey_Semicolon, // ; + ImGuiKey_Equal, // = + ImGuiKey_LeftBracket, // [ + ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) + ImGuiKey_RightBracket, // ] + ImGuiKey_GraveAccent, // ` + ImGuiKey_CapsLock, + ImGuiKey_ScrollLock, + ImGuiKey_NumLock, + ImGuiKey_PrintScreen, + ImGuiKey_Pause, + ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, + ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, + ImGuiKey_KeypadDecimal, + ImGuiKey_KeypadDivide, + ImGuiKey_KeypadMultiply, + ImGuiKey_KeypadSubtract, + ImGuiKey_KeypadAdd, + ImGuiKey_KeypadEnter, + ImGuiKey_KeypadEqual, + ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" + ImGuiKey_AppForward, + ImGuiKey_Oem102, // Non-US backslash. + + // Gamepad + // (analog values are 0.0f to 1.0f) + // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) + // // XBOX | SWITCH | PLAYSTA. | -> ACTION + ImGuiKey_GamepadStart, // Menu | + | Options | + ImGuiKey_GamepadBack, // View | - | Share | + ImGuiKey_GamepadFaceLeft, // X | Y | Square | Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) + ImGuiKey_GamepadFaceRight, // B | A | Circle | Cancel / Close / Exit + ImGuiKey_GamepadFaceUp, // Y | X | Triangle | Text Input / On-screen Keyboard + ImGuiKey_GamepadFaceDown, // A | B | Cross | Activate / Open / Toggle / Tweak + ImGuiKey_GamepadDpadLeft, // D-pad Left | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadRight, // D-pad Right | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadUp, // D-pad Up | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadDown, // D-pad Down | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadL1, // L Bumper | L | L1 | Tweak Slower / Focus Previous (in Windowing mode) + ImGuiKey_GamepadR1, // R Bumper | R | R1 | Tweak Faster / Focus Next (in Windowing mode) + ImGuiKey_GamepadL2, // L Trigger | ZL | L2 | [Analog] + ImGuiKey_GamepadR2, // R Trigger | ZR | R2 | [Analog] + ImGuiKey_GamepadL3, // L Stick | L3 | L3 | + ImGuiKey_GamepadR3, // R Stick | R3 | R3 | + ImGuiKey_GamepadLStickLeft, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickRight, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickUp, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickDown, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadRStickLeft, // | | | [Analog] + ImGuiKey_GamepadRStickRight, // | | | [Analog] + ImGuiKey_GamepadRStickUp, // | | | [Analog] + ImGuiKey_GamepadRStickDown, // | | | [Analog] + + // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) + // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. + ImGuiKey_MouseLeft, ImGuiKey_MouseRight, ImGuiKey_MouseMiddle, ImGuiKey_MouseX1, ImGuiKey_MouseX2, ImGuiKey_MouseWheelX, ImGuiKey_MouseWheelY, + + // [Internal] Reserved for mod storage + ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, + + // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. + ImGuiKey_NamedKey_END, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, + + // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) + // - Any functions taking a ImGuiKeyChord parameter can binary-or those with regular keys, e.g. Shortcut(ImGuiMod_Ctrl | ImGuiKey_S). + // - Those are written back into io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper for convenience, + // but may be accessed via standard key API such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those + // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). + // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. + // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and + // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... + // - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. + ImGuiMod_None = 0, + ImGuiMod_Ctrl = 1 << 12, // Ctrl (non-macOS), Cmd (macOS) + ImGuiMod_Shift = 1 << 13, // Shift + ImGuiMod_Alt = 1 << 14, // Option/Menu + ImGuiMod_Super = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS) + ImGuiMod_Mask_ = 0xF000, // 4-bits + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was misleading (since named keys don't start at 0 anymore) + ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl + //ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 + //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 +#endif +}; + +// Flags for Shortcut(), SetNextItemShortcut(), +// (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) +// Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) +enum ImGuiInputFlags_ +{ + ImGuiInputFlags_None = 0, + ImGuiInputFlags_Repeat = 1 << 0, // Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. + + // Flags for Shortcut(), SetNextItemShortcut() + // - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. + // - Default policy is RouteFocused. Can select only 1 policy among all available. + ImGuiInputFlags_RouteActive = 1 << 10, // Route to active item only. + ImGuiInputFlags_RouteFocused = 1 << 11, // Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. + ImGuiInputFlags_RouteGlobal = 1 << 12, // Global route (unless a focused window or active item registered the route). + ImGuiInputFlags_RouteAlways = 1 << 13, // Do not register route, poll keys directly. + // - Routing options + ImGuiInputFlags_RouteOverFocused = 1 << 14, // Option: global route: higher priority than focused route (unless active item in focused route). + ImGuiInputFlags_RouteOverActive = 1 << 15, // Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. Ctrl+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. + ImGuiInputFlags_RouteUnlessBgFocused = 1 << 16, // Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. + ImGuiInputFlags_RouteFromRootWindow = 1 << 17, // Option: route evaluated from the point of view of root window rather than current window. + + // Flags for SetNextItemShortcut() + ImGuiInputFlags_Tooltip = 1 << 18, // Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) +}; + +// Configuration flags stored in io.ConfigFlags. Set by user/application. +enum ImGuiConfigFlags_ +{ + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate. + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse inputs and interactions. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + ImGuiConfigFlags_NoKeyboard = 1 << 6, // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states. + + // [BETA] Docking + ImGuiConfigFlags_DockingEnable = 1 << 7, // Docking enable flags. + + // [BETA] Viewports + // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. + ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends) + + // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21, // Application is using a touch screen instead of a mouse. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavMoveSetMousePos + ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavCaptureKeyboard + ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 14, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleFonts + ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 15, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleViewports +#endif +}; + +// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. +enum ImGuiBackendFlags_ +{ + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for instructions on how to upgrade your custom backend. + + // [BETA] Multi-Viewports + ImGuiBackendFlags_RendererHasViewports = 1 << 10, // Backend Renderer supports multiple viewports. + ImGuiBackendFlags_PlatformHasViewports = 1 << 11, // Backend Platform supports multiple viewports. + ImGuiBackendFlags_HasMouseHoveredViewport=1 << 12, // Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags_NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + ImGuiBackendFlags_HasParentViewport = 1 << 13, // Backend Platform supports honoring viewport->ParentViewport/ParentViewportId value, by applying the corresponding parent/child relation at the Platform level. +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, // Title bar + ImGuiCol_TitleBgActive, // Title bar when focused + ImGuiCol_TitleBgCollapsed, // Title bar when collapsed + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, // Checkbox tick and RadioButton circle + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_InputTextCursor, // InputText cursor/caret + ImGuiCol_TabHovered, // Tab background, when hovered + ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected + ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected + ImGuiCol_TabSelectedOverline, // Tab horizontal overline, when tab-bar is focused & tab is selected + ImGuiCol_TabDimmed, // Tab background, when tab-bar is unfocused & tab is unselected + ImGuiCol_TabDimmedSelected, // Tab background, when tab-bar is unfocused & tab is selected + ImGuiCol_TabDimmedSelectedOverline,//..horizontal overline, when tab-bar is unfocused & tab is selected + ImGuiCol_DockingPreview, // Preview overlay color when about to docking something + ImGuiCol_DockingEmptyBg, // Background color for empty node (e.g. CentralNode with no window docked into it) + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) + ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) + ImGuiCol_TableRowBg, // Table row background (even rows) + ImGuiCol_TableRowBgAlt, // Table row background (odd rows) + ImGuiCol_TextLink, // Hyperlink color + ImGuiCol_TextSelectedBg, // Selected text inside an InputText + ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines + ImGuiCol_DragDropTarget, // Rectangle border highlighting a drop target + ImGuiCol_DragDropTargetBg, // Rectangle background highlighting a drop target + ImGuiCol_UnsavedMarker, // Unsaved Document marker (in window title and tabs) + ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible + ImGuiCol_NavWindowingHighlight, // Highlight window when using Ctrl+Tab + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the Ctrl+Tab window list, when active + ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_COUNT, + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] + ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] + ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] + ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] +#endif +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +// During initialization or between frames, feel free to just poke into ImGuiStyle directly. +// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. +// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name -------------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign + ImGuiStyleVar_ChildRounding, // float ChildRounding + ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize + ImGuiStyleVar_PopupRounding, // float PopupRounding + ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_CellPadding, // ImVec2 CellPadding + ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize + ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_ScrollbarPadding, // float ScrollbarPadding + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_ImageRounding, // float ImageRounding + ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize + ImGuiStyleVar_TabRounding, // float TabRounding + ImGuiStyleVar_TabBorderSize, // float TabBorderSize + ImGuiStyleVar_TabMinWidthBase, // float TabMinWidthBase + ImGuiStyleVar_TabMinWidthShrink, // float TabMinWidthShrink + ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize + ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize + ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle + ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign + ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize + ImGuiStyleVar_TreeLinesRounding, // float TreeLinesRounding + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign + ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize + ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign + ImGuiStyleVar_SeparatorTextPadding, // ImVec2 SeparatorTextPadding + ImGuiStyleVar_DockingSeparatorSize, // float DockingSeparatorSize + ImGuiStyleVar_COUNT +}; + +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, // [Internal] + ImGuiButtonFlags_EnableNav = 1 << 3, // InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. +}; + +// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() +enum ImGuiColorEditFlags_ +{ + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. + ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + ImGuiColorEditFlags_NoColorMarkers = 1 << 11, // // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. + + // Alpha preview + // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview. + // - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. + // - The new flags may be combined better and allow finer controls. + ImGuiColorEditFlags_AlphaOpaque = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. + ImGuiColorEditFlags_AlphaNoBg = 1 << 13, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 14, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. + + // User Options (right-click on widget to change some of them). + ImGuiColorEditFlags_AlphaBar = 1 << 18, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). + ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " + ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " + ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. + ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. + + // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to + // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. + ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + + // [Internal] Masks + ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf, + ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiColorEditFlags_AlphaPreview = 0, // Removed in 1.91.8. This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set. +#endif + //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] +}; + +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +// (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText) +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). + ImGuiSliderFlags_NoInput = 1 << 7, // Disable Ctrl+Click or Enter key allowing to input text directly into the widget. + ImGuiSliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. + ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. + ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. + ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. + ImGuiSliderFlags_ColorMarkers = 1 << 12, // DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. + ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. +}; + +// Identify a mouse button. +// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. +enum ImGuiMouseButton_ +{ + ImGuiMouseButton_Left = 0, + ImGuiMouseButton_Right = 1, + ImGuiMouseButton_Middle = 2, + ImGuiMouseButton_COUNT = 5 +}; + +// Enumeration for GetMouseCursor() +// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) + ImGuiMouseCursor_ResizeNS, // When hovering over a horizontal border + ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column + ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_Wait, // When waiting for something to process/load. + ImGuiMouseCursor_Progress, // When waiting for something to process/load, but application is still interactive. + ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. + ImGuiMouseCursor_COUNT +}; + +// Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. +// Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() +// But that "Mouse" data can come from different source which occasionally may be useful for application to know about. +// You can submit a change of pointer type using io.AddMouseSourceEvent(). +enum ImGuiMouseSource : int +{ + ImGuiMouseSource_Mouse = 0, // Input is coming from an actual mouse. + ImGuiMouseSource_TouchScreen, // Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). + ImGuiMouseSource_Pen, // Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). + ImGuiMouseSource_COUNT +}; + +// Enumeration for ImGui::SetNextWindow***(), SetWindow***(), SetNextItem***() functions +// Represent a condition. +// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. +enum ImGuiCond_ +{ + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable), same as _None + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) + ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) + ImGuiCond_Appearing = 1 << 3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) +}; + +//----------------------------------------------------------------------------- +// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +//----------------------------------------------------------------------------- + +// Flags for ImGui::BeginTable() +// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The DEFAULT sizing policies are: +// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. +// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. +// - When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. +// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +// - Stretch Columns will share the remaining width according to their respective weight. +// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +// - When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed +// - Columns sizing policy allowed: Fixed/Auto mostly. +// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +// - Read on documentation at the top of imgui_tables.cpp for details. +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. + ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width, visibility and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). + // Decorations + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + // Sizing Policy (read above for defaults) + ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. + ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. + ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + // Sizing Extra Options + ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + // Clipping + ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + // Padding + ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. + ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + // Sorting + ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + // Miscellaneous + ImGuiTableFlags_HighlightHoveredColumn = 1 << 28, // Highlight column headers when hovered (may evolve into a fuller highlight) + + // [Internal] Combinations and masks + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, +}; + +// Flags for ImGui::TableSetupColumn() +enum ImGuiTableColumnFlags_ +{ + // Input configuration flags + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. + ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. + ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. + ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). + ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + ImGuiTableColumnFlags_AngledHeader = 1 << 18, // TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. + + // Output status flags, read-only via TableGetColumnFlags() + ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. + ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs + ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse + + // [Internal] Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) +}; + +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + + ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +// Sorting specification for one column of a table (sizeof == 12 bytes) +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImS16 ColumnIndex; // Index of the column + ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending + + ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Debug Logging into ShowDebugLogWindow(), tty and more. +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +#define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__) +#else +#define IMGUI_DEBUG_LOG(...) ((void)0) +#endif + +//----------------------------------------------------------------------------- +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + +//----------------------------------------------------------------------------- +// ImVector<> +// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). +//----------------------------------------------------------------------------- +// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. +// - We use std-like naming convention here, which is a little unusual for this codebase. +// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. +// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, +// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. +//----------------------------------------------------------------------------- + +IM_MSVC_RUNTIME_CHECKS_OFF +template +struct ImVector +{ + int Size; + int Capacity; + T* Data; + + // Provide standard typedefs but we don't use them ourselves. + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + // Constructors, destructor + inline ImVector() { Size = Capacity = 0; Data = NULL; } + inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (Data && src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } + inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything + + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything + inline void clear_delete() { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); } // Important: never called automatically! always explicit. + inline void clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); } // Important: never called automatically! always explicit. + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int size_in_bytes() const { return Size * (int)sizeof(T); } + inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } + inline int capacity() const { return Capacity; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return Data + Size; } + inline const T* end() const { return Data + Size; } + inline T& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } + inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } + inline void reserve_discard(int new_capacity) { if (new_capacity <= Capacity) return; if (Data) IM_FREE(Data); Data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); Capacity = new_capacity; } + + // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. + inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } + inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline int find_index(const T& v) const { const T* data_end = Data + Size; const T* it = find(v); if (it == data_end) return -1; const ptrdiff_t off = it - Data; return (int)off; } + inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; } + inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; } + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStyle +//----------------------------------------------------------------------------- +// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). +// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, +// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. +//----------------------------------------------------------------------------- + +struct ImGuiStyle +{ + // Font scaling + // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) + float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. + float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user. + float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. In docking branch: when io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + + float Alpha; // Global alpha applies to everything in Dear ImGui. + float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + ImVec2 WindowPadding; // Padding within a window. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float WindowBorderHoverPadding; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders. + ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. + float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. + float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) + float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 CellPadding; // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. + float ScrollbarRounding; // Radius of grab corners for scrollbar. + float ScrollbarPadding; // Padding of scrollbar grab within its frame (same for both axes). + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float ImageRounding; // Rounding of Image() calls. + float ImageBorderSize; // Thickness of border around Image() calls. + float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthBase; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + float TabMinWidthShrink; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy. + float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. + float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. + float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. + float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. + float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). + ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell + ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. + float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line. + float DragDropTargetRounding; // Radius of the drag and drop target frame. + float DragDropTargetBorderSize; // Thickness of the drag and drop target border. + float DragDropTargetPadding; // Size to expand the drag and drop target from actual target item size. + float ColorMarkerSize; // Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags_ColorMarkers. + ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + float SeparatorTextBorderSize; // Thickness of border in SeparatorText() + ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). + ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. + ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen. + ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). + bool DockingNodeHasCloseButton; // Docking node has their own CloseButton() to close all docked windows. + float DockingSeparatorSize; // Thickness of resizing border between docked windows + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + + // Colors + ImVec4 Colors[ImGuiCol_COUNT]; + + // Behaviors + // (It is possible to modify those fields mid-frame if specific behavior need it, unlike e.g. configuration fields in ImGuiIO) + float HoverStationaryDelay; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. + float HoverDelayShort; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay. + float HoverDelayNormal; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). " + ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. + + // [Internal] + float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). + float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work. + + // Functions + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); // Scale all spacing/padding/thickness values. Do not scale fonts. + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9. +#endif +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiIO +//----------------------------------------------------------------------------- +// Communicate most settings and inputs/outputs to Dear ImGui using this structure. +// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +// It is generally expected that: +// - initialization: backends and user code writes to ImGuiIO. +// - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. +//----------------------------------------------------------------------------- +// Also see ImGui::GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. +//----------------------------------------------------------------------------- + +// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. +struct ImGuiKeyData +{ + bool Down; // True for if key is down + float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) + float DownDurationPrev; // Last frame duration the key has been down + float AnalogValue; // 0.0f..1.0f for gamepad values +}; + +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Configuration // Default value + //------------------------------------------------------------------ + + ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. + ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ImVec2 DisplaySize; // // Main display size, in pixels (== GetMainViewport()->Size). May change every frame. + ImVec2 DisplayFramebufferScale; // = (1, 1) // Main display density. For retina display where window coordinates are different from framebuffer coordinates. This will affect font density + will end up in ImDrawData::FramebufferScale. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. + float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. + const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + void* UserData; // = NULL // Store your own data. + + // Font system + ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with Ctrl+Wheel. + + // Keyboard/Gamepad Navigation options + bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. + bool ConfigNavMoveSetMousePos; // = false // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. + bool ConfigNavCaptureKeyboard; // = true // Sets io.WantCaptureKeyboard when io.NavActive is set. + bool ConfigNavEscapeClearFocusItem; // = true // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on. + bool ConfigNavEscapeClearFocusWindow;// = false // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem). + bool ConfigNavCursorVisibleAuto; // = true // Using directional navigation key makes the cursor visible. Mouse click hides the cursor. + bool ConfigNavCursorVisibleAlways; // = false // Navigation cursor is always visible. + + // Docking options (when ImGuiConfigFlags_DockingEnable is set) + bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + bool ConfigDockingNoDockingOver; // = false // Simplified docking mode: disable window merging into a same tab-bar, so docking is limited to splitting windows. + bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + + // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) + bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. + bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. + bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). + bool ConfigViewportsNoDefaultParent; // = true // When false: set secondary viewports' ParentViewportId to main viewport ID by default. Expects the platform backend to setup a parent/child relationship between the OS windows based on this value. Some backend may ignore this. Set to true if you want viewports to automatically be parent of main viewport, otherwise all viewports will be top-level OS windows. + bool ConfigViewportsPlatformFocusSetsImGuiFocus;//= true // When a platform window is focused (e.g. using Alt+Tab, clicking Platform Title Bar), apply corresponding focus on imgui windows (may clear focus/active id from imgui windows location in other platform windows). In principle this is better enabled but we provide an opt-out, because some Linux window managers tend to eagerly focus windows (e.g. on mouse hover, or even a simple window pos/size change). + + // DPI/Scaling options + // This may keep evolving during 1.92.x releases. Expect some turbulence. + bool ConfigDpiScaleFonts; // = false // [EXPERIMENTAL] Automatically overwrite style.FontScaleDpi when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. + bool ConfigDpiScaleViewports; // = false // [EXPERIMENTAL] Scale Dear ImGui and Platform Windows when Monitor DPI changes. + + // Miscellaneous options + // (you can visualize and interact with all options in 'Demo->Configuration') + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. + bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). + bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). + bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. + bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) + bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] Ctrl+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order. + bool ConfigScrollbarScrollByPage; // = true // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location. + float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. + + // Inputs Behaviors + // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. + float KeyRepeatDelay; // = 0.275f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. + + //------------------------------------------------------------------ + // Debug options + //------------------------------------------------------------------ + + // Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] + // - Error recovery is provided as a way to facilitate: + // - Recovery after a programming error (native code or scripting language - the latter tends to facilitate iterating on code while running). + // - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. + // - Error recovery is not perfect nor guaranteed! It is a feature to ease development. + // You not are not supposed to rely on it in the course of a normal application run. + // - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT(). + // - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked! + // - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls! + // Otherwise it would severely hinder your ability to catch and correct mistakes! + // Read https://github.com/ocornut/imgui/wiki/Error-Handling for details. + // - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!) + // - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.) + // - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings. + bool ConfigErrorRecovery; // = true // Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled. + bool ConfigErrorRecoveryEnableAssert; // = true // Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR() + bool ConfigErrorRecoveryEnableDebugLog; // = true // Enable debug log output on recoverable errors. + bool ConfigErrorRecoveryEnableTooltip; // = true // Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled. + + // Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro. + // - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability. + // - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application. + // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version. + bool ConfigDebugIsDebuggerPresent; // = false // Enable various tools calling IM_DEBUG_BREAK(). + + // Tools to detect code submitting items with conflicting/duplicate IDs + // - Code should use PushID()/PopID() in loops, or append "##xx" to same-label identifiers. + // - Empty label e.g. Button("") == same ID as parent widget/node. Use Button("##xx") instead! + // - See FAQ https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system + bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message popup when multiple items have conflicting identifiers. + bool ConfigDebugHighlightIdConflictsShowItemPicker;//=true // Show "Item Picker" button in aforementioned popup. + + // Tools to test correct Begin/End and BeginChild/EndChild behaviors. + // - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX() + // - This is inconsistent with other BeginXXX functions and create confusion for many users. + // - We expect to update the API eventually. In the meanwhile we provide tools to facilitate checking user-code behavior. + bool ConfigDebugBeginReturnValueOnce;// = false // First-time calls to Begin()/BeginChild() will return false. NEEDS TO BE SET AT APPLICATION BOOT TIME if you don't want to miss windows. + bool ConfigDebugBeginReturnValueLoop;// = false // Some calls to Begin()/BeginChild() will return false. Will cycle through window depths then repeat. Suggested use: add "io.ConfigDebugBeginReturnValue = io.KeyShift" in your main loop then occasionally press SHIFT. Windows should be flickering while running. + + // Option to deactivate io.AddFocusEvent(false) handling. + // - May facilitate interactions with a debugger when focus loss leads to clearing inputs data. + // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. + bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. + + // Option to audit .ini data + bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) + + //------------------------------------------------------------------ + // Platform Identifiers + // (the imgui_impl_xxxx backend files are setting those up for you) + //------------------------------------------------------------------ + + // Nowadays those would be stored in ImGuiPlatformIO but we are leaving them here for legacy reasons. + // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. + const char* BackendPlatformName; // = NULL + const char* BackendRendererName; // = NULL + void* BackendPlatformUserData; // = NULL // User data for platform backend + void* BackendRendererUserData; // = NULL // User data for renderer backend + void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend + + //------------------------------------------------------------------ + // Input - Call before calling NewFrame() + //------------------------------------------------------------------ + + // Input Functions + IMGUI_API void AddKeyEvent(ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) + IMGUI_API void AddKeyAnalogEvent(ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. + IMGUI_API void AddMousePosEvent(float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) + IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change + IMGUI_API void AddMouseWheelEvent(float wheel_x, float wheel_y); // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left. + IMGUI_API void AddMouseSourceEvent(ImGuiMouseSource source); // Queue a mouse source change (Mouse/TouchScreen/Pen) + IMGUI_API void AddMouseViewportEvent(ImGuiID id); // Queue a mouse hovered viewport. Requires backend to set ImGuiBackendFlags_HasMouseHoveredViewport to call this (for multi-viewport support). + IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) + IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input + IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate + IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue a new characters input from a UTF-8 string + + IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. + IMGUI_API void SetAppAcceptingEvents(bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. + IMGUI_API void ClearEventsQueue(); // Clear all incoming events. + IMGUI_API void ClearInputKeys(); // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. + IMGUI_API void ClearInputMouse(); // Clear current mouse state. + + //------------------------------------------------------------------ + // Output - Updated by NewFrame() or EndFrame()/Render() + // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is + // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). + bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled. + bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! + bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. + bool NavVisible; // Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey_NavXXX events). + float Framerate; // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsRenderWindows; // Number of visible windows + int MetricsActiveWindows; // Number of active windows + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. + + //------------------------------------------------------------------ + // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). + + // Main Input State + // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold Shift to turn vertical scroll into horizontal scroll. + float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. + ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). + ImGuiID MouseHoveredViewport; // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag is much better (few backends can handle that). Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows). + bool KeyCtrl; // Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) + bool KeyShift; // Keyboard modifier down: Shift + bool KeyAlt; // Keyboard modifier down: Alt + bool KeySuper; // Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) + + // Other state maintained from data above + IO function calls + ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags). Read-only, updated by NewFrame() + ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this. + bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. + ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) + ImVec2 MouseClickedPos[5]; // Position at time of clicking + double MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) + ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + bool MouseReleased[5]; // Mouse button went from Down to !Down + double MouseReleasedTime[5]; // Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). + bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. + bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding Shift requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. + bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+Click that spawned a simulated right click + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. + bool AppFocusLost; // Only modify via AddFocusEvent() + bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents() + ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() + ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. + + // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. + // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). + // Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) + // Old (<1.87): ImGui::IsKeyPressed(MYPLATFORM_KEY_SPACE) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) + // Read https://github.com/ocornut/imgui/issues/4921 for details. + //int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. + //bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. + //float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. + //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92 (June 2025) + + // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. + // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + //void ClearInputCharacters() { InputQueueCharacters.resize(0); } // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. +#endif + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +//----------------------------------------------------------------------------- + +// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. +// The callback function should return 0 by default. +// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration +// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB +// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows +// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. +struct ImGuiInputTextCallbackData +{ + ImGuiContext* Ctx; // Parent UI context + ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + ImGuiID ID; // Widget ID // Read-only + + // Arguments for the different callback events + // - During Resize callback, Buf will be same as your input buffer. + // - However, during Completion/History/Always callback, Buf always points to our own internal data (it is not the same as your buffer)! Changes to it will be reflected into your own buffer shortly after the callback. + // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. + // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + bool EventActivated; // Input field just got activated // Read-only // [Always] + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] + char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! + int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land: == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + int CursorPos; // // Read-write // [Completion,History,Always] + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection + int SelectionEnd; // // Read-write // [Completion,History,Always] + + // Helper functions for text manipulation. + // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. + IMGUI_API ImGuiInputTextCallbackData(); + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + void SelectAll() { SelectionStart = 0; CursorPos = SelectionEnd = BufTextLen; } + void SetSelection(int s, int e) { IM_ASSERT(s >= 0 && s <= BufTextLen); IM_ASSERT(e >= 0 && e <= BufTextLen); SelectionStart = s; CursorPos = SelectionEnd = e; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>). + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +// Important: the content of this class is still highly WIP and likely to change and be refactored +// before we stabilize Docking features. Please be mindful if using this. +// Provide hints: +// - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +// - To the platform backend for OS level parent/child relationships of viewport. +// - To the docking system for various options and filtering. +struct ImGuiWindowClass +{ + ImGuiID ClassId; // User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ImGuiID ParentViewportId; // Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + ImGuiID FocusRouteParentWindowId; // ID of parent window for shortcut focus route evaluation, e.g. Shortcut() call from Parent Window will succeed when this window is focused. + ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiTabItemFlags TabItemFlagsOverrideSet; // [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags_Leading or ImGuiTabItemFlags_Trailing. + ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? + + ImGuiWindowClass() { memset(this, 0, sizeof(*this)); ParentViewportId = (ImGuiID)-1; DockingAllowUnclassed = true; } +}; + +// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() +struct ImGuiPayload +{ + // Members + void* Data; // Data (copied and owned by dear imgui) + int DataSize; // Data size + + // [Internal] + ImGuiID SourceId; // Source item id + ImGuiID SourceParentId; // Source parent id (if available) + int DataFrameCount; // Data timestamp + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) + bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) + bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. + + ImGuiPayload() { Clear(); } + void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } + bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsPreview() const { return Preview; } + bool IsDelivery() const { return Delivery; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +//----------------------------------------------------------------------------- + +// Helper: Unicode defines +#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. +#endif + +// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame. +// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } + + // [Internal] + struct ImGuiTextRange + { + const char* b; + const char* e; + + ImGuiTextRange() { b = e = NULL; } + ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; +}; + +// Helper: Growable text buffer for logging/accumulating text +// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') +struct ImGuiTextBuffer +{ + ImVector Buf; + IMGUI_API static char EmptyString[1]; + + ImGuiTextBuffer() { } + inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } + const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size ? Buf.Size - 1 : 0; } + bool empty() const { return Buf.Size <= 1; } + void clear() { Buf.clear(); } + void resize(int size) { if (Buf.Size > size) Buf.Data[size] = 0; Buf.resize(size ? size + 1 : 0, 0); } // Similar to resize(0) on ImVector: empty string but don't free buffer. + void reserve(int capacity) { Buf.reserve(capacity); } + const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } + IMGUI_API void append(const char* str, const char* str_end = NULL); + IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); + IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +}; + +// [Internal] Key+Value for ImGuiStorage +struct ImGuiStoragePair +{ + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + ImGuiStoragePair(ImGuiID _key, int _val) { key = _key; val_i = _val; } + ImGuiStoragePair(ImGuiID _key, float _val) { key = _key; val_f = _val; } + ImGuiStoragePair(ImGuiID _key, void* _val) { key = _key; val_p = _val; } +}; + +// Helper: Key->Value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1) +// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + // [Internal] + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + void Clear() { Data.clear(); } + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Advanced: for quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. + IMGUI_API void BuildSortByKey(); + // Obsolete: use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //typedef ::ImGuiStoragePair ImGuiStoragePair; // 1.90.8: moved type outside struct +#endif +}; + +// Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent) +enum ImGuiListClipperFlags_ +{ + ImGuiListClipperFlags_None = 0, + ImGuiListClipperFlags_NoSetTableRowCounters = 1 << 0, // [Internal] Disabled modifying table row counters. Avoid assumption that 1 clipper item == 1 table row. +}; + +// Helper: Manually clip large list of items. +// If you have lots evenly spaced items and you have random access to the list, you can perform coarse +// clipping based on visibility to only submit items that are in view. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally +// fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily +// scale using lists with tens of thousands of items without a problem) +// Usage: +// ImGuiListClipper clipper; +// clipper.Begin(1000); // We have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// Generally what happens is: +// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. +// - User code submit that one element. +// - Clipper can measure the height of the first element +// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. +// - User code submit visible elements. +// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. +struct ImGuiListClipper +{ + ImGuiContext* Ctx; // Parent UI context + int DisplayStart; // First item to display, updated by each call to Step() + int DisplayEnd; // End of items to display (exclusive) + int ItemsCount; // [Internal] Number of items + float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it + double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. + void* TempData; // [Internal] Internal data + ImGuiListClipperFlags Flags; // [Internal] Flags, currently not yet well exposed. + + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step, and you can call SeekCursorForItem() manually if you need) + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). + IMGUI_API ImGuiListClipper(); + IMGUI_API ~ImGuiListClipper(); + IMGUI_API void Begin(int items_count, float items_height = -1.0f); + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + + // Call IncludeItemByIndex() or IncludeItemsByIndex() *BEFORE* first call to Step() if you need a range of items to not be clipped, regardless of their visibility. + // (Due to alignment / padding of certain items it is possible that an extra item may be included on either end of the display range). + inline void IncludeItemByIndex(int item_index) { IncludeItemsByIndex(item_index, item_index + 1); } + IMGUI_API void IncludeItemsByIndex(int item_begin, int item_end); // item_end is exclusive e.g. use (42, 42+1) to make item 42 never clipped. + + // Seek cursor toward given item. This is automatically called while stepping. + // - The only reason to call this is: you can use ImGuiListClipper::Begin(INT_MAX) if you don't know item count ahead of time. + // - In this case, after all steps are done, you'll want to call SeekCursorForItem(item_count). + IMGUI_API void SeekCursorForItem(int item_index); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] + //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] + //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] +#endif +}; + +// Helpers: ImVec2/ImVec4 operators +// - It is important that we are keeping those disabled by default so they don't leak in user space. +// - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. +// - We intentionally provide ImVec2*float but not float*ImVec2: this is rare enough and we want to reduce the surface for possible user mistake. +#ifdef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED +IM_MSVC_RUNTIME_CHECKS_OFF +// ImVec2 operators +inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } +inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +// ImVec4 operators +inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } +inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } +inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } +inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } +IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Helpers macros to generate 32-bit encoded colors +// - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. +// - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9. +#ifndef IM_COL32_R_SHIFT +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<> IM_COL32_R_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * (1.0f / 255.0f)) {} + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) +//----------------------------------------------------------------------------- + +// Multi-selection system +// Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select +// - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. +// - This system implements standard multi-selection idioms (Ctrl+Mouse/Keyboard, Shift+Mouse/Keyboard, etc) +// with support for clipper (skipping non-visible items), box-select and many other details. +// - Selectable(), Checkbox() are supported but custom widgets may use it as well. +// - TreeNode() is technically supported but... using this correctly is more complicated: you need some sort of linear/random access to your tree, +// which is suited to advanced trees setups also implementing filters and clipper. We will work toward simplifying and demoing it. +// - In the spirit of Dear ImGui design, your code owns actual selection data. +// This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. +// About ImGuiSelectionBasicStorage: +// - This is an optional helper to store a selection state and apply selection requests. +// - It is used by our demos and provided as a convenience to quickly implement multi-selection. +// Usage: +// - Identify submitted items with SetNextItemSelectionUserData(), most likely using an index into your current data-set. +// - Store and maintain actual selection data using persistent object identifiers. +// - Usage flow: +// BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (2) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. +// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. +// LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. +// END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (6) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 2. +// If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. +// About ImGuiSelectionUserData: +// - This can store an application-defined identifier (e.g. index or pointer) submitted via SetNextItemSelectionUserData(). +// - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. +// - Most applications will store an object INDEX, hence the chosen name and type. Storing an index is natural, because +// SetRange requests will give you two end-points and you will need to iterate/interpolate between them to update your selection. +// - However it is perfectly possible to store a POINTER or another IDENTIFIER inside ImGuiSelectionUserData. +// Our system never assume that you identify items by indices, it never attempts to interpolate between two values. +// - If you enable ImGuiMultiSelectFlags_NoRangeSelect then it is guaranteed that you will never have to interpolate +// between two ImGuiSelectionUserData, which may be a convenient way to use part of the feature with less code work. +// - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, +// being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. + +// Flags for BeginMultiSelect() +enum ImGuiMultiSelectFlags_ +{ + ImGuiMultiSelectFlags_None = 0, + ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable Ctrl+A shortcut to select all. + ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. + ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes). + ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes). + ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item. + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This is slower: alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 10, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 11, // Scope for _BoxSelect and _ClearOnClickVoid is whole window (Default). Use if BeginMultiSelect() covers a whole window or used a single time in same window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 12, // Scope for _BoxSelect and _ClearOnClickVoid is rectangle encompassing BeginMultiSelect()/EndMultiSelect(). Use if BeginMultiSelect() is called multiple times in same window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. + ImGuiMultiSelectFlags_NavWrapX = 1 << 16, // [Temporary] Enable navigation wrapping on X axis. Provided as a convenience because we don't have a design for the general Nav API for this yet. When the more general feature be public we may obsolete this flag in favor of new one. + ImGuiMultiSelectFlags_NoSelectOnRightClick = 1 << 17, // Disable default right-click processing, which selects item on mouse down, and is designed for context-menus. +}; + +// Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). +// This mainly contains a list of selection requests. +// - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. +// - Some fields are only useful if your list is dynamic and allows deletion (getting post-deletion focus/state right is shown in the demo) +// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. +struct ImGuiMultiSelectIO +{ + //------------------------------------------// BeginMultiSelect / EndMultiSelect + ImVector Requests; // ms:w, app:r / ms:w app:r // Requests to apply to your selection data. + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (often the first selected item) must never be clipped: use clipper.IncludeItemByIndex() to ensure it is submitted. + ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). + bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + int ItemsCount; // ms:w, app:r / app:r // 'int items_count' parameter to BeginMultiSelect() is copied here for convenience, allowing simpler calls to your ApplyRequests handler. Not used internally. +}; + +// Selection request type +enum ImGuiSelectionRequestType +{ + ImGuiSelectionRequestType_None = 0, + ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true). We cannot set RangeFirstItem/RangeLastItem as its contents is entirely up to user (not necessarily an index) + ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items (inclusive) based on value of Selected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. +}; + +// Selection request item +struct ImGuiSelectionRequest +{ + //------------------------------------------// BeginMultiSelect / EndMultiSelect + ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. + bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) + ImS8 RangeDirection; // / ms:w app:r // Parameter for SetRange request: +1 when RangeFirstItem comes before RangeLastItem, -1 otherwise. Useful if you want to preserve selection order on a backward Shift+Click. + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom). + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top). Inclusive! +}; + +// Optional helper to store multi-selection state + apply multi-selection requests. +// - Used by our demos and provided as a convenience to easily implement basic multi-selection. +// - Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' +// Or you can check 'if (Contains(id)) { ... }' for each possible object if their number is not too high to iterate. +// - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. +// To store a multi-selection, in your application you could: +// - Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. +// - Use your own external storage: e.g. std::set, std::vector, interval trees, intrusively stored selection etc. +// In ImGuiSelectionBasicStorage we: +// - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) +// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. +// - use decently optimized logic to allow queries and insertion of very large selection sets. +// - do not preserve selection order. +// Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. +// Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. +// See https://github.com/ocornut/imgui/wiki/Multi-Select for details and pseudo-code using this helper. +struct ImGuiSelectionBasicStorage +{ + // Members + int Size; // // Number of selected items, maintained by this helper. + bool PreserveOrder; // = false // GetNextSelectedItem() will return ordered selection (currently implemented by two additional sorts of selection. Could be improved) + void* UserData; // = NULL // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; + int _SelectionOrder;// [Internal] Increasing counter to store selection order + ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). + + // Methods + IMGUI_API ImGuiSelectionBasicStorage(); + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() + IMGUI_API bool Contains(ImGuiID id) const; // Query if an item id is in selection. + IMGUI_API void Clear(); // Clear selection + IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections + IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) + IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' + inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. +}; + +// Optional helper to apply multi-selection requests to existing randomly accessible storage. +// Convenient if you want to quickly wire multi-select API on e.g. an array of bool or items storing their own selection state. +struct ImGuiSelectionExternalStorage +{ + // Members + void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } + + // Methods + IMGUI_API ImGuiSelectionExternalStorage(); + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests by using AdapterSetItemSelected() calls +}; + +//----------------------------------------------------------------------------- +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) +#endif + +// ImDrawIdx: vertex index. [Compile-time configurable type] +// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). +// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) +#endif + +// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +// you can poke into the draw list for that! Draw callback may be useful for example to: +// A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. +#ifndef ImDrawCallback +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +#endif + +// Special Draw callback value to request renderer backend to reset the graphics/render state. +// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. +// This is useful, for example, if you submitted callbacks which you know have altered the render state and you want it to be restored. +// Render state is not reset by default because they are many perfectly useful way of altering render state (e.g. changing shader/blending settings before an Image call). +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) + +// Typically, 1 command = 1 GPU draw call (unless command is a callback) +// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Backends made for <1.71. will typically ignore the VtxOffset fields. +// - The ClipRect/TexRef/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +struct ImDrawCmd +{ + ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureRef TexRef; // 16 // Reference to a font/texture atlas (where backend called ImTextureData::SetTexID()) or to a user-provided texture ID (via e.g. ImGui::Image() calls). Both will lead to a ImTextureID value. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. + unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // Callback user data (when UserCallback != NULL). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored. + int UserCallbackDataSize; // 4 // Size of callback user data when using storage, otherwise 0. + int UserCallbackDataOffset;// 4 // [Internal] Offset of callback user data when using storage, otherwise -1. + + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed + + // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) + // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! + inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID) +}; + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared at the time you'd want to set your type up. +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// [Internal] For use by ImDrawList +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureRef TexRef; + unsigned int VtxOffset; +}; + +// [Internal] For use by ImDrawListSplitter +struct ImDrawChannel +{ + ImVector _CmdBuffer; + ImVector _IdxBuffer; +}; + +// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. +// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. +struct ImDrawListSplitter +{ + int _Current; // Current channel number (0) + int _Count; // Number of active channels (1+) + ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) + + inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } + inline ~ImDrawListSplitter() { ClearFreeMemory(); } + inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame + IMGUI_API void ClearFreeMemory(); + IMGUI_API void Split(ImDrawList* draw_list, int count); + IMGUI_API void Merge(ImDrawList* draw_list); + IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); +}; + +// Flags for ImDrawList functions +// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) +enum ImDrawFlags_ +{ + ImDrawFlags_None = 0, + ImDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. + ImDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. + ImDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, +}; + +// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. +}; + +// Draw command list +// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, +// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to +// access the current window draw list and draw custom primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). +// You are totally free to apply whatever transformation matrix you want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!) +// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + + // [Internal, used while building lists] + unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _Path; // [Internal] current path building + ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureStack; // [Internal] + ImVector _CallbacksDataBuf; // [Internal] + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + const char* _OwnerName; // Pointer to owner window's name for debugging + + // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData(). + // (advanced: you may create and use your own ImDrawListSharedData so you can use ImDrawList without ImGui, but that's more involved) + IMGUI_API ImDrawList(ImDrawListSharedData* shared_data); + IMGUI_API ~ImDrawList(); + + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTexture(ImTextureRef tex_ref); + IMGUI_API void PopTexture(); + inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } + inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } + + // Primitives + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. + // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. + // In future versions we will use textures to provide cheaper and higher-quality circles. + // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); + IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); + IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) + + // General polygon + // - Only simple polygons are supported by filling functions (no self-intersections, no holes). + // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); + IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); + + // Image primitives + // - Read FAQ to understand what ImTextureID/ImTextureRef are. + // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. + // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. + IMGUI_API void AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() + // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + // so e.g. 'PathArcTo(center, radius, PI * -0.5f, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5f)' won't have correct anti-aliasing when followed by PathFillConvex(). + inline void PathClear() { _Path.Size = 0; } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; } + IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); + IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse + IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points) + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0); + + // Advanced: Draw Callbacks + // - May be used to alter render state (change sampler, blending, current shader). May be used to emit custom rendering commands (difficult to do correctly, but possible). + // - Use special ImDrawCallback_ResetRenderState callback to instruct backend to reset its render state to the default. + // - Your rendering loop must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. All standard backends are honoring this. + // - For some backends, the callback may access selected render-states exposed by the backend in a ImGui_ImplXXXX_RenderState structure pointed to by platform_io.Renderer_RenderState. + // - IMPORTANT: please be mindful of the different level of indirection between using size==0 (copying argument) and using size>0 (copying pointed data into a buffer). + // - If userdata_size == 0: we copy/store the 'userdata' argument as-is. It will be available unmodified in ImDrawCmd::UserCallbackData during render. + // - If userdata_size > 0, we copy/store 'userdata_size' bytes pointed to by 'userdata'. We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData will point inside that buffer so you have to retrieve data from there. Your callback may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data. + // - Support for userdata_size > 0 was added in v1.91.4, October 2024. So earlier code always only allowed to copy/store a simple void*. + IMGUI_API void AddCallback(ImDrawCallback callback, void* userdata, size_t userdata_size = 0); + + // Advanced: Miscellaneous + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club instead. + + // Advanced: Channels + // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) + // - This API shouldn't have been in ImDrawList in the first place! + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. + // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. + inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } + inline void ChannelsMerge() { _Splitter.Merge(this); } + inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } + + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.0 + inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.0 +#endif + //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) + //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) + //inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) + //inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + + // [Internal helpers] + IMGUI_API void _SetDrawListSharedData(ImDrawListSharedData* data); + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _TryMergeDrawCmds(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTexture(); + IMGUI_API void _OnChangedVtxOffset(); + IMGUI_API void _SetTexture(ImTextureRef tex_ref); + IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; + IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); + IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); +}; + +// All draw data to render a Dear ImGui frame +// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + int CmdListsCount; // == CmdLists.Size. (OBSOLETE: exists for legacy reasons). Number of ImDrawList* to render. + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. + ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) + ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). + ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overridden or set to NULL if you want to manually update textures. + + // Functions + ImDrawData() { Clear(); } + IMGUI_API void Clear(); + IMGUI_API void AddDrawList(ImDrawList* draw_list); // Helper to add an external draw list into an existing ImDrawData. + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +//----------------------------------------------------------------------------- +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +//----------------------------------------------------------------------------- +// In principle, the only data types that user/application code should care about are 'ImTextureRef' and 'ImTextureID'. +// They are defined above in this header file. Read their description to the difference between ImTextureRef and ImTextureID. +// FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM. +//----------------------------------------------------------------------------- + +#undef Status // X11 headers are leaking this. + +// We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. +// Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems. +enum ImTextureFormat +{ + ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight +}; + +// Status of a texture to communicate with Renderer Backend. +enum ImTextureStatus +{ + ImTextureStatus_OK, + ImTextureStatus_Destroyed, // Backend destroyed the texture. + ImTextureStatus_WantCreate, // Requesting backend to create the texture. Set status OK when done. + ImTextureStatus_WantUpdates, // Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + ImTextureStatus_WantDestroy, // Requesting backend to destroy the texture. Set status to Destroyed when done. +}; + +// Coordinates of a rectangle within a texture. +// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to the graphics system. +// You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box. +struct ImTextureRect +{ + unsigned short x, y; // Upper-left coordinates of rectangle to update + unsigned short w, h; // Size of rectangle to update (in pixels) +}; + +// Specs and pixel storage for a texture used by Dear ImGui. +// This is only useful for (1) core library and (2) backends. End-user/applications do not need to care about this. +// Renderer Backends will create a GPU-side version of this. +// Why does we store two identifiers: TexID and BackendUserData? +// - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. +// - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. + // In columns below: who reads/writes each fields? 'r'=read, 'w'=write, 'core'=main library, 'backend'=renderer backend +struct ImTextureData +{ + //------------------------------------------ core / backend --------------------------------------- + int UniqueID; // w - // [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID. + ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function. + ImTextureFormat Format; // w r // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 + int Width; // w r // Texture width + int Height; // w r // Texture height + int BytesPerPixel; // w r // 4 or 1 + unsigned char* Pixels; // w r // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + ImTextureRect UsedRect; // w r // Bounding box encompassing all past and queued Updates[]. + ImTextureRect UpdateRect; // w r // Bounding box encompassing all queued Updates[]. + ImVector Updates; // w r // Array of individual updates. + int UnusedFrames; // w r // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. + unsigned short RefCount; // w r // Number of contexts using this texture. Used during backend shutdown. + bool UseColors; // w r // Tell whether our texture data is known to use colors (rather than just white + alpha). + bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. + + // Functions + ImTextureData() { memset(this, 0, sizeof(*this)); Status = ImTextureStatus_Destroyed; TexID = ImTextureID_Invalid; } + ~ImTextureData() { DestroyPixels(); } + IMGUI_API void Create(ImTextureFormat format, int w, int h); + IMGUI_API void DestroyPixels(); + void* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } + void* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } + int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } + int GetPitch() const { return Width * BytesPerPixel; } + ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; } + ImTextureID GetTexID() const { return TexID; } + + // Called by Renderer backend + // - Call SetTexID() and SetStatus() after honoring texture requests. Never modify TexID and Status directly! + // - A backend may decide to destroy a texture that we did not request to destroy, which is fine (e.g. freeing resources), but we immediately set the texture back in _WantCreate mode. + void SetTexID(ImTextureID tex_id) { TexID = tex_id; } + void SetStatus(ImTextureStatus status) { Status = status; if (status == ImTextureStatus_Destroyed && !WantDestroyNextFrame && Pixels != nullptr) Status = ImTextureStatus_WantCreate; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) +//----------------------------------------------------------------------------- + +// A font input/source (we may rename this to ImFontSource in the future) +struct ImFontConfig +{ + // Data Source + char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) + void* FontData; // // TTF/OTF data + int FontDataSize; // // TTF/OTF data size + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). SINCE 1.92, THE DATA NEEDS TO PERSIST FOR WHOLE DURATION OF ATLAS. + + // Options + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. + ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + float SizePixels; // // Output size in pixels for rasterizer (more or less maps to the resulting font height). + const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. + //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled + ImU32 FontNo; // 0 // Index of font within TTF/OTF file + unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Use FontLoaderFlags. + float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. + float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. + float ExtraSizeScale; // 1.0f // Extra rasterizer scale over SizePixels. + + // [Internal] + ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) + ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) + const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas) + void* FontLoaderData; // Font loader opaque storage (per font config) + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + bool PixelSnapV; // true // [Obsoleted in 1.91.6] Align Scaled GlyphOffset.y to pixel boundaries. +#endif + IMGUI_API ImFontConfig(); +}; + +// Hold rendering data for one glyph. +// (Note: some language parsers may fail to convert the bitfield members, in this case maybe drop store a single u32 or we can rework this) +struct ImFontGlyph +{ + unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) + unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. + unsigned int SourceIdx : 4; // Index of source in parent font + unsigned int Codepoint : 26; // 0x0000..0x10FFFF + float AdvanceX; // Horizontal distance to advance cursor/layout position. + float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. + float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. + int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) + + ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } +}; + +// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). +// This is essentially a tightly packed of vector of 64k booleans = 8KB storage. +struct ImFontGlyphRangesBuilder +{ + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + + ImFontGlyphRangesBuilder() { Clear(); } + inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges +}; + +// An opaque identifier to a rectangle in the atlas. -1 when invalid. +// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. +typedef int ImFontAtlasRectId; +#define ImFontAtlasRectId_Invalid -1 + +// Output of ImFontAtlas::GetCustomRect() when using custom rectangles. +// Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef +// (this is in theory derived from ImTextureRect but we use separate structures for reasons) +struct ImFontAtlasRect +{ + unsigned short x, y; // Position (in current texture) + unsigned short w, h; // Size + ImVec2 uv0, uv1; // UV coordinates (in current texture) + + ImFontAtlasRect() { memset(this, 0, sizeof(*this)); } +}; + +// Flags for ImFontAtlas build +enum ImFontAtlasFlags_ +{ + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). +}; + +// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +// - One or more fonts. +// - Custom graphics data needed to render the shapes needed by Dear ImGui. +// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). +// - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you. +// It is the rendering backend responsibility to upload texture into your graphics API: +// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance. +// - Backend then set ImTextureData's TexID and BackendUserData. +// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID/ImTextureRef for more details. +// Legacy path: +// - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. +// Common pitfalls: +// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the +// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. +// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. +// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, +// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. +// - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future! +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); // Selects between AddFontDefaultVector() and AddFontDefaultBitmap(). + IMGUI_API ImFont* AddFontDefaultVector(const ImFontConfig* font_cfg = NULL); // Embedded scalable font. Recommended at any higher size. + IMGUI_API ImFont* AddFontDefaultBitmap(const ImFontConfig* font_cfg = NULL); // Embedded classic pixel-clean font. Recommended at Size 13px with no scaling. + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void RemoveFont(ImFont* font); + + IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures). + IMGUI_API void CompactCache(); // Compact cached glyphs and texture. + IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. + + // As we are transitioning toward a new font system, we expect to obsolete those soon: + IMGUI_API void ClearInputData(); // [OBSOLETE] Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). + IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy path for build atlas + retrieving pixel data. + // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // - The pitch is always = Width * BytesPerPixels (1 or 4) + // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste). + // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures: + // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed. + // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid); TexRef._TexData->TexID = id; } // Called by legacy backends. May be called before texture creation. + void SetTexID(ImTextureRef id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid && id._TexData == NULL); TexRef._TexData->TexID = id._TexID; } // Called by legacy backends. + bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent.. +#endif + + //------------------------------------------- + // Glyph Ranges + //------------------------------------------- + + // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_RendererHasTextures! + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. + // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. + // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. + IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters +#endif + + //------------------------------------------- + // [ALPHA] Custom Rectangles/Glyphs API + //------------------------------------------- + + // Register and retrieve custom rectangles + // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. + // - Since 1.92.0, packing is done immediately in the function call (previously packing was done during the Build call) + // - You can render your pixels into the texture right after calling the AddCustomRect() functions. + // - VERY IMPORTANT: + // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions. + // - IT WILL INVALIDATE RECTANGLE DATA SUCH AS UV COORDINATES. Always use latest values from GetCustomRect(). + // - UV coordinates are associated to the current texture identifier aka 'atlas->TexRef'. Both TexRef and UV coordinates are typically changed at the same time. + // - If you render colored output into your custom rectangles: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. + // - Read docs/FONTS.md for more details about using colorful icons. + // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. + // - (Pre-1.92 names) ------------> (1.92 names) + // - GetCustomRectByIndex() --> Use GetCustomRect() + // - CalcCustomRectUV() --> Use GetCustomRect() and read uv0, uv1 fields. + // - AddCustomRectRegular() --> Renamed to AddCustomRect() + // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig + // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect + IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height, ImFontAtlasRect* out_r = NULL);// Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. + IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected. + IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! + + //------------------------------------------- + // Members + //------------------------------------------- + + // Input + ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) + ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). + int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. + int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. + int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. + int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192. + void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + + // Output + // - Because textures are dynamically created/resized, the current texture identifier may changed at *ANY TIME* during the frame. + // - This should not affect you as you can always use the latest value. But note that any precomputed UV coordinates are only valid for the current TexRef. +#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef(). +#else + union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.0. +#endif + ImTextureData* TexData; // Latest texture. + + // [Internal] + ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! + bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. + bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. + bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. + ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + ImVector Sources; // Source/configuration data + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + int TexNextUniqueID; // Next value to be stored in TexData->UniqueID + int FontNextUniqueID; // Next value to be stored in ImFont->FontID + ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. + ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. + const ImFontLoader* FontLoader; // Font loader opaque interface (default to use FreeType when IMGUI_ENABLE_FREETYPE is defined, otherwise default to use stb_truetype). Use SetFontLoader() to change this at runtime. + const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name + void* FontLoaderData; // Font backend opaque storage + unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). + int RefCount; // Number of contexts using this atlas + ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. + + // [Obsolete] +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. + ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API + inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.0 + inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.0 + inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.0 + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.0: Use custom ImFontLoader in ImFontConfig + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.0 +#endif + //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.0: Renamed to FontLoaderFlags. + //int TexDesiredWidth; // OBSOLETED in 1.92.0: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.0 + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +}; + +// Font runtime data for a given size +// Important: pointers to ImFontBaked are only valid for the current frame. +struct ImFontBaked +{ + // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). + float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX + float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading) + float RasterizerDensity; // 4 // in // Density this is baked at + + // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) + ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // All glyphs. + int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar + + // [Internal] Members: Cold + float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) + unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + unsigned int WantDestroy:1; // 0 // // Queued for destroy + unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls. + unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantagous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw. + int LastUsedFrame; // 4 // // Record of that time this was bounds + ImGuiID BakedId; // 4 // // Unique ID for this baked storage + ImFont* OwnerFont; // 4-8 // in // Parent font + void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. + + // Functions + IMGUI_API ImFontBaked(); + IMGUI_API void ClearOutputData(); + IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return U+FFFD glyph if requested glyph doesn't exists. + IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist + IMGUI_API float GetCharAdvance(ImWchar c); + IMGUI_API bool IsGlyphLoaded(ImWchar c); +}; + +// Font flags +// (in future versions as we redesign font loading API, this will become more important and better documented. for now please consider this as internal/advanced use) +enum ImFontFlags_ +{ + ImFontFlags_None = 0, + ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. + ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. +}; + +// Font runtime data and rendering +// - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +// - Since 1.92.0 a font may be rendered as any size! Therefore a font doesn't have one specific size. +// - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size. +// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). +struct ImFont +{ + // [Internal] Members: Hot ~12-20 bytes + ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + ImFontAtlas* OwnerAtlas; // 4-8 // What we have been loaded into. + ImFontFlags Flags; // 4 // Font flags. + float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font. + + // [Internal] Members: Cold ~24-52 bytes + // Conceptually Sources[] is the list of font sources merged to create this font. + ImGuiID FontId; // Unique identifier for the font + float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). + ImVector Sources; // 16 // in // List of sources. Pointers within OwnerAtlas->Sources[] + ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). + ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') + ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() +#endif + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API bool IsGlyphInFont(ImWchar c); + bool IsLoaded() const { return OwnerAtlas != NULL; } + const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. + + // [Internal] Don't use! + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** out_remaining = NULL); + IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip = NULL); + IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, ImDrawTextFlags flags = 0); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, text, text_end, wrap_width); } +#endif + + // [Internal] Don't use! + IMGUI_API void ClearOutputData(); + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. + IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); +}; + +// This is provided for consistency (but we don't actually use this) +inline ImTextureID ImTextureRef::GetTexID() const +{ + IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid)); + return _TexData ? _TexData->TexID : _TexID; +} + +// Using an indirection to avoid patching ImDrawCmd after a SetTexID() call (but this could be an alternative solution too) +inline ImTextureID ImDrawCmd::GetTexID() const +{ + // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) + // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[]. + ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; // == TexRef.GetTexID() above. + if (TexRef._TexData != NULL) + IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"); + return tex_id; +} + +//----------------------------------------------------------------------------- +// [SECTION] Viewports +//----------------------------------------------------------------------------- + +// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. +enum ImGuiViewportFlags_ +{ + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) + ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Is created/managed by the user application? (rather than our backend) + ImGuiViewportFlags_NoDecoration = 1 << 3, // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips) + ImGuiViewportFlags_NoTaskBarIcon = 1 << 4, // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags_ViewportsNoTaskBarIcon is set) + ImGuiViewportFlags_NoFocusOnAppearing = 1 << 5, // Platform Window: Don't take focus when created. + ImGuiViewportFlags_NoFocusOnClick = 1 << 6, // Platform Window: Don't take focus when clicked on. + ImGuiViewportFlags_NoInputs = 1 << 7, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + ImGuiViewportFlags_NoRendererClear = 1 << 8, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + ImGuiViewportFlags_NoAutoMerge = 1 << 9, // Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + ImGuiViewportFlags_TopMost = 1 << 10, // Platform Window: Display on top (for tooltips only). + ImGuiViewportFlags_CanHostOtherWindows = 1 << 11, // Viewport can host multiple imgui windows (secondary viewports are associated to a single window). // FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". + + // Output status flags (from Platform) + ImGuiViewportFlags_IsMinimized = 1 << 12, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + ImGuiViewportFlags_IsFocused = 1 << 13, // Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) +}; + +// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +// - With multi-viewport enabled, we extend this concept to have multiple active viewports. +// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +// - About Main Area vs Work Area: +// - Main Area = entire viewport. +// - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +// - Windows are generally trying to stay within the Work Area of their host viewport. +struct ImGuiViewport +{ + ImGuiID ID; // Unique identifier for the viewport + ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ + ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 FramebufferScale; // Density of the viewport for Retina display (always 1,1 on Windows, may be 2,2 etc on macOS/iOS). This will affect font rasterizer density. + ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + float DpiScale; // 1.0f = 96 DPI = No extra scale. + ImGuiID ParentViewportId; // (Advanced) 0: no parent. Instruct the platform backend to setup a parent/child relationship between platform windows. + ImGuiViewport* ParentViewport; // (Advanced) Direct shortcut to ImGui::FindViewportByID(ParentViewportId). NULL: no parent. + ImDrawData* DrawData; // The ImDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame(). + + // Platform/Backend Dependent Data + // Our design separate the Renderer and Platform backends to facilitate combining default backends with each others. + // When our create your own backend for a custom engine, it is possible that both Renderer and Platform will be handled + // by the same system and you may not need to use all the UserData/Handle fields. + // The library never uses those fields, they are merely storage to facilitate backend implementation. + void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function. + void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function. + void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND for Win32 backend, Uint32 WindowID for SDL, GLFWWindow* for GLFW), for FindViewportByPlatformHandle(). + void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (always HWND on Win32 platform, unused for other platforms). + bool PlatformWindowCreated; // Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. + bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) + bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) + bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) + + ImGuiViewport() { memset(this, 0, sizeof(*this)); } + ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } + + // Helpers + ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } + ImVec2 GetWorkCenter() const { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +//----------------------------------------------------------------------------- + +// [BETA] (Optional) Multi-Viewport Support! +// If you are new to Dear ImGui and trying to integrate it into your engine, you can probably ignore this for now. +// +// This feature allows you to seamlessly drag Dear ImGui windows outside of your application viewport. +// This is achieved by creating new Platform/OS windows on the fly, and rendering into them. +// Dear ImGui manages the viewport structures, and the backend create and maintain one Platform/OS window for each of those viewports. +// +// See Recap: https://github.com/ocornut/imgui/wiki/Multi-Viewports +// See Glossary https://github.com/ocornut/imgui/wiki/Glossary for details about some of the terminology. +// +// About the coordinates system: +// - When multi-viewports are enabled, all Dear ImGui coordinates become absolute coordinates (same as OS coordinates!) +// - So e.g. ImGui::SetNextWindowPos(ImVec2(0,0)) will position a window relative to your primary monitor! +// - If you want to position windows relative to your main application viewport, use ImGui::GetMainViewport()->Pos as a base position. +// +// Steps to use multi-viewports in your application, when using a default backend from the examples/ folder: +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: The backend initialization will setup all necessary ImGuiPlatformIO's functions and update monitors info every frame. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// Steps to use multi-viewports in your application, when using a custom backend: +// - Important: THIS IS NOT EASY TO DO and comes with many subtleties not described here! +// It's also an experimental feature, so some of the requirements may evolve. +// Consider using default backends if you can. Either way, carefully follow and refer to examples/ backends for details. +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: Hook ImGuiPlatformIO's Platform_* and Renderer_* callbacks (see below). +// Set 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports' and 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports'. +// Update ImGuiPlatformIO's Monitors list every frame. +// Update MousePos every frame, in absolute coordinates. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// You may skip calling RenderPlatformWindowsDefault() if its API is not convenient for your needs. Read comments below. +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// About ImGui::RenderPlatformWindowsDefault(): +// - This function is a mostly a _helper_ for the common-most cases, and to facilitate using default backends. +// - You can check its simple source code to understand what it does. +// It basically iterates secondary viewports and call 4 functions that are setup in ImGuiPlatformIO, if available: +// Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers() +// Those functions pointers exists only for the benefit of RenderPlatformWindowsDefault(). +// - If you have very specific rendering needs (e.g. flipping multiple swap-chain simultaneously, unusual sync/threading issues, etc.), +// you may be tempted to ignore RenderPlatformWindowsDefault() and write customized code to perform your renderingg. +// You may decide to setup the platform_io's *RenderWindow and *SwapBuffers pointers and call your functions through those pointers, +// or you may decide to never setup those pointers and call your code directly. They are a convenience, not an obligatory interface. +//----------------------------------------------------------------------------- + +// Access via ImGui::GetPlatformIO() +struct ImGuiPlatformIO +{ + IMGUI_API ImGuiPlatformIO(); + + //------------------------------------------------------------------ + // Input - Interface with OS and Platform backend (most common stuff) + //------------------------------------------------------------------ + + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); // Should return NULL on failure (e.g. clipboard data is not text). + void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); + void* Platform_ClipboardUserData; + + // Optional: Open link/folder/file in OS Shell + // (default to use ShellExecuteW() on Windows, system() on Linux/Mac. expected to return false on failure, but some platforms may always return true) + bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); + void* Platform_OpenInShellUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + void* Platform_ImeUserData; + //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to platform_io.PlatformSetImeDataFn in 1.91.1] + + // Optional: Platform locale + // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point + ImWchar Platform_LocaleDecimalPoint; // '.' + + //------------------------------------------------------------------ + // Input - Interface with Renderer Backend + //------------------------------------------------------------------ + + // Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. + int Renderer_TextureMaxWidth; + int Renderer_TextureMaxHeight; + + // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. + void* Renderer_RenderState; + + //------------------------------------------------------------------ + // Input - Interface with Platform & Renderer backends for Multi-Viewport support + //------------------------------------------------------------------ + + // For reference, the second column shows which function are generally calling the Platform Functions: + // N = ImGui::NewFrame() ~ beginning of the dear imgui frame: read info from platform/OS windows (latest size/position) + // F = ImGui::Begin(), ImGui::EndFrame() ~ during the dear imgui frame + // U = ImGui::UpdatePlatformWindows() ~ after the dear imgui frame: create and update all platform/OS windows + // R = ImGui::RenderPlatformWindowsDefault() ~ render + // D = ImGui::DestroyPlatformWindows() ~ shutdown + // The general idea is that NewFrame() we will read the current Platform/OS state, and UpdatePlatformWindows() will write to it. + + // The handlers are designed so we can mix and match two imgui_impl_xxxx files, one Platform backend and one Renderer backend. + // Custom engine backends will often provide both Platform and Renderer interfaces together and so may not need to use all functions. + // Platform functions are typically called _before_ their Renderer counterpart, apart from Destroy which are called the other way. + + // Platform Backend functions (e.g. Win32, GLFW, SDL) ------------------- Called by ----- + void (*Platform_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create a new platform window for the given viewport + void (*Platform_DestroyWindow)(ImGuiViewport* vp); // N . U . D // + void (*Platform_ShowWindow)(ImGuiViewport* vp); // . . U . . // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them before showing the window + void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos); // . . U . . // Set platform window position (given the upper-left corner of client area) + ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . // + void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.) + ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size + ImVec2 (*Platform_GetWindowFramebufferScale)(ImGuiViewport* vp); // N . . . . // Return viewport density. Always 1,1 on Windows, often 2,2 on Retina display on macOS/iOS. MUST BE INTEGER VALUES. + void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus + bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . // + bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily + void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* str); // . . U . . // Set platform window title (given an UTF-8 string) + void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); // . . U . . // (Optional) Setup global transparency (not per-pixel transparency) + void (*Platform_UpdateWindow)(ImGuiViewport* vp); // . . U . . // (Optional) Called by UpdatePlatformWindows(). Optional hook to allow the platform backend from doing general book-keeping every frame. + void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Main rendering (platform side! This is often unused, or just setting a "current" context for OpenGL bindings). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers (platform side! This is often unused!). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI. + void (*Platform_OnChangedViewport)(ImGuiViewport* vp); // . F . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. + ImVec4 (*Platform_GetWindowWorkAreaInsets)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] Get initial work area inset for the viewport (won't be covered by main menu bar, dockspace over viewport etc.). Default to (0,0),(0,0). 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); // (Optional) For a Vulkan Renderer to call into Platform code (since the surface creation needs to tie them both). + + // Renderer Backend functions (e.g. DirectX, OpenGL, Vulkan) ------------ Called by ----- + void (*Renderer_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create swap chain, frame buffers etc. (called after Platform_CreateWindow) + void (*Renderer_DestroyWindow)(ImGuiViewport* vp); // N . U . D // Destroy swap chain, frame buffers etc. (called before Platform_DestroyWindow) + void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Resize swap chain, frame buffers etc. (called after Platform_SetWindowSize) + void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Clear framebuffer, setup render target, then render the viewport->DrawData. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + + // (Optional) Monitor list + // - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + // - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. + ImVector Monitors; + + //------------------------------------------------------------------ + // Output + //------------------------------------------------------------------ + + // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. + ImVector Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this. + + // Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + // (in the future we will attempt to organize this feature to remove the need for a "main viewport") + ImVector Viewports; // Main viewports, followed by all secondary viewports. + + //------------------------------------------------------------------ + // Functions + //------------------------------------------------------------------ + + IMGUI_API void ClearPlatformHandlers(); // Clear all Platform_XXX fields. Typically called on Platform Backend shutdown. + IMGUI_API void ClearRendererHandlers(); // Clear all Renderer_XXX fields. Typically called on Renderer Backend shutdown. +}; + +// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. +struct ImGuiPlatformMonitor +{ + ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) + ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. + float DpiScale; // 1.0f = 96 DPI + void* PlatformHandle; // Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) + ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; } +}; + +// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). +struct ImGuiPlatformImeData +{ + bool WantVisible; // A widget wants the IME to be visible. + bool WantTextInput; // A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + ImVec2 InputPos; // Position of input cursor (for IME). + float InputLineHeight; // Line height (for IME). + ImGuiID ViewportId; // ID of platform window/viewport. + + ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete functions and types +// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) +// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +namespace ImGui +{ + // OBSOLETED in 1.92.0 (from June 2025) + inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } + IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. + // OBSOLETED in 1.91.9 (from February 2025) + IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. + // OBSOLETED in 1.91.0 (from July 2024) + inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + inline void PopButtonRepeat() { PopItemFlag(); } + inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + inline void PopTabStop() { PopItemFlag(); } + IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! + IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! + IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! + // OBSOLETED in 1.90.0 (from September 2023) + IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); + + // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + // OBSOLETED in 1.90.0 (from September 2023) + //inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders + //inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders + //inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, flags); } + //inline void EndChildFrame() { EndChild(); } + //inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } + // OBSOLETED in 1.89.7 (from June 2023) + //IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() _before_ item. + //-- OBSOLETED in 1.89.4 (from March 2023) + //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + //static inline void PopAllowKeyboardFocus() { PopItemFlag(); } + //-- OBSOLETED in 1.89 (from August 2022) + //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. + //-- OBSOLETED in 1.88 (from May 2022) + //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. + //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. + //-- OBSOLETED in 1.87 (from February 2022, more formally obsoleted April 2024) + //IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); const ImGuiKeyData* key_data = GetKeyData(key); return (ImGuiKey)(key_data - g.IO.KeysData); } // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! + //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } + //-- OBSOLETED in 1.86 (from November 2021) + //IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper. + //-- OBSOLETED in 1.85 (from August 2021) + //static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } + //-- OBSOLETED in 1.81 (from February 2021) + //static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } + //static inline bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1) { float height = GetTextLineHeightWithSpacing() * ((height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f) + GetStyle().FramePadding.y * 2.0f; return BeginListBox(label, ImVec2(0.0f, height)); } // Helper to calculate size from items_count and height_in_items + //static inline void ListBoxFooter() { EndListBox(); } + //-- OBSOLETED in 1.79 (from August 2020) + //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! + //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. + //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //-- OBSOLETED in 1.77 and before + //static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.77 (from June 2020) + //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) + //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) + //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) + //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) + //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) + //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) + //-- OBSOLETED in 1.60 and before + //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) + //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) + //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //IMGUI_API bool Begin(char* name, bool* p_open, ImVec2 size_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags=0); // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017): Equivalent of using SetNextWindowSize(size, ImGuiCond_FirstUseEver) and SetNextWindowBgAlpha(). + //static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void SetNextWindowPosCenter(ImGuiCond c=0) { SetNextWindowPos(GetMainViewport()->GetCenter(), c, ImVec2(0.5f,0.5f)); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017): This was misleading and partly broken. You probably want to use the io.WantCaptureMouse flag instead. + //static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //-- OBSOLETED in 1.50 and before + //static inline bool CollapsingHeader(char* label, const char* str_id, bool framed = true, bool default_open = false) { return CollapsingHeader(label, (default_open ? (1 << 5) : 0)); } // OBSOLETED in 1.49 + //static inline ImFont*GetWindowFont() { return GetFont(); } // OBSOLETED in 1.48 + //static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETED in 1.48 + //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 +} + +//-- OBSOLETED in 1.92.0: ImFontAtlasCustomRect becomes ImTextureRect +// - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y +// - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h +// - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() +// We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. +typedef ImFontAtlasRect ImFontAtlasCustomRect; +/*struct ImFontAtlasCustomRect +{ + unsigned short X, Y; // Output // Packed position in Atlas + unsigned short Width, Height; // Input // [Internal] Desired rectangle dimension + unsigned int GlyphID:31; // Input // [Internal] For custom font glyphs only (ID < 0x110000) + unsigned int GlyphColored:1; // Input // [Internal] For custom font glyphs only: glyph is colored, removed tinting. + float GlyphAdvanceX; // Input // [Internal] For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // [Internal] For custom font glyphs only: glyph display offset + ImFont* Font; // Input // [Internal] For custom font glyphs only: target font + ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +};*/ + +//-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() +//typedef ImDrawFlags ImDrawCornerFlags; +//enum ImDrawCornerFlags_ +//{ +// ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit +// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). +// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. +// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. +// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. +// ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 +// ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, +// ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, +// ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, +// ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, +//}; + +// RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) +// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obsolescence schedule to reduce confusion and because they were not meant to be used in the first place. +//typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", so you may store mods in there. +//enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; +//typedef ImGuiKeyChord ImGuiKeyModFlags; // == int +//enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; + +//#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // OBSOLETED IN 1.90 (now using C++11 standard version) + +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +#define IM_ARRAYSIZE IM_COUNTOF // RENAMED IN 1.92.6: IM_ARRAYSIZE -> IM_COUNTOF + +// RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) +#ifdef IMGUI_DISABLE_METRICS_WINDOW +#error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// Include imgui_user.h at the end of imgui.h +// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#ifdef IMGUI_USER_H_FILENAME +#include IMGUI_USER_H_FILENAME +#else +#include "imgui_user.h" +#endif +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui_demo.cpp b/libs/imgui/imgui_demo.cpp new file mode 100644 index 0000000..8018d2c --- /dev/null +++ b/libs/imgui/imgui_demo.cpp @@ -0,0 +1,11282 @@ +// dear imgui, v1.92.6 WIP +// (demo code) + +// Help: +// - Read FAQ at http://dearimgui.com/faq +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// - Need help integrating Dear ImGui in your codebase? +// - Read Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started +// - Read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +// Read top of imgui.cpp and imgui.h for many details, documentation, comments, links. +// Get the latest version at https://github.com/ocornut/imgui + +// How to easily locate code? +// - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Browse an online version the demo with code linked to hovered widgets: https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html +// - Find a visible string and search for it in the code! + +//--------------------------------------------------- +// PLEASE DO NOT REMOVE THIS FILE FROM YOUR PROJECT! +//--------------------------------------------------- +// Message to the person tempted to delete this file when integrating Dear ImGui into their codebase: +// Think again! It is the most useful reference code that you and other coders will want to refer to and call. +// Have the ImGui::ShowDemoWindow() function wired in an always-available debug menu of your game/app! +// Also include Metrics! ItemPicker! DebugLog! and other debug features. +// Removing this file from your project is hindering access to documentation for everyone in your team, +// likely leading you to poorer usage of the library. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow(). +// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be +// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. +// In another situation, whenever you have Dear ImGui available you probably want this to be available for reference. +// Thank you, +// -Your beloved friend, imgui_demo.cpp (which you won't delete) + +//-------------------------------------------- +// ABOUT THE MEANING OF THE 'static' KEYWORD: +//-------------------------------------------- +// In this demo code, we frequently use 'static' variables inside functions. +// A static variable persists across calls. It is essentially a global variable but declared inside the scope of the function. +// Think of "static int n = 0;" as "global int n = 0;" ! +// We do this IN THE DEMO because we want: +// - to gather code and data in the same place. +// - to make the demo source code faster to read, faster to change, smaller in size. +// - it is also a convenient way of storing simple UI related information as long as your function +// doesn't need to be reentrant or used in multiple threads. +// This might be a pattern you will want to use in your code, but most of the data you would be working +// with in a complex codebase is likely going to be stored outside your functions. + +//----------------------------------------- +// ABOUT THE CODING STYLE OF OUR DEMO CODE +//----------------------------------------- +// The Demo code in this file is designed to be easy to copy-and-paste into your application! +// Because of this: +// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace. +// - We try to declare static variables in the local scope, as close as possible to the code using them. +// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API. +// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided +// by imgui.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional +// and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h. +// Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp. + +// Navigating this file: +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. +// - You can search/grep for all sections listed in the index to find the section. + +/* + +Index of this file: + +// [SECTION] Forward Declarations +// [SECTION] Helpers +// [SECTION] Demo Window / ShowDemoWindow() +// [SECTION] DemoWindowMenuBar() +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +// [SECTION] DemoWindowWidgetsBasic() +// [SECTION] DemoWindowWidgetsBullets() +// [SECTION] DemoWindowWidgetsCollapsingHeaders() +// [SECTION] DemoWindowWidgetsComboBoxes() +// [SECTION] DemoWindowWidgetsColorAndPickers() +// [SECTION] DemoWindowWidgetsDataTypes() +// [SECTION] DemoWindowWidgetsDisableBlocks() +// [SECTION] DemoWindowWidgetsDragAndDrop() +// [SECTION] DemoWindowWidgetsDragsAndSliders() +// [SECTION] DemoWindowWidgetsFonts() +// [SECTION] DemoWindowWidgetsImages() +// [SECTION] DemoWindowWidgetsListBoxes() +// [SECTION] DemoWindowWidgetsMultiComponents() +// [SECTION] DemoWindowWidgetsPlotting() +// [SECTION] DemoWindowWidgetsProgressBars() +// [SECTION] DemoWindowWidgetsQueryingStatuses() +// [SECTION] DemoWindowWidgetsSelectables() +// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() +// [SECTION] DemoWindowWidgetsTabs() +// [SECTION] DemoWindowWidgetsText() +// [SECTION] DemoWindowWidgetsTextFilter() +// [SECTION] DemoWindowWidgetsTextInput() +// [SECTION] DemoWindowWidgetsTooltips() +// [SECTION] DemoWindowWidgetsTreeNodes() +// [SECTION] DemoWindowWidgetsVerticalSliders() +// [SECTION] DemoWindowWidgets() +// [SECTION] DemoWindowLayout() +// [SECTION] DemoWindowPopups() +// [SECTION] DemoWindowTables() +// [SECTION] DemoWindowInputs() +// [SECTION] About Window / ShowAboutWindow() +// [SECTION] Style Editor / ShowStyleEditor() +// [SECTION] User Guide / ShowUserGuide() +// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +// [SECTION] Example App: Debug Console / ShowExampleAppConsole() +// [SECTION] Example App: Debug Log / ShowExampleAppLog() +// [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +// [SECTION] Example App: Long Text / ShowExampleAppLongText() +// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +// [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() +// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() +// [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser() + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +// System includes +#include // toupper +#include // INT_MIN, INT_MAX +#include // sqrtf, powf, cosf, sinf, floorf, ceilf +#include // vsnprintf, sscanf, printf +#include // NULL, malloc, free, atoi +#include // intptr_t +#if !defined(_MSC_VER) || _MSC_VER >= 1800 +#include // PRId64/PRIu64, not avail in some MinGW headers. +#endif +#ifdef __EMSCRIPTEN__ +#include // __EMSCRIPTEN_major__ etc. +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type +#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' +#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#endif + +// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!) +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +// Helpers +#if defined(_MSC_VER) && !defined(snprintf) +#define snprintf _snprintf +#endif +#if defined(_MSC_VER) && !defined(vsnprintf) +#define vsnprintf _vsnprintf +#endif + +// Format specifiers for 64-bit values (hasn't been decently standardized before VS2013) +#if !defined(PRId64) && defined(_MSC_VER) +#define PRId64 "I64d" +#define PRIu64 "I64u" +#elif !defined(PRId64) +#define PRId64 "lld" +#define PRIu64 "llu" +#endif + +// Helpers macros +// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +// but making an exception here as those are largely simplifying code... +// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. +#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V)) + +// Enforce cdecl calling convention for functions called by the standard library, +// in case compilation settings changed the default to e.g. __vectorcall +#ifndef IMGUI_CDECL +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//----------------------------------------------------------------------------- + +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) + +// Forward Declarations +struct ImGuiDemoWindowData; +static void ShowExampleAppMainMenuBar(); +static void ShowExampleAppAssetsBrowser(bool* p_open); +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleAppDockSpace(bool* p_open); +static void ShowExampleAppDocuments(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data); +static void ShowExampleAppSimpleOverlay(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppFullscreen(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppWindowTitles(bool* p_open); +static void ShowExampleMenuFile(); + +// We split the contents of the big ShowDemoWindow() function into smaller functions +// (because the link time of very large functions tends to grow non-linearly) +static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); +static void DemoWindowLayout(); +static void DemoWindowPopups(); +static void DemoWindowTables(); +static void DemoWindowColumns(); +static void DemoWindowInputs(); + +// Helper tree functions used by Property Editor & Multi-Select demos +struct ExampleTreeNode; +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent); +static void ExampleTree_DestroyNode(ExampleTreeNode* node); + +//----------------------------------------------------------------------------- +// [SECTION] Helpers +//----------------------------------------------------------------------------- + +// Helper to display a little (?) mark which shows a tooltip when hovered. +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) +static void HelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::BeginItemTooltip()) + { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +static void ShowDockingDisabledMessage() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration."); + ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or "); + ImGui::SameLine(0.0f, 0.0f); + if (ImGui::SmallButton("click here")) + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; +} + +// Helper to wire demo markers located in code to an interactive browser +typedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data); +extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback; +extern void* GImGuiDemoMarkerCallbackUserData; +ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL; +void* GImGuiDemoMarkerCallbackUserData = NULL; +#define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback("imgui_demo.cpp", __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) + +//----------------------------------------------------------------------------- +// [SECTION] Demo Window / ShowDemoWindow() +//----------------------------------------------------------------------------- + +// Data to be shared across different functions of the demo. +struct ImGuiDemoWindowData +{ + // Examples Apps (accessible from the "Examples" menu) + bool ShowMainMenuBar = false; + bool ShowAppAssetsBrowser = false; + bool ShowAppConsole = false; + bool ShowAppCustomRendering = false; + bool ShowAppDocuments = false; + bool ShowAppDockSpace = false; + bool ShowAppLog = false; + bool ShowAppLayout = false; + bool ShowAppPropertyEditor = false; + bool ShowAppSimpleOverlay = false; + bool ShowAppAutoResize = false; + bool ShowAppConstrainedResize = false; + bool ShowAppFullscreen = false; + bool ShowAppLongText = false; + bool ShowAppWindowTitles = false; + + // Dear ImGui Tools (accessible from the "Tools" menu) + bool ShowMetrics = false; + bool ShowDebugLog = false; + bool ShowIDStackTool = false; + bool ShowStyleEditor = false; + bool ShowAbout = false; + + // Other data + bool DisableSections = false; + ExampleTreeNode* DemoTree = NULL; + + ~ImGuiDemoWindowData() { if (DemoTree) ExampleTree_DestroyNode(DemoTree); } +}; + +// Demonstrate most Dear ImGui features (this is big function!) +// You may execute this function to experiment with the UI and understand what it does. +// You may then search for keywords in the code when you are interested by a specific feature. +void ImGui::ShowDemoWindow(bool* p_open) +{ + // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + // Most functions would normally just assert/crash if the context is missing. + IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing Dear ImGui context. Refer to examples app!"); + + // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues. + IMGUI_CHECKVERSION(); + + // Stored data + static ImGuiDemoWindowData demo_data; + + // Examples Apps (accessible from the "Examples" menu) + if (demo_data.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); } + if (demo_data.ShowAppDockSpace) { ShowExampleAppDockSpace(&demo_data.ShowAppDockSpace); } // Important: Process the Docking app first, as explicit DockSpace() nodes needs to be submitted early (read comments near the DockSpace function) + if (demo_data.ShowAppDocuments) { ShowExampleAppDocuments(&demo_data.ShowAppDocuments); } // ...process the Document app next, as it may also use a DockSpace() + if (demo_data.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo_data.ShowAppAssetsBrowser); } + if (demo_data.ShowAppConsole) { ShowExampleAppConsole(&demo_data.ShowAppConsole); } + if (demo_data.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo_data.ShowAppCustomRendering); } + if (demo_data.ShowAppLog) { ShowExampleAppLog(&demo_data.ShowAppLog); } + if (demo_data.ShowAppLayout) { ShowExampleAppLayout(&demo_data.ShowAppLayout); } + if (demo_data.ShowAppPropertyEditor) { ShowExampleAppPropertyEditor(&demo_data.ShowAppPropertyEditor, &demo_data); } + if (demo_data.ShowAppSimpleOverlay) { ShowExampleAppSimpleOverlay(&demo_data.ShowAppSimpleOverlay); } + if (demo_data.ShowAppAutoResize) { ShowExampleAppAutoResize(&demo_data.ShowAppAutoResize); } + if (demo_data.ShowAppConstrainedResize) { ShowExampleAppConstrainedResize(&demo_data.ShowAppConstrainedResize); } + if (demo_data.ShowAppFullscreen) { ShowExampleAppFullscreen(&demo_data.ShowAppFullscreen); } + if (demo_data.ShowAppLongText) { ShowExampleAppLongText(&demo_data.ShowAppLongText); } + if (demo_data.ShowAppWindowTitles) { ShowExampleAppWindowTitles(&demo_data.ShowAppWindowTitles); } + + // Dear ImGui Tools (accessible from the "Tools" menu) + if (demo_data.ShowMetrics) { ImGui::ShowMetricsWindow(&demo_data.ShowMetrics); } + if (demo_data.ShowDebugLog) { ImGui::ShowDebugLogWindow(&demo_data.ShowDebugLog); } + if (demo_data.ShowIDStackTool) { ImGui::ShowIDStackToolWindow(&demo_data.ShowIDStackTool); } + if (demo_data.ShowAbout) { ImGui::ShowAboutWindow(&demo_data.ShowAbout); } + if (demo_data.ShowStyleEditor) + { + ImGui::Begin("Dear ImGui Style Editor", &demo_data.ShowStyleEditor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } + + // Demonstrate the various window flags. Typically you would just use the default! + static bool no_titlebar = false; + static bool no_scrollbar = false; + static bool no_menu = false; + static bool no_move = false; + static bool no_resize = false; + static bool no_collapse = false; + static bool no_close = false; + static bool no_nav = false; + static bool no_background = false; + static bool no_bring_to_front = false; + static bool no_docking = false; + static bool unsaved_document = false; + + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (no_nav) window_flags |= ImGuiWindowFlags_NoNav; + if (no_background) window_flags |= ImGuiWindowFlags_NoBackground; + if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; + if (no_docking) window_flags |= ImGuiWindowFlags_NoDocking; + if (unsaved_document) window_flags |= ImGuiWindowFlags_UnsavedDocument; + if (no_close) p_open = NULL; // Don't pass our bool* to Begin + + // We specify a default position/size in case there's no data in the .ini file. + // We only do it to make the demo applications a little more welcoming, but typically this isn't required. + const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); + + // Main body of the Demo window starts here. + if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + // Most framed widgets share a common width settings. Remaining width is used for the label. + // The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + // - Positive value for absolute size, negative value for right-alignment. + // - The default value is about GetWindowWidth() * 0.65f. + // - See 'Demo->Layout->Widgets Width' for details. + // Here we change the frame width based on how much width we want to give to the label. + const float label_width_base = ImGui::GetFontSize() * 12; // Some amount of width for label, based on font size. + const float label_width_max = ImGui::GetContentRegionAvail().x * 0.40f; // ...but always leave some room for framed widgets. + const float label_width = IM_MIN(label_width_base, label_width_max); + ImGui::PushItemWidth(-label_width); // Right-align: framed items will leave 'label_width' available for the label. + //ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for framed widgets, leaving 60% width for labels. + //ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for labels, leaving 60% width for framed widgets. + //ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Use XXX width for labels, leaving the rest for framed widgets. + + // Menu Bar + DemoWindowMenuBar(&demo_data); + + ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + ImGui::Spacing(); + + IMGUI_DEMO_MARKER("Help"); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::SeparatorText("ABOUT THIS DEMO:"); + ImGui::BulletText("Sections below are demonstrating many aspects of the library."); + ImGui::BulletText("The \"Examples\" menu above leads to more demo contents."); + ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n" + "and Metrics/Debugger (general purpose Dear ImGui debugging tool)."); + + ImGui::SeparatorText("PROGRAMMER GUIDE:"); + ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!"); + ImGui::BulletText("See comments in imgui.cpp."); + ImGui::BulletText("See example applications in the examples/ folder."); + ImGui::BulletText("Read the FAQ at "); + ImGui::SameLine(0, 0); + ImGui::TextLinkOpenURL("https://www.dearimgui.com/faq/"); + ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls."); + ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls."); + + ImGui::SeparatorText("USER GUIDE:"); + ImGui::ShowUserGuide(); + } + + IMGUI_DEMO_MARKER("Configuration"); + if (ImGui::CollapsingHeader("Configuration")) + { + ImGuiIO& io = ImGui::GetIO(); + + if (ImGui::TreeNode("Configuration##2")) + { + ImGui::SeparatorText("General"); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::SameLine(); HelpMarker("Enable keyboard controls."); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse); + ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable mouse inputs and interactions."); + + // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it: + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) + { + if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) + { + ImGui::SameLine(); + ImGui::Text("<>"); + } + // Prevent both being checked + if (ImGui::IsKeyPressed(ImGuiKey_Space) || (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)) + io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; + } + + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility."); + ImGui::CheckboxFlags("io.ConfigFlags: NoKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NoKeyboard); + ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable keyboard inputs and interactions."); + + ImGui::Checkbox("io.ConfigInputTrickleEventQueue", &io.ConfigInputTrickleEventQueue); + ImGui::SameLine(); HelpMarker("Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates."); + ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); + ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + + ImGui::SeparatorText("Keyboard/Gamepad Navigation"); + ImGui::Checkbox("io.ConfigNavSwapGamepadButtons", &io.ConfigNavSwapGamepadButtons); + ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos); + ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult"); + ImGui::Checkbox("io.ConfigNavCaptureKeyboard", &io.ConfigNavCaptureKeyboard); + ImGui::Checkbox("io.ConfigNavEscapeClearFocusItem", &io.ConfigNavEscapeClearFocusItem); + ImGui::SameLine(); HelpMarker("Pressing Escape clears focused item."); + ImGui::Checkbox("io.ConfigNavEscapeClearFocusWindow", &io.ConfigNavEscapeClearFocusWindow); + ImGui::SameLine(); HelpMarker("Pressing Escape clears focused window."); + ImGui::Checkbox("io.ConfigNavCursorVisibleAuto", &io.ConfigNavCursorVisibleAuto); + ImGui::SameLine(); HelpMarker("Using directional navigation key makes the cursor visible. Mouse click hides the cursor."); + ImGui::Checkbox("io.ConfigNavCursorVisibleAlways", &io.ConfigNavCursorVisibleAlways); + ImGui::SameLine(); HelpMarker("Navigation cursor is always visible."); + + ImGui::SeparatorText("Docking"); + ImGui::CheckboxFlags("io.ConfigFlags: DockingEnable", &io.ConfigFlags, ImGuiConfigFlags_DockingEnable); + ImGui::SameLine(); + if (io.ConfigDockingWithShift) + HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to enable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); + else + HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); + if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + ImGui::Indent(); + ImGui::Checkbox("io.ConfigDockingNoSplit", &io.ConfigDockingNoSplit); + ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars."); + ImGui::Checkbox("io.ConfigDockingNoDockingOver", &io.ConfigDockingNoDockingOver); + ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window merging into a same tab-bar, so docking is limited to splitting windows."); + ImGui::Checkbox("io.ConfigDockingWithShift", &io.ConfigDockingWithShift); + ImGui::SameLine(); HelpMarker("Enable docking when holding Shift only (allow to drop in wider space, reduce visual noise)"); + ImGui::Checkbox("io.ConfigDockingAlwaysTabBar", &io.ConfigDockingAlwaysTabBar); + ImGui::SameLine(); HelpMarker("Create a docking node and tab-bar on single floating windows."); + ImGui::Checkbox("io.ConfigDockingTransparentPayload", &io.ConfigDockingTransparentPayload); + ImGui::SameLine(); HelpMarker("Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge."); + ImGui::Unindent(); + } + + ImGui::SeparatorText("Multi-viewports"); + ImGui::CheckboxFlags("io.ConfigFlags: ViewportsEnable", &io.ConfigFlags, ImGuiConfigFlags_ViewportsEnable); + ImGui::SameLine(); HelpMarker("[beta] Enable beta multi-viewports support. See ImGuiPlatformIO for details."); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + ImGui::Indent(); + ImGui::Checkbox("io.ConfigViewportsNoAutoMerge", &io.ConfigViewportsNoAutoMerge); + ImGui::SameLine(); HelpMarker("Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it."); + ImGui::Checkbox("io.ConfigViewportsNoTaskBarIcon", &io.ConfigViewportsNoTaskBarIcon); + ImGui::SameLine(); HelpMarker("(note: some platform backends may not reflect a change of this value for existing viewports, and may need the viewport to be recreated)"); + ImGui::Checkbox("io.ConfigViewportsNoDecoration", &io.ConfigViewportsNoDecoration); + ImGui::SameLine(); HelpMarker("(note: some platform backends may not reflect a change of this value for existing viewports, and may need the viewport to be recreated)"); + ImGui::Checkbox("io.ConfigViewportsNoDefaultParent", &io.ConfigViewportsNoDefaultParent); + ImGui::SameLine(); HelpMarker("(note: some platform backends may not reflect a change of this value for existing viewports, and may need the viewport to be recreated)"); + ImGui::Checkbox("io.ConfigViewportsPlatformFocusSetsImGuiFocus", &io.ConfigViewportsPlatformFocusSetsImGuiFocus); + ImGui::SameLine(); HelpMarker("When a platform window is focused (e.g. using Alt+Tab, clicking Platform Title Bar), apply corresponding focus on imgui windows (may clear focus/active id from imgui windows location in other platform windows). In principle this is better enabled but we provide an opt-out, because some Linux window managers tend to eagerly focus windows (e.g. on mouse hover, or even a simple window pos/size change)."); + ImGui::Unindent(); + } + + //ImGui::SeparatorText("DPI/Scaling"); + //ImGui::Checkbox("io.ConfigDpiScaleFonts", &io.ConfigDpiScaleFonts); + //ImGui::SameLine(); HelpMarker("Experimental: Automatically update style.FontScaleDpi when Monitor DPI changes. This will scale fonts but NOT style sizes/padding for now."); + //ImGui::Checkbox("io.ConfigDpiScaleViewports", &io.ConfigDpiScaleViewports); + //ImGui::SameLine(); HelpMarker("Experimental: Scale Dear ImGui and Platform Windows when Monitor DPI changes."); + + ImGui::SeparatorText("Windows"); + ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges); + ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback."); + ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); + ImGui::Checkbox("io.ConfigWindowsCopyContentsWithCtrlC", &io.ConfigWindowsCopyContentsWithCtrlC); // [EXPERIMENTAL] + ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* Ctrl+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order."); + ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage); + ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location."); + + ImGui::SeparatorText("Widgets"); + ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); + ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting)."); + ImGui::Checkbox("io.ConfigInputTextEnterKeepActive", &io.ConfigInputTextEnterKeepActive); + ImGui::SameLine(); HelpMarker("Pressing Enter will keep item active and select contents (single-line only)."); + ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText); + ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving)."); + ImGui::Checkbox("io.ConfigMacOSXBehaviors", &io.ConfigMacOSXBehaviors); + ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors."); + ImGui::Text("Also see Style->Rendering for rendering options."); + + // Also read: https://github.com/ocornut/imgui/wiki/Error-Handling + ImGui::SeparatorText("Error Handling"); + + ImGui::Checkbox("io.ConfigErrorRecovery", &io.ConfigErrorRecovery); + ImGui::SameLine(); HelpMarker( + "Options to configure how we handle recoverable errors.\n" + "- Error recovery is not perfect nor guaranteed! It is a feature to ease development.\n" + "- You not are not supposed to rely on it in the course of a normal application run.\n" + "- Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.\n" + "- Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call! " + "Otherwise it would severely hinder your ability to catch and correct mistakes!"); + ImGui::Checkbox("io.ConfigErrorRecoveryEnableAssert", &io.ConfigErrorRecoveryEnableAssert); + ImGui::Checkbox("io.ConfigErrorRecoveryEnableDebugLog", &io.ConfigErrorRecoveryEnableDebugLog); + ImGui::Checkbox("io.ConfigErrorRecoveryEnableTooltip", &io.ConfigErrorRecoveryEnableTooltip); + if (!io.ConfigErrorRecoveryEnableAssert && !io.ConfigErrorRecoveryEnableDebugLog && !io.ConfigErrorRecoveryEnableTooltip) + io.ConfigErrorRecoveryEnableAssert = io.ConfigErrorRecoveryEnableDebugLog = io.ConfigErrorRecoveryEnableTooltip = true; + + // Also read: https://github.com/ocornut/imgui/wiki/Debug-Tools + ImGui::SeparatorText("Debug"); + ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent); + ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application."); + ImGui::Checkbox("io.ConfigDebugHighlightIdConflicts", &io.ConfigDebugHighlightIdConflicts); + ImGui::SameLine(); HelpMarker("Highlight and show an error message when multiple items have conflicting identifiers."); + ImGui::BeginDisabled(); + ImGui::Checkbox("io.ConfigDebugBeginReturnValueOnce", &io.ConfigDebugBeginReturnValueOnce); + ImGui::EndDisabled(); + ImGui::SameLine(); HelpMarker("First calls to Begin()/BeginChild() will return false.\n\nTHIS OPTION IS DISABLED because it needs to be set at application boot-time to make sense. Showing the disabled option is a way to make this feature easier to discover."); + ImGui::Checkbox("io.ConfigDebugBeginReturnValueLoop", &io.ConfigDebugBeginReturnValueLoop); + ImGui::SameLine(); HelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running."); + ImGui::Checkbox("io.ConfigDebugIgnoreFocusLoss", &io.ConfigDebugIgnoreFocusLoss); + ImGui::SameLine(); HelpMarker("Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data."); + ImGui::Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings); + ImGui::SameLine(); HelpMarker("Option to save .ini data with extra comments (particularly helpful for Docking, but makes saving slower)."); + + ImGui::TreePop(); + ImGui::Spacing(); + } + + IMGUI_DEMO_MARKER("Configuration/Backend Flags"); + if (ImGui::TreeNode("Backend Flags")) + { + HelpMarker( + "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose them as read-only fields to avoid breaking interactions with your backend."); + + // Make a local copy to avoid modifying actual backend flags. + // FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright? + ImGui::BeginDisabled(); + ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &io.BackendFlags, ImGuiBackendFlags_HasGamepad); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors); + ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos); + ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", &io.BackendFlags, ImGuiBackendFlags_PlatformHasViewports); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport",&io.BackendFlags, ImGuiBackendFlags_HasMouseHoveredViewport); + ImGui::CheckboxFlags("io.BackendFlags: HasParentViewport", &io.BackendFlags, ImGuiBackendFlags_HasParentViewport); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", &io.BackendFlags, ImGuiBackendFlags_RendererHasViewports); + ImGui::EndDisabled(); + + ImGui::TreePop(); + ImGui::Spacing(); + } + + IMGUI_DEMO_MARKER("Configuration/Style, Fonts"); + if (ImGui::TreeNode("Style, Fonts")) + { + ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor); + ImGui::SameLine(); + HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); + ImGui::TreePop(); + ImGui::Spacing(); + } + + IMGUI_DEMO_MARKER("Configuration/Capture, Logging"); + if (ImGui::TreeNode("Capture/Logging")) + { + HelpMarker( + "The logging API redirects all text output so you can easily capture the content of " + "a window or a block. Tree nodes can be automatically expanded.\n" + "Try opening any of the contents below in this window and then click one of the \"Log To\" button."); + ImGui::LogButtons(); + + HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output."); + if (ImGui::Button("Copy \"Hello, world!\" to clipboard")) + { + ImGui::LogToClipboard(); + ImGui::LogText("Hello, world!"); + ImGui::LogFinish(); + } + ImGui::TreePop(); + } + } + + IMGUI_DEMO_MARKER("Window options"); + if (ImGui::CollapsingHeader("Window options")) + { + if (ImGui::BeginTable("split", 3)) + { + ImGui::TableNextColumn(); ImGui::Checkbox("No titlebar", &no_titlebar); + ImGui::TableNextColumn(); ImGui::Checkbox("No scrollbar", &no_scrollbar); + ImGui::TableNextColumn(); ImGui::Checkbox("No menu", &no_menu); + ImGui::TableNextColumn(); ImGui::Checkbox("No move", &no_move); + ImGui::TableNextColumn(); ImGui::Checkbox("No resize", &no_resize); + ImGui::TableNextColumn(); ImGui::Checkbox("No collapse", &no_collapse); + ImGui::TableNextColumn(); ImGui::Checkbox("No close", &no_close); + ImGui::TableNextColumn(); ImGui::Checkbox("No nav", &no_nav); + ImGui::TableNextColumn(); ImGui::Checkbox("No background", &no_background); + ImGui::TableNextColumn(); ImGui::Checkbox("No bring to front", &no_bring_to_front); + ImGui::TableNextColumn(); ImGui::Checkbox("No docking", &no_docking); + ImGui::TableNextColumn(); ImGui::Checkbox("Unsaved document", &unsaved_document); + ImGui::EndTable(); + } + } + + // All demo contents + DemoWindowWidgets(&demo_data); + DemoWindowLayout(); + DemoWindowPopups(); + DemoWindowTables(); + DemoWindowInputs(); + + // End of ShowDemoWindow() + ImGui::PopItemWidth(); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowMenuBar() +//----------------------------------------------------------------------------- + +static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Menu"); + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + IMGUI_DEMO_MARKER("Menu/File"); + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + IMGUI_DEMO_MARKER("Menu/Examples"); + ImGui::MenuItem("Main menu bar", NULL, &demo_data->ShowMainMenuBar); + + ImGui::SeparatorText("Mini apps"); + ImGui::MenuItem("Assets Browser", NULL, &demo_data->ShowAppAssetsBrowser); + ImGui::MenuItem("Console", NULL, &demo_data->ShowAppConsole); + ImGui::MenuItem("Custom rendering", NULL, &demo_data->ShowAppCustomRendering); + ImGui::MenuItem("Documents", NULL, &demo_data->ShowAppDocuments); + ImGui::MenuItem("Dockspace", NULL, &demo_data->ShowAppDockSpace); + ImGui::MenuItem("Log", NULL, &demo_data->ShowAppLog); + ImGui::MenuItem("Property editor", NULL, &demo_data->ShowAppPropertyEditor); + ImGui::MenuItem("Simple layout", NULL, &demo_data->ShowAppLayout); + ImGui::MenuItem("Simple overlay", NULL, &demo_data->ShowAppSimpleOverlay); + + ImGui::SeparatorText("Concepts"); + ImGui::MenuItem("Auto-resizing window", NULL, &demo_data->ShowAppAutoResize); + ImGui::MenuItem("Constrained-resizing window", NULL, &demo_data->ShowAppConstrainedResize); + ImGui::MenuItem("Fullscreen window", NULL, &demo_data->ShowAppFullscreen); + ImGui::MenuItem("Long text display", NULL, &demo_data->ShowAppLongText); + ImGui::MenuItem("Manipulating window titles", NULL, &demo_data->ShowAppWindowTitles); + + ImGui::EndMenu(); + } + //if (ImGui::MenuItem("MenuItem")) {} // You can also use MenuItem() inside a menu bar! + if (ImGui::BeginMenu("Tools")) + { + IMGUI_DEMO_MARKER("Menu/Tools"); + ImGuiIO& io = ImGui::GetIO(); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + const bool has_debug_tools = true; +#else + const bool has_debug_tools = false; +#endif + ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools); + if (ImGui::BeginMenu("Debug Options")) + { + ImGui::BeginDisabled(!has_debug_tools); + ImGui::Checkbox("Highlight ID Conflicts", &io.ConfigDebugHighlightIdConflicts); + ImGui::EndDisabled(); + ImGui::Checkbox("Assert on error recovery", &io.ConfigErrorRecoveryEnableAssert); + ImGui::TextDisabled("(see Demo->Configuration for details & more)"); + ImGui::EndMenu(); + } + ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools); + ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools); + bool is_debugger_present = io.ConfigDebugIsDebuggerPresent; + if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools))// && is_debugger_present)) + ImGui::DebugStartItemPicker(); + if (!is_debugger_present) + ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable some extra features to avoid casual users crashing the application."); + ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor); + ImGui::MenuItem("About Dear ImGui", NULL, &demo_data->ShowAbout); + + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +//----------------------------------------------------------------------------- + +// Simple representation for a tree +// (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) +struct ExampleTreeNode +{ + // Tree structure + char Name[28] = ""; + int UID = 0; + ExampleTreeNode* Parent = NULL; + ImVector Childs; + unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily + + // Leaf Data + bool HasData = false; // All leaves have data + bool DataMyBool = true; + int DataMyInt = 128; + ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); +}; + +// Simple representation of struct metadata/serialization data. +// (this is a minimal version of what a typical advanced application may provide) +struct ExampleMemberInfo +{ + const char* Name; // Member name + ImGuiDataType DataType; // Member type + int DataCount; // Member count (1 when scalar) + int Offset; // Offset inside parent structure +}; + +// Metadata description of ExampleTreeNode struct. +static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] +{ + { "MyName", ImGuiDataType_String, 1, offsetof(ExampleTreeNode, Name) }, + { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) }, + { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) }, + { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) }, +}; + +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent) +{ + ExampleTreeNode* node = IM_NEW(ExampleTreeNode); + snprintf(node->Name, IM_COUNTOF(node->Name), "%s", name); + node->UID = uid; + node->Parent = parent; + node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0; + if (parent) + parent->Childs.push_back(node); + return node; +} + +static void ExampleTree_DestroyNode(ExampleTreeNode* node) +{ + for (ExampleTreeNode* child_node : node->Childs) + ExampleTree_DestroyNode(child_node); + IM_DELETE(node); +} + +// Create example tree data +// (this allocates _many_ more times than most other code in either Dear ImGui or others demo) +static ExampleTreeNode* ExampleTree_CreateDemoTree() +{ + static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; + const size_t NAME_MAX_LEN = sizeof(ExampleTreeNode::Name); + char name_buf[NAME_MAX_LEN]; + int uid = 0; + ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); + const int root_items_multiplier = 2; + for (int idx_L0 = 0; idx_L0 < IM_COUNTOF(root_names) * root_items_multiplier; idx_L0++) + { + snprintf(name_buf, IM_COUNTOF(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); + ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); + const int number_of_childs = (int)strlen(node_L1->Name); + for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) + { + snprintf(name_buf, IM_COUNTOF(name_buf), "Child %d", idx_L1); + ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); + node_L2->HasData = true; + if (idx_L1 == 0) + { + snprintf(name_buf, IM_COUNTOF(name_buf), "Sub-child %d", 0); + ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); + node_L3->HasData = true; + } + } + } + return node_L0; +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsBasic() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsBasic() +{ + IMGUI_DEMO_MARKER("Widgets/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGui::SeparatorText("General"); + + IMGUI_DEMO_MARKER("Widgets/Basic/Button"); + static int clicked = 0; + if (ImGui::Button("Button")) + clicked++; + if (clicked & 1) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + IMGUI_DEMO_MARKER("Widgets/Basic/Checkbox"); + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + IMGUI_DEMO_MARKER("Widgets/Basic/RadioButton"); + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + ImGui::AlignTextToFramePadding(); + ImGui::TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling"); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); + for (int i = 0; i < 7; i++) + { + if (i > 0) + ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + // See 'Demo->Layout->Text Baseline Alignment' for details. + ImGui::AlignTextToFramePadding(); + ImGui::Text("Hold to repeat:"); + ImGui::SameLine(); + + // Arrow buttons with Repeater + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)"); + static int counter = 0; + float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); + if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; } + ImGui::SameLine(0.0f, spacing); + if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; } + ImGui::PopItemFlag(); + ImGui::SameLine(); + ImGui::Text("%d", counter); + + ImGui::Button("Tooltip"); + ImGui::SetItemTooltip("I am a tooltip"); + + ImGui::LabelText("label", "Value"); + + ImGui::SeparatorText("Inputs"); + + { + // If you want to use InputText() with std::string or any custom dynamic string type: + // - For std::string: use the wrapper in misc/cpp/imgui_stdlib.h/.cpp + // - Otherwise, see the 'Dear ImGui Demo->Widgets->Text Input->Resize Callback' for using ImGuiInputTextFlags_CallbackResize. + IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); + static char str0[128] = "Hello, world!"; + ImGui::InputText("input text", str0, IM_COUNTOF(str0)); + ImGui::SameLine(); HelpMarker( + "USER:\n" + "Hold Shift or use mouse to select text.\n" + "Ctrl+Left/Right to word jump.\n" + "Ctrl+A or Double-Click to select all.\n" + "Ctrl+X,Ctrl+C,Ctrl+V for clipboard.\n" + "Ctrl+Z to undo, Ctrl+Y/Ctrl+Shift+Z to redo.\n" + "Escape to revert.\n\n" + "PROGRAMMER:\n" + "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " + "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " + "in imgui_demo.cpp)."); + + static char str1[128] = ""; + ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_COUNTOF(str1)); + + IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat"); + static int i0 = 123; + ImGui::InputInt("input int", &i0); + + static float f0 = 0.001f; + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); + + static double d0 = 999999.00000001; + ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f"); + + static float f1 = 1.e10f; + ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); + ImGui::SameLine(); HelpMarker( + "You can input value using the scientific notation,\n" + " e.g. \"1e+8\" becomes \"100000000\"."); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + ImGui::SeparatorText("Drags"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat"); + static int i1 = 50, i2 = 42, i3 = 128; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); HelpMarker( + "Click and drag to edit value.\n" + "Hold Shift/Alt for faster/slower edit.\n" + "Double-Click or Ctrl+Click to input value."); + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround); + + static float f1 = 1.00f, f2 = 0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuiSliderFlags_WrapAround); + } + + ImGui::SeparatorText("Sliders"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat"); + static int i1 = 0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); HelpMarker("Ctrl+Click to input value."); + + static float f1 = 0.123f, f2 = 0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Basic/SliderAngle"); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + + // Using the format string to display a name instead of an integer. + // Here we completely omit '%d' from the format string, so it'll only display a name. + // This technique can also be used with DragInt(). + IMGUI_DEMO_MARKER("Widgets/Basic/Slider (enum)"); + enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; + static int elem = Element_Fire; + const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable Ctrl+Click here. + ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); + } + + ImGui::SeparatorText("Selectors/Pickers"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/ColorEdit3, ColorEdit4"); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-Click on the color square to show options.\n" + "Ctrl+Click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + } + + { + // Using the _simplified_ one-liner Combo() api here + // See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. + IMGUI_DEMO_MARKER("Widgets/Basic/Combo"); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; + static int item_current = 0; + ImGui::Combo("combo", &item_current, items, IM_COUNTOF(items)); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner Combo API here.\n" + "Refer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API."); + } + + { + // Using the _simplified_ one-liner ListBox() api here + // See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. + IMGUI_DEMO_MARKER("Widgets/Basic/ListBox"); + const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int item_current = 1; + ImGui::ListBox("listbox", &item_current, items, IM_COUNTOF(items), 4); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner ListBox API here.\n" + "Refer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API."); + } + + // Testing ImGuiOnceUponAFrame helper. + //static ImGuiOnceUponAFrame once; + //for (int i = 0; i < 5; i++) + // if (once) + // ImGui::Text("This will be displayed only once."); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsBullets() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsBullets() +{ + IMGUI_DEMO_MARKER("Widgets/Bullets"); + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + if (ImGui::TreeNode("Tree node")) + { + ImGui::BulletText("Another bullet point"); + ImGui::TreePop(); + } + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsCollapsingHeaders() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsCollapsingHeaders() +{ + IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + ImGui::Checkbox("Show 2nd header", &closable_group); + if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + /* + if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet)) + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + */ + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsColorAndPickers() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsColorAndPickers() +{ + IMGUI_DEMO_MARKER("Widgets/Color"); + if (ImGui::TreeNode("Color/Picker Widgets")) + { + static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); + static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_None; + + ImGui::SeparatorText("Options"); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &base_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaOpaque", &base_flags, ImGuiColorEditFlags_AlphaOpaque); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaNoBg", &base_flags, ImGuiColorEditFlags_AlphaNoBg); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoColorMarkers", &base_flags, ImGuiColorEditFlags_NoColorMarkers); + ImGui::CheckboxFlags("ImGuiColorEditFlags_HDR", &base_flags, ImGuiColorEditFlags_HDR); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); + ImGui::SeparatorText("Inline color editor"); + ImGui::Text("Color widget:"); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "Ctrl+Click on individual component to input value.\n"); + ImGui::ColorEdit3("MyColor##1", (float*)&color, base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); + ImGui::Text("Color widget HSV with Alpha:"); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)"); + ImGui::Text("Color widget with Float Display:"); + ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)"); + ImGui::Text("Color button with Picker:"); + ImGui::SameLine(); HelpMarker( + "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" + "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " + "be used for the tooltip and picker popup."); + ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)"); + ImGui::Text("Color button with Custom Picker Popup:"); + + // Generate a default palette. The palette will persist and can be edited. + static bool saved_palette_init = true; + static ImVec4 saved_palette[32] = {}; + if (saved_palette_init) + { + for (int n = 0; n < IM_COUNTOF(saved_palette); n++) + { + ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, + saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); + saved_palette[n].w = 1.0f; // Alpha + } + saved_palette_init = false; + } + + static ImVec4 backup_color; + bool open_popup = ImGui::ColorButton("MyColor##3b", color, base_flags); + ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); + open_popup |= ImGui::Button("Palette"); + if (open_popup) + { + ImGui::OpenPopup("mypicker"); + backup_color = color; + } + if (ImGui::BeginPopup("mypicker")) + { + ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); + ImGui::Separator(); + ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); + ImGui::SameLine(); + + ImGui::BeginGroup(); // Lock X position + ImGui::Text("Current"); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); + ImGui::Text("Previous"); + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) + color = backup_color; + ImGui::Separator(); + ImGui::Text("Palette"); + for (int n = 0; n < IM_COUNTOF(saved_palette); n++) + { + ImGui::PushID(n); + if ((n % 8) != 0) + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); + + ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) + color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! + + // Allow user to drop colors into each palette entry. Note that ColorButton() is already a + // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3); + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4); + ImGui::EndDragDropTarget(); + } + + ImGui::PopID(); + } + ImGui::EndGroup(); + ImGui::EndPopup(); + } + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); + ImGui::Text("Color button only:"); + static bool no_border = false; + ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); + ImGui::SeparatorText("Color picker"); + + static bool ref_color = false; + static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); + static int picker_mode = 0; + static int display_mode = 0; + static ImGuiColorEditFlags color_picker_flags = ImGuiColorEditFlags_AlphaBar; + + ImGui::PushID("Color picker"); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &color_picker_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaBar", &color_picker_flags, ImGuiColorEditFlags_AlphaBar); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoSidePreview", &color_picker_flags, ImGuiColorEditFlags_NoSidePreview); + if (color_picker_flags & ImGuiColorEditFlags_NoSidePreview) + { + ImGui::SameLine(); + ImGui::Checkbox("With Ref Color", &ref_color); + if (ref_color) + { + ImGui::SameLine(); + ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | base_flags); + } + } + + ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0ImGuiColorEditFlags_PickerHueBar\0ImGuiColorEditFlags_PickerHueWheel\0"); + ImGui::SameLine(); HelpMarker("When not specified explicitly, user can right-click the picker to change mode."); + + ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0ImGuiColorEditFlags_NoInputs\0ImGuiColorEditFlags_DisplayRGB\0ImGuiColorEditFlags_DisplayHSV\0ImGuiColorEditFlags_DisplayHex\0"); + ImGui::SameLine(); HelpMarker( + "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " + "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex " + "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); + + ImGuiColorEditFlags flags = base_flags | color_picker_flags; + if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; + if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays + if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode + if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV; + if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; + ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); + + ImGui::Text("Set defaults in code:"); + ImGui::SameLine(); HelpMarker( + "SetColorEditOptions() is designed to allow you to set boot-time default.\n" + "We don't have Push/Pop functions because you can force options on a per-widget basis if needed, " + "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid " + "encouraging you to persistently save values that aren't forward-compatible."); + if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); + if (ImGui::Button("Default: Float + HDR + Hue Wheel")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); + + // Always display a small version of both types of pickers + // (that's in order to make it more visible in the demo to people who are skimming quickly through it) + ImGui::Text("Both types:"); + float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.y) * 0.40f; + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##5", (float*)&color, ImGuiColorEditFlags_PickerHueBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::SameLine(); + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::PopID(); + + // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! + ImGui::Spacing(); + ImGui::Text("HSV encoded colors"); + ImGui::SameLine(); HelpMarker( + "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV " + "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the " + "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); + ImGui::Text("Color widget with InputHSV:"); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsComboBoxes() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsComboBoxes() +{ + IMGUI_DEMO_MARKER("Widgets/Combo"); + if (ImGui::TreeNode("Combo")) + { + // Combo Boxes are also called "Dropdown" in other systems + // Expose flags as checkbox for the demo + static ImGuiComboFlags flags = 0; + ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft); + ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton)) + flags &= ~ImGuiComboFlags_NoPreview; // Clear incompatible flags + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview)) + flags &= ~(ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_WidthFitPreview); // Clear incompatible flags + if (ImGui::CheckboxFlags("ImGuiComboFlags_WidthFitPreview", &flags, ImGuiComboFlags_WidthFitPreview)) + flags &= ~ImGuiComboFlags_NoPreview; + + // Override default popup height + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightSmall", &flags, ImGuiComboFlags_HeightSmall)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightSmall); + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightRegular", &flags, ImGuiComboFlags_HeightRegular)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightRegular); + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightLargest", &flags, ImGuiComboFlags_HeightLargest)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightLargest); + + // Using the generic BeginCombo() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_selected_idx = 0; // Here we store our selection data as an index. + + // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) + const char* combo_preview_value = items[item_selected_idx]; + if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) + { + for (int n = 0; n < IM_COUNTOF(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + // Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + // See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. + if (ImGui::BeginCombo("combo 2 (w/ filter)", combo_preview_value, flags)) + { + static ImGuiTextFilter filter; + if (ImGui::IsWindowAppearing()) + { + ImGui::SetKeyboardFocusHere(); + filter.Clear(); + } + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); + filter.Draw("##Filter", -FLT_MIN); + + for (int n = 0; n < IM_COUNTOF(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (filter.PassFilter(items[n])) + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + } + ImGui::EndCombo(); + } + + ImGui::Spacing(); + ImGui::SeparatorText("One-liner variants"); + HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section."); + + // Simplified one-liner Combo() API, using values packed in a single constant string + // This is a convenience for when the selection set is small and known at compile-time. + static int item_current_2 = 0; + ImGui::Combo("combo 3 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + + // Simplified one-liner Combo() using an array of const char* + // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview + ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_COUNTOF(items)); + + // Simplified one-liner Combo() using an accessor function + static int item_current_4 = 0; + ImGui::Combo("combo 5 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_COUNTOF(items)); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDataTypes() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsDataTypes() +{ + IMGUI_DEMO_MARKER("Widgets/Data Types"); + if (ImGui::TreeNode("Data Types")) + { + // DragScalar/InputScalar/SliderScalar functions allow various data types + // - signed/unsigned + // - 8/16/32/64-bits + // - integer/float/double + // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + // to pass the type, and passing all arguments by pointer. + // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each type. + // In practice, if you frequently use a given type that is not covered by the normal API entry points, + // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, + // and then pass their address to the generic function. For example: + // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") + // { + // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); + // } + + // Setup limits (as helper variables so we can take their address, as explained above) + // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. + #ifndef LLONG_MIN + ImS64 LLONG_MIN = -9223372036854775807LL - 1; + ImS64 LLONG_MAX = 9223372036854775807LL; + ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1); + #endif + const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127; + const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255; + const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767; + const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535; + const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2; + const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2; + const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2; + const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2; + const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f; + const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0; + + // State + static char s8_v = 127; + static ImU8 u8_v = 255; + static short s16_v = 32767; + static ImU16 u16_v = 65535; + static ImS32 s32_v = -1; + static ImU32 u32_v = (ImU32)-1; + static ImS64 s64_v = -1; + static ImU64 u64_v = (ImU64)-1; + static float f32_v = 0.123f; + static double f64_v = 90000.01234567890123456789; + + const float drag_speed = 0.2f; + static bool drag_clamp = false; + IMGUI_DEMO_MARKER("Widgets/Data Types/Drags"); + ImGui::SeparatorText("Drags"); + ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); + ImGui::SameLine(); HelpMarker( + "As with every widget in dear imgui, we never modify values unless there is a user interaction.\n" + "You can override the clamping limits by using Ctrl+Click to input a value."); + ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); + ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); + ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL); + ImGui::DragScalar("drag s32 hex", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL, "0x%08X"); + ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); + ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); + ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); + ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Sliders"); + ImGui::SeparatorText("Sliders"); + ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); + ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); + ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); + ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); + ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); + ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); + ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); + ImGui::SliderScalar("slider s32 hex", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "0x%04X"); + ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); + ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); + ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); + ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%" PRId64); + ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%" PRId64); + ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%" PRId64); + ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%" PRIu64 " ms"); + ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%" PRIu64 " ms"); + ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%" PRIu64 " ms"); + ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); + ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); + + ImGui::SeparatorText("Sliders (reverse)"); + ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d"); + ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u"); + ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d"); + ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u"); + ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%" PRId64); + ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%" PRIu64 " ms"); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Inputs"); + static bool inputs_step = true; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; + ImGui::SeparatorText("Inputs"); + ImGui::Checkbox("Show step buttons", &inputs_step); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ParseEmptyRefVal", &flags, ImGuiInputTextFlags_ParseEmptyRefVal); + ImGui::CheckboxFlags("ImGuiInputTextFlags_DisplayEmptyRefVal", &flags, ImGuiInputTextFlags_DisplayEmptyRefVal); + ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%04X", flags); + ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", flags); + ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL, NULL, NULL, flags); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDisableBlocks() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Widgets/Disable Blocks"); + if (ImGui::TreeNode("Disable Blocks")) + { + ImGui::Checkbox("Disable entire section above", &demo_data->DisableSections); + ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across other sections."); + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDragAndDrop() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsDragAndDrop() +{ + IMGUI_DEMO_MARKER("Widgets/Drag and drop"); + if (ImGui::TreeNode("Drag and Drop")) + { + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); + if (ImGui::TreeNode("Drag and drop in standard widgets")) + { + // ColorEdit widgets automatically act as drag source and drag target. + // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + // to allow your own widgets to use colors in their drag and drop interaction. + // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. + HelpMarker("You can drag from the color squares."); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::ColorEdit4("color 2", col2); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); + if (ImGui::TreeNode("Drag and drop to copy/swap items")) + { + enum Mode + { + Mode_Copy, + Mode_Move, + Mode_Swap + }; + static int mode = 0; + if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); + if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); + if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } + static const char* names[9] = + { + "Bobby", "Beatrice", "Betty", + "Brianna", "Barry", "Bernard", + "Bibi", "Blaine", "Bryn" + }; + for (int n = 0; n < IM_COUNTOF(names); n++) + { + ImGui::PushID(n); + if ((n % 3) != 0) + ImGui::SameLine(); + ImGui::Button(names[n], ImVec2(60, 60)); + + // Our buttons are both drag sources and drag targets here! + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) + { + // Set payload to carry the index of our item (could be anything) + ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); + + // Display preview (could be anything, e.g. when dragging an image we could decide to display + // the filename and a small preview of the image, etc.) + if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } + if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } + if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } + ImGui::EndDragDropSource(); + } + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL")) + { + IM_ASSERT(payload->DataSize == sizeof(int)); + int payload_n = *(const int*)payload->Data; + if (mode == Mode_Copy) + { + names[n] = names[payload_n]; + } + if (mode == Mode_Move) + { + names[n] = names[payload_n]; + names[payload_n] = ""; + } + if (mode == Mode_Swap) + { + const char* tmp = names[n]; + names[n] = names[payload_n]; + names[payload_n] = tmp; + } + } + ImGui::EndDragDropTarget(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); + if (ImGui::TreeNode("Drag to reorder items (simple)")) + { + // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. + // This code was always slightly faulty but in a way which was not easily noticeable. + // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue. + ImGui::PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); + + // Simple reordering + HelpMarker( + "We don't use the drag and drop api at all here! " + "Instead we query when the item is held but not hovered, and order items accordingly."); + static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; + for (int n = 0; n < IM_COUNTOF(item_names); n++) + { + const char* item = item_names[n]; + ImGui::Selectable(item); + + if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) + { + int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1); + if (n_next >= 0 && n_next < IM_COUNTOF(item_names)) + { + item_names[n] = item_names[n_next]; + item_names[n_next] = item; + ImGui::ResetMouseDragDelta(); + } + } + } + + ImGui::PopItemFlag(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location"); + if (ImGui::TreeNode("Tooltip at target location")) + { + for (int n = 0; n < 2; n++) + { + // Drop targets + ImGui::Button(n ? "drop here##1" : "drop here##0"); + if (ImGui::BeginDragDropTarget()) + { + ImGuiDragDropFlags drop_target_flags = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoPreviewTooltip; + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags)) + { + IM_UNUSED(payload); + ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); + ImGui::SetTooltip("Cannot drop here!"); + } + ImGui::EndDragDropTarget(); + } + + // Drop source + static ImVec4 col4 = { 1.0f, 0.0f, 0.2f, 1.0f }; + if (n == 0) + ImGui::ColorButton("drag me", col4); + + } + ImGui::TreePop(); + } + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDragsAndSliders() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsDragsAndSliders() +{ + IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); + if (ImGui::TreeNode("Drag/Slider Flags")) + { + // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! + static ImGuiSliderFlags flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds."); + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange); + ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp."); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable Ctrl+Click or Enter key allowing to input text directly into the widget."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoSpeedTweaks", &flags, ImGuiSliderFlags_NoSpeedTweaks); + ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic."); + ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); + ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); + ImGui::CheckboxFlags("ImGuiSliderFlags_ColorMarkers", &flags, ImGuiSliderFlags_ColorMarkers); + //ImGui::CheckboxFlags("ImGuiSliderFlags_ColorMarkersG", &flags, 1 << ImGuiSliderFlags_ColorMarkersIndexShift_); // Not explicitly documented but possible. + + // Drags + static float drag_f = 0.5f; + static float drag_f4[4]; + static int drag_i = 50; + ImGui::Text("Underlying float value: %f", drag_f); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); + //ImGui::DragFloat("DragFloat (0 -> 0)", &drag_f, 0.005f, 0.0f, 0.0f, "%.3f", flags); // To test ClampZeroRange + //ImGui::DragFloat("DragFloat (100 -> 100)", &drag_f, 0.005f, 100.0f, 100.0f, "%.3f", flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); + ImGui::DragFloat4("DragFloat4 (0 -> 1)", drag_f4, 0.005f, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. + + // Sliders + static float slider_f = 0.5f; + static float slider_f4[4]; + static int slider_i = 50; + const ImGuiSliderFlags flags_for_sliders = (flags & ~ImGuiSliderFlags_WrapAround); + ImGui::Text("Underlying float value: %f", slider_f); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags_for_sliders); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags_for_sliders); + ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsFonts() +//----------------------------------------------------------------------------- + +// Forward declare ShowFontAtlas() which isn't worth putting in public API yet +namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } + +static void DemoWindowWidgetsFonts() +{ + IMGUI_DEMO_MARKER("Widgets/Fonts"); + if (ImGui::TreeNode("Fonts")) + { + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + ImGui::ShowFontAtlas(atlas); + // FIXME-NEWATLAS: Provide a demo to add/create a procedural font? + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsImages() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsImages() +{ + IMGUI_DEMO_MARKER("Widgets/Images"); + if (ImGui::TreeNode("Images")) + { + ImGuiIO& io = ImGui::GetIO(); + ImGui::TextWrapped( + "Below we are displaying the font texture (which is the only texture we have access to in this demo). " + "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " + "Hover the texture for a zoomed view!"); + + // Below we are displaying the font texture because it is the only texture we have access to inside the demo! + // Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. + // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top + // of their respective source file to specify what they are using as texture identifier, for example: + // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. + // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. + // So with the DirectX11 backend, you call ImGui::Image() with a 'ID3D11ShaderResourceView*' cast to ImTextureID. + // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers + // to ImGui::Image(), and gather width/height through your own functions, etc. + // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + // it will help you debug issues if you are confused about it. + // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). + // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + + // Grab the current texture identifier used by the font atlas. + ImTextureRef my_tex_id = io.Fonts->TexRef; + + // Regular user code should never have to care about TexData-> fields, but since we want to display the entire texture here, we pull Width/Height from it. + float my_tex_w = (float)io.Fonts->TexData->Width; + float my_tex_h = (float)io.Fonts->TexData->Height; + + { + ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); + ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (ImGui::BeginItemTooltip()) + { + float region_sz = 32.0f; + float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; + float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; + float zoom = 4.0f; + if (region_x < 0.0f) { region_x = 0.0f; } + else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } + if (region_y < 0.0f) { region_y = 0.0f; } + else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } + ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); + ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); + ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); + ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); + ImGui::ImageWithBg(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(); + } + + IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons"); + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + // UV coordinates are often (0.0f, 0.0f) and (1.0f, 1.0f) to display an entire textures. + // Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. + // Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + ImGui::PushID(i); + if (i > 0) + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(i - 1.0f, i - 1.0f)); + ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible + ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h); // UV coordinates for (32,32) in our texture + ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + if (ImGui::ImageButton("", my_tex_id, size, uv0, uv1, bg_col, tint_col)) + pressed_count += 1; + if (i > 0) + ImGui::PopStyleVar(); + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsListBoxes() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsListBoxes() +{ + IMGUI_DEMO_MARKER("Widgets/List Boxes"); + if (ImGui::TreeNode("List Boxes")) + { + // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() + // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. + // You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() + // to always be called (inconsistent with BeginListBox()/EndListBox()). + + // Using the generic BeginListBox() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_selected_idx = 0; // Here we store our selected data as an index. + + static bool item_highlight = false; + int item_highlighted_idx = -1; // Here we store our highlighted data as an index. + ImGui::Checkbox("Highlight hovered item in second listbox", &item_highlight); + + if (ImGui::BeginListBox("listbox 1")) + { + for (int n = 0; n < IM_COUNTOF(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + + if (item_highlight && ImGui::IsItemHovered()) + item_highlighted_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + ImGui::SameLine(); HelpMarker("Here we are sharing selection state between both boxes."); + + // Custom size: use all width, 5 items tall + ImGui::Text("Full-width:"); + if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing()))) + { + for (int n = 0; n < IM_COUNTOF(items); n++) + { + bool is_selected = (item_selected_idx == n); + ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0; + if (ImGui::Selectable(items[n], is_selected, flags)) + item_selected_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsMultiComponents() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsMultiComponents() +{ + IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); + if (ImGui::TreeNode("Multi-component Widgets")) + { + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::SeparatorText("2-wide"); + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::InputInt2("input int2", vec4i); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + + ImGui::SeparatorText("3-wide"); + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::InputInt3("input int3", vec4i); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + + ImGui::SeparatorText("4-wide"); + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::SeparatorText("Ranges"); + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsPlotting() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsPlotting() +{ + // Plot/Graph widgets are not very good. +// Consider using a third-party library such as ImPlot: https://github.com/epezent/implot +// (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) + IMGUI_DEMO_MARKER("Widgets/Plotting"); + if (ImGui::TreeNode("Plotting")) + { + ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); + ImGui::TextLinkOpenURL("https://github.com/epezent/implot"); + ImGui::Separator(); + + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + // Plot as lines and plot as histogram + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_COUNTOF(arr)); + ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); + //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); + + // Fill an array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float + // and the sizeof() of your structure in the "stride" parameter. + static float values[90] = {}; + static int values_offset = 0; + static double refresh_time = 0.0; + if (!animate || refresh_time == 0.0) + refresh_time = ImGui::GetTime(); + while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset + 1) % IM_COUNTOF(values); + phase += 0.10f * values_offset; + refresh_time += 1.0f / 60.0f; + } + + // Plots can display overlay texts + // (in this example, we will display an average value) + { + float average = 0.0f; + for (int n = 0; n < IM_COUNTOF(values); n++) + average += values[n]; + average /= (float)IM_COUNTOF(values); + char overlay[32]; + sprintf(overlay, "avg %f", average); + ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); + } + + // Use functions to generate output + // FIXME: This is actually VERY awkward because current plot API only pass in indices. + // We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::SeparatorText("Functions"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::Combo("func", &func_type, "Sin\0Saw\0"); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsProgressBars() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsProgressBars() +{ + IMGUI_DEMO_MARKER("Widgets/Progress Bars"); + if (ImGui::TreeNode("Progress Bars")) + { + // Animate a simple progress bar + static float progress_accum = 0.0f, progress_dir = 1.0f; + progress_accum += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress_accum >= +1.1f) { progress_accum = +1.1f; progress_dir *= -1.0f; } + if (progress_accum <= -0.1f) { progress_accum = -0.1f; progress_dir *= -1.0f; } + + const float progress = IM_CLAMP(progress_accum, 0.0f, 1.0f); + + // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, + // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress * 1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); + + // Pass an animated negative value, e.g. -1.0f * (float)ImGui::GetTime() is the recommended value. + // Adjust the factor if you want to adjust the animation speed. + ImGui::ProgressBar(-1.0f * (float)ImGui::GetTime(), ImVec2(0.0f, 0.0f), "Searching.."); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Indeterminate"); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsQueryingStatuses() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsQueryingStatuses() +{ + IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); + if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) + { + // Select an item type + const char* item_names[] = + { + "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", + "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" + }; + static int item_type = 4; + static bool item_disabled = false; + ImGui::Combo("Item Type", &item_type, item_names, IM_COUNTOF(item_names), IM_COUNTOF(item_names)); + ImGui::SameLine(); + HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered()."); + ImGui::Checkbox("Item Disabled", &item_disabled); + + // Submit selected items so we can query their status in the code following it. + bool ret = false; + static bool b = false; + static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; + static char str[16] = {}; + if (item_disabled) + ImGui::BeginDisabled(true); + if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction + if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button + if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater) + if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox + if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item + if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_COUNTOF(str)); } // Testing input text (which handles tabbing) + if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_COUNTOF(str)); } // Testing input text (which uses a child window) + if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input + if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 10) { ret = ImGui::Selectable("ITEM: Selectable"); } // Testing selectable item + if (item_type == 11) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 12) { ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node + if (item_type == 13) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 14) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_COUNTOF(items)); } + if (item_type == 15) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_COUNTOF(items), IM_COUNTOF(items)); } + + bool hovered_delay_none = ImGui::IsItemHovered(); + bool hovered_delay_stationary = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary); + bool hovered_delay_short = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort); + bool hovered_delay_normal = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal); + bool hovered_delay_tooltip = ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip); // = Normal + Stationary + + // Display the values of IsItemHovered() and other common item state functions. + // Note that the ImGuiHoveredFlags_XXX flags can be combined. + // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + // we query every state in a single call to avoid storing them and to simplify the code. + ImGui::BulletText( + "Return value = %d\n" + "IsItemFocused() = %d\n" + "IsItemHovered() = %d\n" + "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsItemHovered(_AllowWhenOverlappedByItem) = %d\n" + "IsItemHovered(_AllowWhenOverlappedByWindow) = %d\n" + "IsItemHovered(_AllowWhenDisabled) = %d\n" + "IsItemHovered(_RectOnly) = %d\n" + "IsItemActive() = %d\n" + "IsItemEdited() = %d\n" + "IsItemActivated() = %d\n" + "IsItemDeactivated() = %d\n" + "IsItemDeactivatedAfterEdit() = %d\n" + "IsItemVisible() = %d\n" + "IsItemClicked() = %d\n" + "IsItemToggledOpen() = %d\n" + "GetItemRectMin() = (%.1f, %.1f)\n" + "GetItemRectMax() = (%.1f, %.1f)\n" + "GetItemRectSize() = (%.1f, %.1f)", + ret, + ImGui::IsItemFocused(), + ImGui::IsItemHovered(), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled), + ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly), + ImGui::IsItemActive(), + ImGui::IsItemEdited(), + ImGui::IsItemActivated(), + ImGui::IsItemDeactivated(), + ImGui::IsItemDeactivatedAfterEdit(), + ImGui::IsItemVisible(), + ImGui::IsItemClicked(), + ImGui::IsItemToggledOpen(), + ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y, + ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y, + ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y + ); + ImGui::BulletText( + "with Hovering Delay or Stationary test:\n" + "IsItemHovered() = %d\n" + "IsItemHovered(_Stationary) = %d\n" + "IsItemHovered(_DelayShort) = %d\n" + "IsItemHovered(_DelayNormal) = %d\n" + "IsItemHovered(_Tooltip) = %d", + hovered_delay_none, hovered_delay_stationary, hovered_delay_short, hovered_delay_normal, hovered_delay_tooltip); + + if (item_disabled) + ImGui::EndDisabled(); + + char buf[1] = ""; + ImGui::InputText("unused", buf, IM_COUNTOF(buf), ImGuiInputTextFlags_ReadOnly); + ImGui::SameLine(); + HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status."); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); + if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)")) + { + static bool embed_all_inside_a_child_window = false; + ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); + if (embed_all_inside_a_child_window) + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Borders); + + // Testing IsWindowFocused() function with its various flags. + ImGui::BulletText( + "IsWindowFocused() = %d\n" + "IsWindowFocused(_ChildWindows) = %d\n" + "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_RootWindow) = %d\n" + "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_AnyWindow) = %d\n", + ImGui::IsWindowFocused(), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); + + // Testing IsWindowHovered() function with its various flags. + ImGui::BulletText( + "IsWindowHovered() = %d\n" + "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsWindowHovered(_ChildWindows) = %d\n" + "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_RootWindow) = %d\n" + "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AnyWindow) = %d\n" + "IsWindowHovered(_Stationary) = %d\n", + ImGui::IsWindowHovered(), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary)); + + ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Borders); + ImGui::Text("This is another child window for testing the _ChildWindows flag."); + ImGui::EndChild(); + if (embed_all_inside_a_child_window) + ImGui::EndChild(); + + // Calling IsItemHovered() after begin returns the hovered status of the title bar. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. + // This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). + static bool test_window = false; + ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); + if (test_window) + { + // FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. + // Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? + ImGui::Begin("Title bar Hovered/Active tests", &test_window); + if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered() + { + if (ImGui::MenuItem("Close")) { test_window = false; } + ImGui::EndPopup(); + } + ImGui::Text( + "IsItemHovered() after begin = %d (== is title bar hovered)\n" + "IsItemActive() after begin = %d (== is window being clicked/moved)\n", + ImGui::IsItemHovered(), ImGui::IsItemActive()); + ImGui::End(); + } + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsSelectables() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsSelectables() +{ + IMGUI_DEMO_MARKER("Widgets/Selectables"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Selectables")) + { + // Selectable() has 2 overloads: + // - The one taking "bool selected" as a read-only selection information. + // When Selectable() has been clicked it returns true and you can alter selection state accordingly. + // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + // The earlier is more flexible, as in real application your selection may be stored in many different ways + // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). + IMGUI_DEMO_MARKER("Widgets/Selectables/Basic"); + if (ImGui::TreeNode("Basic")) + { + static bool selection[5] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selection[0]); + ImGui::Selectable("2. I am selectable", &selection[1]); + ImGui::Selectable("3. I am selectable", &selection[2]); + if (ImGui::Selectable("4. I am double clickable", selection[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selection[3] = !selection[3]; + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple items on the same line"); + if (ImGui::TreeNode("Multiple items on the same line")) + { + // (1) + // - Using SetNextItemAllowOverlap() + // - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. + { + static bool selected[3] = {}; + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3"); + } + + // (2) + // - Using ImGuiSelectableFlags_AllowOverlap is a shortcut for calling SetNextItemAllowOverlap() + // - No visible label, display contents inside the selectable bounds. + // - We don't maintain actual selection in this example to keep things simple. + ImGui::Spacing(); + { + static bool checked[5] = {}; + static int selected_n = 0; + const float color_marker_w = ImGui::CalcTextSize("x").x; + for (int n = 0; n < 5; n++) + { + ImGui::PushID(n); + ImGui::AlignTextToFramePadding(); + if (ImGui::Selectable("##selectable", selected_n == n, ImGuiSelectableFlags_AllowOverlap)) + selected_n = n; + ImGui::SameLine(0, 0); + ImGui::Checkbox("##check", &checked[n]); + ImGui::SameLine(); + ImVec4 color((n & 1) ? 1.0f : 0.2f, (n & 2) ? 1.0f : 0.2f, 0.2f, 1.0f); + ImGui::ColorButton("##color", color, ImGuiColorEditFlags_NoTooltip, ImVec2(color_marker_w, 0)); + ImGui::SameLine(); + ImGui::Text("Some label"); + ImGui::PopID(); + } + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); + if (ImGui::TreeNode("In Tables")) + { + static bool selected[10] = {}; + + if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap + } + ImGui::EndTable(); + } + ImGui::Spacing(); + if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns); + ImGui::TableNextColumn(); + ImGui::Text("Some other contents"); + ImGui::TableNextColumn(); + ImGui::Text("123456"); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); + if (ImGui::TreeNode("Grid")) + { + static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + + // Add in a bit of silly fun... + const float time = (float)ImGui::GetTime(); + const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected... + if (winning_state) + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + + const float size = ImGui::CalcTextSize("Sailor").x; + for (int y = 0; y < 4; y++) + for (int x = 0; x < 4; x++) + { + if (x > 0) + ImGui::SameLine(); + ImGui::PushID(y * 4 + x); + if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(size, size))) + { + // Toggle clicked cell + toggle neighbors + selected[y][x] ^= 1; + if (x > 0) { selected[y][x - 1] ^= 1; } + if (x < 3) { selected[y][x + 1] ^= 1; } + if (y > 0) { selected[y - 1][x] ^= 1; } + if (y < 3) { selected[y + 1][x] ^= 1; } + } + ImGui::PopID(); + } + + if (winning_state) + ImGui::PopStyleVar(); + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); + if (ImGui::TreeNode("Alignment")) + { + HelpMarker( + "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " + "basis using PushStyleVar(). You'll probably want to always keep your default situation to " + "left-align otherwise it becomes difficult to layout multiple items on a same line"); + + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; + const float size = ImGui::CalcTextSize("(1.0,1.0)").x; + for (int y = 0; y < 3; y++) + { + for (int x = 0; x < 3; x++) + { + ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f); + char name[32]; + sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); + if (x > 0) ImGui::SameLine(); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); + ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(size, size)); + ImGui::PopStyleVar(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() +//----------------------------------------------------------------------------- +// Multi-selection demos +// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select +//----------------------------------------------------------------------------- + +static const char* ExampleNames[] = +{ + "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", + "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", + "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" +}; + +// Extra functions to add deletion support to ImGuiSelectionBasicStorage +struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage +{ + // Find which item should be Focused after deletion. + // Call _before_ item submission. Return an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. + // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. + // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. + // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. + // - Important: Deletion only works if the underlying ImGuiID for your items are stable: aka not depend on their index, but on e.g. item id/ptr. + // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or scroll offset. + int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) + { + if (Size == 0) + return -1; + + // If focused item is not selected... + const int focused_idx = (int)ms_io->NavIdItem; // Index of currently focused item + if (ms_io->NavIdSelected == false) // This is merely a shortcut, == Contains(adapter->IndexToStorage(items, focused_idx)) + { + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even when NavIdSelected==true, but it would take an extra frame to recover RangeSrc when deleting a selected item. + return focused_idx; // Request to focus same item after deletion. + } + + // If focused item is selected: land on first unselected item after focused item. + for (int idx = focused_idx + 1; idx < items_count; idx++) + if (!Contains(GetStorageIdFromIndex(idx))) + return idx; + + // If focused item is selected: otherwise return last unselected item before focused item. + for (int idx = IM_MIN(focused_idx, items_count) - 1; idx >= 0; idx--) + if (!Contains(GetStorageIdFromIndex(idx))) + return idx; + + return -1; + } + + // Rewrite item list (delete items) + update selection. + // - Call after EndMultiSelect() + // - We cannot provide this logic in core Dear ImGui because we don't have access to your items, nor to selection data. + template + void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items, int item_curr_idx_to_select) + { + // Rewrite item list (delete items) + convert old selection index (before deletion) to new selection index (after selection). + // If NavId was not part of selection, we will stay on same item. + ImVector new_items; + new_items.reserve(items.Size - Size); + int item_next_idx_to_select = -1; + for (int idx = 0; idx < items.Size; idx++) + { + if (!Contains(GetStorageIdFromIndex(idx))) + new_items.push_back(items[idx]); + if (item_curr_idx_to_select == idx) + item_next_idx_to_select = new_items.Size - 1; + } + items.swap(new_items); + + // Update selection + Clear(); + if (item_next_idx_to_select != -1 && ms_io->NavIdSelected) + SetItemSelected(GetStorageIdFromIndex(item_next_idx_to_select), true); + } +}; + +// Example: Implement dual list box storage and interface +struct ExampleDualListBox +{ + ImVector Items[2]; // ID is index into ExampleName[] + ImGuiSelectionBasicStorage Selections[2]; // Store ExampleItemId into selection + bool OptKeepSorted = true; + + void MoveAll(int src, int dst) + { + IM_ASSERT((src == 0 && dst == 1) || (src == 1 && dst == 0)); + for (ImGuiID item_id : Items[src]) + Items[dst].push_back(item_id); + Items[src].clear(); + SortItems(dst); + Selections[src].Swap(Selections[dst]); + Selections[src].Clear(); + } + void MoveSelected(int src, int dst) + { + for (int src_n = 0; src_n < Items[src].Size; src_n++) + { + ImGuiID item_id = Items[src][src_n]; + if (!Selections[src].Contains(item_id)) + continue; + Items[src].erase(&Items[src][src_n]); // FIXME-OPT: Could be implemented more optimally (rebuild src items and swap) + Items[dst].push_back(item_id); + src_n--; + } + if (OptKeepSorted) + SortItems(dst); + Selections[src].Swap(Selections[dst]); + Selections[src].Clear(); + } + void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, int side) + { + // In this example we store item id in selection (instead of item index) + Selections[side].UserData = Items[side].Data; + Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->UserData; return items[idx]; }; + Selections[side].ApplyRequests(ms_io); + } + static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) + { + const int* a = (const int*)lhs; + const int* b = (const int*)rhs; + return *a - *b; + } + void SortItems(int n) + { + qsort(Items[n].Data, (size_t)Items[n].Size, sizeof(Items[n][0]), CompareItemsByValue); + } + void Show() + { + //if (ImGui::Checkbox("Sorted", &OptKeepSorted) && OptKeepSorted) { SortItems(0); SortItems(1); } + if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None)) + { + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); // Buttons + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Right side + ImGui::TableNextRow(); + + int request_move_selected = -1; + int request_move_all = -1; + float child_height_0 = 0.0f; + for (int side = 0; side < 2; side++) + { + // FIXME-MULTISELECT: Dual List Box: Add context menus + // FIXME-NAV: Using ImGuiWindowFlags_NavFlattened exhibit many issues. + ImVector& items = Items[side]; + ImGuiSelectionBasicStorage& selection = Selections[side]; + + ImGui::TableSetColumnIndex((side == 0) ? 0 : 2); + ImGui::Text("%s (%d)", (side == 0) ? "Available" : "Basket", items.Size); + + // Submit scrolling range to avoid glitches on moving/deletion + const float items_height = ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + + bool child_visible; + if (side == 0) + { + // Left child is resizable + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetFrameHeightWithSpacing() * 4), ImVec2(FLT_MAX, FLT_MAX)); + child_visible = ImGui::BeginChild("0", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY); + child_height_0 = ImGui::GetWindowSize().y; + } + else + { + // Right child use same height as left one + child_visible = ImGui::BeginChild("1", ImVec2(-FLT_MIN, child_height_0), ImGuiChildFlags_FrameStyle); + } + if (child_visible) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); + ApplySelectionRequests(ms_io, side); + + for (int item_n = 0; item_n < items.Size; item_n++) + { + ImGuiID item_id = items[item_n]; + bool item_is_selected = selection.Contains(item_id); + ImGui::SetNextItemSelectionUserData(item_n); + ImGui::Selectable(ExampleNames[item_id], item_is_selected, ImGuiSelectableFlags_AllowDoubleClick); + if (ImGui::IsItemFocused()) + { + // FIXME-MULTISELECT: Dual List Box: Transfer focus + if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) + request_move_selected = side; + if (ImGui::IsMouseDoubleClicked(0)) // FIXME-MULTISELECT: Double-click on multi-selection? + request_move_selected = side; + } + } + + ms_io = ImGui::EndMultiSelect(); + ApplySelectionRequests(ms_io, side); + } + ImGui::EndChild(); + } + + // Buttons columns + ImGui::TableSetColumnIndex(1); + ImGui::NewLine(); + //ImVec2 button_sz = { ImGui::CalcTextSize(">>").x + ImGui::GetStyle().FramePadding.x * 2.0f, ImGui::GetFrameHeight() + padding.y * 2.0f }; + ImVec2 button_sz = { ImGui::GetFrameHeight(), ImGui::GetFrameHeight() }; + + // (Using BeginDisabled()/EndDisabled() works but feels distracting given how it is currently visualized) + if (ImGui::Button(">>", button_sz)) + request_move_all = 0; + if (ImGui::Button(">", button_sz)) + request_move_selected = 0; + if (ImGui::Button("<", button_sz)) + request_move_selected = 1; + if (ImGui::Button("<<", button_sz)) + request_move_all = 1; + + // Process requests + if (request_move_all != -1) + MoveAll(request_move_all, request_move_all ^ 1); + if (request_move_selected != -1) + MoveSelected(request_move_selected, request_move_selected ^ 1); + + // FIXME-MULTISELECT: Support action from outside + /* + if (OptKeepSorted == false) + { + ImGui::NewLine(); + if (ImGui::ArrowButton("MoveUp", ImGuiDir_Up)) {} + if (ImGui::ArrowButton("MoveDown", ImGuiDir_Down)) {} + } + */ + + ImGui::EndTable(); + } + } +}; + +static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); + if (ImGui::TreeNode("Selection State & Multi-Select")) + { + HelpMarker("Selections can be built using Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); + + ImGui::BulletText("Wiki page:"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("imgui/wiki/Multi-Select", "https://github.com/ocornut/imgui/wiki/Multi-Select"); + + // Without any fancy API: manage single-selection yourself. + IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); + if (ImGui::TreeNode("Single-Select")) + { + static int selected = -1; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selected == n)) + selected = n; + } + ImGui::TreePop(); + } + + // Demonstrate implementation a most-basic form of multi-selection manually + // This doesn't support the Shift modifier which requires BeginMultiSelect()! + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)"); + if (ImGui::TreeNode("Multi-Select (manual/simplified, without BeginMultiSelect)")) + { + HelpMarker("Hold Ctrl and Click to select multiple items."); + static bool selection[5] = { false, false, false, false, false }; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selection[n])) + { + if (!ImGui::GetIO().KeyCtrl) // Clear selection when Ctrl is not held + memset(selection, 0, sizeof(selection)); + selection[n] ^= 1; // Toggle current item + } + } + ImGui::TreePop(); + } + + // Demonstrate handling proper multi-selection using the BeginMultiSelect/EndMultiSelect API. + // Shift+Click w/ Ctrl and other standard features are supported. + // We use the ImGuiSelectionBasicStorage helper which you may freely reimplement. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); + if (ImGui::TreeNode("Multi-Select")) + { + ImGui::Text("Supported features:"); + ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); + ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); + ImGui::BulletText("Shift modifier for range selection."); + ImGui::BulletText("Ctrl+A to select all."); + ImGui::BulletText("Escape to clear selection."); + ImGui::BulletText("Click and drag to box-select."); + ImGui::Text("Tip: Use 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen."); + + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection + const int ITEMS_COUNT = 50; + static ImGuiSelectionBasicStorage selection; + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); + + // The BeginChild() has no purpose for selection logic, other that offering a scrolling region. + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); + + for (int n = 0; n < ITEMS_COUNT; n++) + { + char label[64]; + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); + bool item_is_selected = selection.Contains((ImGuiID)n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + } + + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + } + ImGui::EndChild(); + ImGui::TreePop(); + } + + // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)"); + if (ImGui::TreeNode("Multi-Select (with clipper)")) + { + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection + static ImGuiSelectionBasicStorage selection; + + ImGui::Text("Added features:"); + ImGui::BulletText("Using ImGuiListClipper."); + + const int ITEMS_COUNT = 10000; + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); + + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. + while (clipper.Step()) + { + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + char label[64]; + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); + bool item_is_selected = selection.Contains((ImGuiID)n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + } + } + + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + } + ImGui::EndChild(); + ImGui::TreePop(); + } + + // Demonstrate dynamic item list + deletion support using the BeginMultiSelect/EndMultiSelect API. + // In order to support Deletion without any glitches you need to: + // - (1) If items are submitted in their own scrolling area, submit contents size SetNextWindowContentSize() ahead of time to prevent one-frame readjustment of scrolling. + // - (2) Items needs to have persistent ID Stack identifier = ID needs to not depends on their index. PushID(index) = KO. PushID(item_id) = OK. This is in order to focus items reliably after a selection. + // - (3) BeginXXXX process + // - (4) Focus process + // - (5) EndXXXX process + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)"); + if (ImGui::TreeNode("Multi-Select (with deletion)")) + { + // Storing items data separately from selection data. + // (you may decide to store selection data inside your item (aka intrusive storage) if you don't need multiple views over same items) + // Use a custom selection.Adapter: store item identifier in Selection (instead of index) + static ImVector items; + static ExampleSelectionWithDeletion selection; + selection.UserData = (void*)&items; + selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImVector* p_items = (ImVector*)self->UserData; return (*p_items)[idx]; }; // Index -> ID + + ImGui::Text("Added features:"); + ImGui::BulletText("Dynamic list with Delete key support."); + ImGui::Text("Selection size: %d/%d", selection.Size, items.Size); + + // Initialize default list with 50 items + button to add/remove items. + static ImGuiID items_next_id = 0; + if (items_next_id == 0) + for (ImGuiID n = 0; n < 50; n++) + items.push_back(items_next_id++); + if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } + ImGui::SameLine(); + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetItemSelected(items.back(), false); items.pop_back(); } } + + // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion + const float items_height = ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); + selection.ApplyRequests(ms_io); + + const bool want_delete = ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0); + const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; + + for (int n = 0; n < items.Size; n++) + { + const ImGuiID item_id = items[n]; + char label[64]; + sprintf(label, "Object %05u: %s", item_id, ExampleNames[item_id % IM_COUNTOF(ExampleNames)]); + + bool item_is_selected = selection.Contains(item_id); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + if (item_curr_idx_to_focus == n) + ImGui::SetKeyboardFocusHere(-1); + } + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + if (want_delete) + selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); + } + ImGui::EndChild(); + ImGui::TreePop(); + } + + // Implement a Dual List Box (#6648) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (dual list box)"); + if (ImGui::TreeNode("Multi-Select (dual list box)")) + { + // Init default state + static ExampleDualListBox dlb; + if (dlb.Items[0].Size == 0 && dlb.Items[1].Size == 0) + for (int item_id = 0; item_id < IM_COUNTOF(ExampleNames); item_id++) + dlb.Items[0].push_back((ImGuiID)item_id); + + // Show + dlb.Show(); + + ImGui::TreePop(); + } + + // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (in a table)"); + if (ImGui::TreeNode("Multi-Select (in a table)")) + { + static ImGuiSelectionBasicStorage selection; + + const int ITEMS_COUNT = 10000; + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); + if (ImGui::BeginTable("##Basket", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter, ImVec2(0.0f, ImGui::GetFontSize() * 20))) + { + ImGui::TableSetupColumn("Object"); + ImGui::TableSetupColumn("Action"); + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableHeadersRow(); + + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); + + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. + while (clipper.Step()) + { + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushID(n); + char label[64]; + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); + bool item_is_selected = selection.Contains((ImGuiID)n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); + ImGui::TableNextColumn(); + ImGui::SmallButton("hello"); + ImGui::PopID(); + } + } + + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)"); + if (ImGui::TreeNode("Multi-Select (checkboxes)")) + { + ImGui::Text("In a list of checkboxes (not selectable):"); + ImGui::BulletText("Using _NoAutoSelect + _NoAutoClear flags."); + ImGui::BulletText("Shift+Click to check multiple boxes."); + ImGui::BulletText("Shift+Keyboard to copy current value to other boxes."); + + // If you have an array of checkboxes, you may want to use NoAutoSelect + NoAutoClear and the ImGuiSelectionExternalStorage helper. + static bool items[20] = {}; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. + + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_COUNTOF(items)); + ImGuiSelectionExternalStorage storage_wrapper; + storage_wrapper.UserData = (void*)items; + storage_wrapper.AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int n, bool selected) { bool* array = (bool*)self->UserData; array[n] = selected; }; + storage_wrapper.ApplyRequests(ms_io); + for (int n = 0; n < 20; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Checkbox(label, &items[n]); + } + ms_io = ImGui::EndMultiSelect(); + storage_wrapper.ApplyRequests(ms_io); + } + ImGui::EndChild(); + + ImGui::TreePop(); + } + + // Demonstrate individual selection scopes in same window + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); + if (ImGui::TreeNode("Multi-Select (multiple scopes)")) + { + // Use default select: Pass index to SetNextItemSelectionUserData(), store index in Selection + const int SCOPES_COUNT = 3; + const int ITEMS_COUNT = 8; // Per scope + static ImGuiSelectionBasicStorage selections_data[SCOPES_COUNT]; + + // Use ImGuiMultiSelectFlags_ScopeRect to not affect other selections in same window. + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ScopeRect | ImGuiMultiSelectFlags_ClearOnEscape;// | ImGuiMultiSelectFlags_ClearOnClickVoid; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) + flags &= ~ImGuiMultiSelectFlags_ScopeRect; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) + flags &= ~ImGuiMultiSelectFlags_ScopeWindow; + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); + + for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) + { + ImGui::PushID(selection_scope_n); + ImGuiSelectionBasicStorage* selection = &selections_data[selection_scope_n]; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection->Size, ITEMS_COUNT); + selection->ApplyRequests(ms_io); + + ImGui::SeparatorText("Selection scope"); + ImGui::Text("Selection size: %d/%d", selection->Size, ITEMS_COUNT); + + for (int n = 0; n < ITEMS_COUNT; n++) + { + char label[64]; + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); + bool item_is_selected = selection->Contains((ImGuiID)n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + } + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection->ApplyRequests(ms_io); + ImGui::PopID(); + } + ImGui::TreePop(); + } + + // See ShowExampleAppAssetsBrowser() + if (ImGui::TreeNode("Multi-Select (tiled assets browser)")) + { + ImGui::Checkbox("Assets Browser", &demo_data->ShowAppAssetsBrowser); + ImGui::Text("(also access from 'Examples->Assets Browser' in menu)"); + ImGui::TreePop(); + } + + // Demonstrate supporting multiple-selection in a tree. + // - We don't use linear indices for selection user data, but our ExampleTreeNode* pointer directly! + // This showcase how SetNextItemSelectionUserData() never assume indices! + // - The difficulty here is to "interpolate" from RangeSrcItem to RangeDstItem in the SetAll/SetRange request. + // We want this interpolation to match what the user sees: in visible order, skipping closed nodes. + // This is implemented by our TreeGetNextNodeInVisibleOrder() user-space helper. + // - Important: In a real codebase aiming to implement full-featured selectable tree with custom filtering, you + // are more likely to build an array mapping sequential indices to visible tree nodes, since your + // filtering/search + clipping process will benefit from it. Having this will make this interpolation much easier. + // - Consider this a prototype: we are working toward simplifying some of it. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (trees)"); + if (ImGui::TreeNode("Multi-Select (trees)")) + { + HelpMarker( + "This is rather advanced and experimental. If you are getting started with multi-select, " + "please don't start by looking at how to use it for a tree!\n\n" + "Future versions will try to simplify and formalize some of this."); + + struct ExampleTreeFuncs + { + static void DrawNode(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Enable pressing left to jump to parent + if (node->Childs.Size == 0) + tree_node_flags |= ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_Leaf; + if (selection->Contains((ImGuiID)node->UID)) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + + // Using SetNextItemStorageID() to specify storage id, so we can easily peek into + // the storage holding open/close stage, using our TreeNodeGetOpen/TreeNodeSetOpen() functions. + ImGui::SetNextItemSelectionUserData((ImGuiSelectionUserData)(intptr_t)node); + ImGui::SetNextItemStorageID((ImGuiID)node->UID); + if (ImGui::TreeNodeEx(node->Name, tree_node_flags)) + { + for (ExampleTreeNode* child : node->Childs) + DrawNode(child, selection); + ImGui::TreePop(); + } + else if (ImGui::IsItemToggledOpen()) + { + TreeCloseAndUnselectChildNodes(node, selection); + } + } + + static bool TreeNodeGetOpen(ExampleTreeNode* node) + { + return ImGui::GetStateStorage()->GetBool((ImGuiID)node->UID); + } + + static void TreeNodeSetOpen(ExampleTreeNode* node, bool open) + { + ImGui::GetStateStorage()->SetBool((ImGuiID)node->UID, open); + } + + // When closing a node: 1) close and unselect all child nodes, 2) select parent if any child was selected. + // FIXME: This is currently handled by user logic but I'm hoping to eventually provide tree node + // features to do this automatically, e.g. a ImGuiTreeNodeFlags_AutoCloseChildNodes etc. + static int TreeCloseAndUnselectChildNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, int depth = 0) + { + // Recursive close (the test for depth == 0 is because we call this on a node that was just closed!) + int unselected_count = selection->Contains((ImGuiID)node->UID) ? 1 : 0; + if (depth == 0 || TreeNodeGetOpen(node)) + { + for (ExampleTreeNode* child : node->Childs) + unselected_count += TreeCloseAndUnselectChildNodes(child, selection, depth + 1); + TreeNodeSetOpen(node, false); + } + + // Select root node if any of its child was selected, otherwise unselect + selection->SetItemSelected((ImGuiID)node->UID, (depth == 0 && unselected_count > 0)); + return unselected_count; + } + + // Apply multi-selection requests + static void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, ExampleTreeNode* tree, ImGuiSelectionBasicStorage* selection) + { + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + { + if (req.Selected) + TreeSetAllInOpenNodes(tree, selection, req.Selected); + else + selection->Clear(); + } + else if (req.Type == ImGuiSelectionRequestType_SetRange) + { + ExampleTreeNode* first_node = (ExampleTreeNode*)(intptr_t)req.RangeFirstItem; + ExampleTreeNode* last_node = (ExampleTreeNode*)(intptr_t)req.RangeLastItem; + for (ExampleTreeNode* node = first_node; node != NULL; node = TreeGetNextNodeInVisibleOrder(node, last_node)) + selection->SetItemSelected((ImGuiID)node->UID, req.Selected); + } + } + } + + static void TreeSetAllInOpenNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, bool selected) + { + if (node->Parent != NULL) // Root node isn't visible nor selectable in our scheme + selection->SetItemSelected((ImGuiID)node->UID, selected); + if (node->Parent == NULL || TreeNodeGetOpen(node)) + for (ExampleTreeNode* child : node->Childs) + TreeSetAllInOpenNodes(child, selection, selected); + } + + // Interpolate in *user-visible order* AND only *over opened nodes*. + // If you have a sequential mapping tables (e.g. generated after a filter/search pass) this would be simpler. + // Here the tricks are that: + // - we store/maintain ExampleTreeNode::IndexInParent which allows implementing a linear iterator easily, without searches, without recursion. + // this could be replaced by a search in parent, aka 'int index_in_parent = curr_node->Parent->Childs.find_index(curr_node)' + // which would only be called when crossing from child to a parent, aka not too much. + // - we call SetNextItemStorageID() before our TreeNode() calls with an ID which doesn't relate to UI stack, + // making it easier to call TreeNodeGetOpen()/TreeNodeSetOpen() from any location. + static ExampleTreeNode* TreeGetNextNodeInVisibleOrder(ExampleTreeNode* curr_node, ExampleTreeNode* last_node) + { + // Reached last node + if (curr_node == last_node) + return NULL; + + // Recurse into childs. Query storage to tell if the node is open. + if (curr_node->Childs.Size > 0 && TreeNodeGetOpen(curr_node)) + return curr_node->Childs[0]; + + // Next sibling, then into our own parent + while (curr_node->Parent != NULL) + { + if (curr_node->IndexInParent + 1 < curr_node->Parent->Childs.Size) + return curr_node->Parent->Childs[curr_node->IndexInParent + 1]; + curr_node = curr_node->Parent; + } + return NULL; + } + + }; // ExampleTreeFuncs + + static ImGuiSelectionBasicStorage selection; + if (demo_data->DemoTree == NULL) + demo_data->DemoTree = ExampleTree_CreateDemoTree(); // Create tree once + ImGui::Text("Selection size: %d", selection.Size); + + if (ImGui::BeginChild("##Tree", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ExampleTreeNode* tree = demo_data->DemoTree; + ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect2d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, selection.Size, -1); + ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection); + for (ExampleTreeNode* node : tree->Childs) + ExampleTreeFuncs::DrawNode(node, &selection); + ms_io = ImGui::EndMultiSelect(); + ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection); + } + ImGui::EndChild(); + + ImGui::TreePop(); + } + + // Advanced demonstration of BeginMultiSelect() + // - Showcase clipping. + // - Showcase deletion. + // - Showcase basic drag and drop. + // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). + // - Showcase using inside a table. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Multi-Select (advanced)")) + { + // Options + enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; + static bool use_clipper = true; + static bool use_deletion = true; + static bool use_drag_drop = true; + static bool show_in_table = false; + static bool show_color_button = true; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + static WidgetType widget_type = WidgetType_Selectable; + + if (ImGui::TreeNode("Options")) + { + if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } + ImGui::SameLine(); + if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } + ImGui::SameLine(); + HelpMarker("TreeNode() is technically supported but... using this correctly is more complicated (you need some sort of linear/random access to your tree, which is suited to advanced trees setups already implementing filters and clipper. We will work toward simplifying and demoing this.\n\nFor now the tree demo is actually a little bit meaningless because it is an empty tree with only root nodes."); + ImGui::Checkbox("Enable clipper", &use_clipper); + ImGui::Checkbox("Enable deletion", &use_deletion); + ImGui::Checkbox("Enable drag & drop", &use_drag_drop); + ImGui::Checkbox("Show in a table", &show_in_table); + ImGui::Checkbox("Show color button", &show_color_button); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClearOnReselect", &flags, ImGuiMultiSelectFlags_NoAutoClearOnReselect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectOnRightClick", &flags, ImGuiMultiSelectFlags_NoSelectOnRightClick); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) + flags &= ~ImGuiMultiSelectFlags_ScopeRect; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) + flags &= ~ImGuiMultiSelectFlags_ScopeWindow; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClick", &flags, ImGuiMultiSelectFlags_SelectOnClick) && (flags & ImGuiMultiSelectFlags_SelectOnClick)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClick; + ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); + ImGui::TreePop(); + } + + // Initialize default list with 1000 items. + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection + static ImVector items; + static int items_next_id = 0; + if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } + static ExampleSelectionWithDeletion selection; + static bool request_deletion_from_menu = false; // Queue deletion triggered from context menu + + ImGui::Text("Selection size: %d/%d", selection.Size, items.Size); + + const float items_height = (widget_type == WidgetType_TreeNode) ? ImGui::GetTextLineHeight() : ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); + if (widget_type == WidgetType_TreeNode) + ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, 0.0f); + + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); + selection.ApplyRequests(ms_io); + + const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0)) || request_deletion_from_menu; + const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; + request_deletion_from_menu = false; + + if (show_in_table) + { + if (widget_type == WidgetType_TreeNode) + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); + ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); + //ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, 0.0f); + } + + ImGuiListClipper clipper; + if (use_clipper) + { + clipper.Begin(items.Size); + if (item_curr_idx_to_focus != -1) + clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped. + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. + } + + while (!use_clipper || clipper.Step()) + { + const int item_begin = use_clipper ? clipper.DisplayStart : 0; + const int item_end = use_clipper ? clipper.DisplayEnd : items.Size; + for (int n = item_begin; n < item_end; n++) + { + if (show_in_table) + ImGui::TableNextColumn(); + + const int item_id = items[n]; + const char* item_category = ExampleNames[item_id % IM_COUNTOF(ExampleNames)]; + char label[64]; + sprintf(label, "Object %05d: %s", item_id, item_category); + + // IMPORTANT: for deletion refocus to work we need object ID to be stable, + // aka not depend on their index in the list. Here we use our persistent item_id + // instead of index to build a unique ID that will persist. + // (If we used PushID(index) instead, focus wouldn't be restored correctly after deletion). + ImGui::PushID(item_id); + + // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part + // of the selection scope doesn't erroneously alter our selection. + if (show_color_button) + { + ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; + ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); + ImGui::SameLine(); + } + + // Submit item + bool item_is_selected = selection.Contains((ImGuiID)n); + bool item_is_open = false; + ImGui::SetNextItemSelectionUserData(n); + if (widget_type == WidgetType_Selectable) + { + ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_None); + } + else if (widget_type == WidgetType_TreeNode) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + if (item_is_selected) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + item_is_open = ImGui::TreeNodeEx(label, tree_node_flags); + } + + // Focus (for after deletion) + if (item_curr_idx_to_focus == n) + ImGui::SetKeyboardFocusHere(-1); + + // Drag and Drop + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + // Create payload with full selection OR single unselected item. + // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) + if (ImGui::GetDragDropPayload() == NULL) + { + ImVector payload_items; + void* it = NULL; + ImGuiID id = 0; + if (!item_is_selected) + payload_items.push_back(item_id); + else + while (selection.GetNextSelectedItem(&it, &id)) + payload_items.push_back((int)id); + ImGui::SetDragDropPayload("MULTISELECT_DEMO_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); + } + + // Display payload content in tooltip + const ImGuiPayload* payload = ImGui::GetDragDropPayload(); + const int* payload_items = (int*)payload->Data; + const int payload_count = (int)payload->DataSize / (int)sizeof(int); + if (payload_count == 1) + ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_COUNTOF(ExampleNames)]); + else + ImGui::Text("Dragging %d objects", payload_count); + + ImGui::EndDragDropSource(); + } + + if (widget_type == WidgetType_TreeNode && item_is_open) + ImGui::TreePop(); + + // Right-click: context menu + if (ImGui::BeginPopupContextItem()) + { + ImGui::BeginDisabled(!use_deletion || selection.Size == 0); + sprintf(label, "Delete %d item(s)###DeleteSelected", selection.Size); + if (ImGui::Selectable(label)) + request_deletion_from_menu = true; + ImGui::EndDisabled(); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + + // Demo content within a table + if (show_in_table) + { + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::InputText("##NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly); + ImGui::PopStyleVar(); + } + + ImGui::PopID(); + } + if (!use_clipper) + break; + } + + if (show_in_table) + { + ImGui::EndTable(); + if (widget_type == WidgetType_TreeNode) + ImGui::PopStyleVar(); + } + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + if (want_delete) + selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); + + if (widget_type == WidgetType_TreeNode) + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTabs() +//----------------------------------------------------------------------------- + +static void EditTabBarFittingPolicyFlags(ImGuiTabBarFlags* p_flags) +{ + if ((*p_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + *p_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyMixed", p_flags, ImGuiTabBarFlags_FittingPolicyMixed)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyMixed); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyShrink", p_flags, ImGuiTabBarFlags_FittingPolicyShrink)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyShrink); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", p_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); +} + +static void DemoWindowWidgetsTabs() +{ + IMGUI_DEMO_MARKER("Widgets/Tabs"); + if (ImGui::TreeNode("Tabs")) + { + IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + if (ImGui::BeginTabItem("Avocado")) + { + ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Broccoli")) + { + ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Cucumber")) + { + ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); + if (ImGui::TreeNode("Advanced & Close Button")) + { + // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; + ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline); + EditTabBarFittingPolicyFlags(&tab_bar_flags); + + // Tab Bar + ImGui::AlignTextToFramePadding(); + ImGui::Text("Opened:"); + const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; + static bool opened[4] = { true, true, true, true }; // Persistent user state + for (int n = 0; n < IM_COUNTOF(opened); n++) + { + ImGui::SameLine(); + ImGui::Checkbox(names[n], &opened[n]); + } + + // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): + // the underlying bool will be set to false when the tab is closed. + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + for (int n = 0; n < IM_COUNTOF(opened); n++) + if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", names[n]); + if (n & 1) + ImGui::Text("I am an odd tab."); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); + if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) + { + static ImVector active_tabs; + static int next_tab_id = 0; + if (next_tab_id == 0) // Initialize with some default tabs + for (int i = 0; i < 3; i++) + active_tabs.push_back(next_tab_id++); + + // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + // but they tend to make more sense together) + static bool show_leading_button = true; + static bool show_trailing_button = true; + ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); + ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); + + // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyShrink; + EditTabBarFittingPolicyFlags(&tab_bar_flags); + + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + // Demo a Leading TabItemButton(): click the "?" button to open a menu + if (show_leading_button) + if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + ImGui::OpenPopup("MyHelpMenu"); + if (ImGui::BeginPopup("MyHelpMenu")) + { + ImGui::Selectable("Hello!"); + ImGui::EndPopup(); + } + + // Demo Trailing Tabs: click the "+" button to add a new tab. + // (In your app you may want to use a font icon instead of the "+") + // We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags_Trailing flag it will always appear at the end. + if (show_trailing_button) + if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + active_tabs.push_back(next_tab_id++); // Add new tab + + // Submit our regular tabs + for (int n = 0; n < active_tabs.Size; ) + { + bool open = true; + char name[16]; + snprintf(name, IM_COUNTOF(name), "%04d", active_tabs[n]); + if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", name); + ImGui::EndTabItem(); + } + + if (!open) + active_tabs.erase(active_tabs.Data + n); + else + n++; + } + + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsText() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsText() +{ + IMGUI_DEMO_MARKER("Widgets/Text"); + if (ImGui::TreeNode("Text")) + { + IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); + if (ImGui::TreeNode("Colorful Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/Font Size"); + if (ImGui::TreeNode("Font Size")) + { + ImGuiStyle& style = ImGui::GetStyle(); + const float global_scale = style.FontScaleMain * style.FontScaleDpi; + ImGui::Text("style.FontScaleMain = %0.2f", style.FontScaleMain); + ImGui::Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi); + ImGui::Text("global_scale = ~%0.2f", global_scale); // This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. + ImGui::Text("FontSize = %0.2f", ImGui::GetFontSize()); + + ImGui::SeparatorText(""); + static float custom_size = 16.0f; + ImGui::SliderFloat("custom_size", &custom_size, 10.0f, 100.0f, "%.0f"); + ImGui::Text("ImGui::PushFont(nullptr, custom_size);"); + ImGui::PushFont(NULL, custom_size); + ImGui::Text("FontSize = %.2f (== %.2f * global_scale)", ImGui::GetFontSize(), custom_size); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + static float custom_scale = 1.0f; + ImGui::SliderFloat("custom_scale", &custom_scale, 0.5f, 4.0f, "%.2f"); + ImGui::Text("ImGui::PushFont(nullptr, style.FontSizeBase * custom_scale);"); + ImGui::PushFont(NULL, style.FontSizeBase * custom_scale); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), custom_scale); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + for (float scaling = 0.5f; scaling <= 4.0f; scaling += 0.5f) + { + ImGui::PushFont(NULL, style.FontSizeBase * scaling); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), scaling); + ImGui::PopFont(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped( + "This text should automatically wrap on the edge of the window. The current implementation " + "for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 2; n++) + { + ImGui::Text("Test paragraph %d:", n); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); + ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + if (n == 0) + ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + else + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + + // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) + draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); + ImGui::PopTextWrapPos(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 + // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you + // can save your source files as 'UTF-8 without signature'). + // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 + // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. + // Don't do this in your application! Please use u8"text in any language" in your application! + // Note that characters values are preserved even by InputText() if the font cannot be displayed, + // so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped( + "CJK text will only appear if the font was loaded with the appropriate CJK character ranges. " + "Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. " + "Read docs/FONTS.md for details."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis + ImGui::InputText("UTF-8 input", buf, IM_COUNTOF(buf)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTextFilter() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsTextFilter() +{ + IMGUI_DEMO_MARKER("Widgets/Text Filter"); + if (ImGui::TreeNode("Text Filter")) + { + // Helper class to easy setup a text filter. + // You may want to implement a more feature-full filtering scheme in your own application. + HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings."); + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_COUNTOF(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTextInput() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsTextInput() +{ + // To wire InputText() with std::string or any other custom string type, + // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + IMGUI_DEMO_MARKER("Widgets/Text Input"); + if (ImGui::TreeNode("Text Input")) + { + IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); + if (ImGui::TreeNode("Multi-line Text Input")) + { + // WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. + // If you want to use InputText() with std::string or any custom dynamic string type: + // - For std::string: use the wrapper in misc/cpp/imgui_stdlib.h/.cpp + // - Otherwise, see the 'Dear ImGui Demo->Widgets->Text Input->Resize Callback' for using ImGuiInputTextFlags_CallbackResize. + static char text[1024 * 16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; + HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_WordWrap", &flags, ImGuiInputTextFlags_WordWrap); + ImGui::SameLine(); HelpMarker("Feature is currently in Beta. Please read comments in imgui.h"); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); + ImGui::InputTextMultiline("##source", text, IM_COUNTOF(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); + if (ImGui::TreeNode("Filtered Text Input")) + { + struct TextFilters + { + // Modify character input by altering 'data->Eventchar' (ImGuiInputTextFlags_CallbackCharFilter callback) + static int FilterCasingSwap(ImGuiInputTextCallbackData* data) + { + if (data->EventChar >= 'a' && data->EventChar <= 'z') { data->EventChar -= 'a' - 'A'; } // Lowercase becomes uppercase + else if (data->EventChar >= 'A' && data->EventChar <= 'Z') { data->EventChar += 'a' - 'A'; } // Uppercase becomes lowercase + return 0; + } + + // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) + static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) + { + if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) + return 0; + return 1; + } + }; + + static char buf1[32] = ""; ImGui::InputText("default", buf1, IM_COUNTOF(buf1)); + static char buf2[32] = ""; ImGui::InputText("decimal", buf2, IM_COUNTOF(buf2), ImGuiInputTextFlags_CharsDecimal); + static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, IM_COUNTOF(buf3), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, IM_COUNTOF(buf4), ImGuiInputTextFlags_CharsUppercase); + static char buf5[32] = ""; ImGui::InputText("no blank", buf5, IM_COUNTOF(buf5), ImGuiInputTextFlags_CharsNoBlank); + static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, IM_COUNTOF(buf6), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. + static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, IM_COUNTOF(buf7), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); + if (ImGui::TreeNode("Password Input")) + { + static char password[64] = "password123"; + ImGui::InputText("password", password, IM_COUNTOF(password), ImGuiInputTextFlags_Password); + ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_COUNTOF(password), ImGuiInputTextFlags_Password); + ImGui::InputText("password (clear)", password, IM_COUNTOF(password)); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks"); + if (ImGui::TreeNode("Completion, History, Edit Callbacks")) + { + struct Funcs + { + static int MyCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) + { + data->InsertChars(data->CursorPos, ".."); + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) + { + if (data->EventKey == ImGuiKey_UpArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Up!"); + data->SelectAll(); + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Down!"); + data->SelectAll(); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) + { + // Toggle casing of first character + char c = data->Buf[0]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; + data->BufDirty = true; + + // Increment a counter + int* p_int = (int*)data->UserData; + *p_int = *p_int + 1; + } + return 0; + } + }; + static char buf1[64]; + ImGui::InputText("Completion", buf1, IM_COUNTOF(buf1), ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker( + "Here we append \"..\" each time Tab is pressed. " + "See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf2[64]; + ImGui::InputText("History", buf2, IM_COUNTOF(buf2), ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker( + "Here we replace and select text each time Up/Down are pressed. " + "See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf3[64]; + static int edit_count = 0; + ImGui::InputText("Edit", buf3, IM_COUNTOF(buf3), ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::SameLine(); HelpMarker( + "Here we toggle the casing of the first character on every edit + count edits."); + ImGui::SameLine(); ImGui::Text("(%d)", edit_count); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); + if (ImGui::TreeNode("Resize Callback")) + { + // To wire InputText() with std::string or any other custom string type, + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper + // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. + HelpMarker( + "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" + "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); + struct Funcs + { + static int MyResizeCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + ImVector* my_str = (ImVector*)data->UserData; + IM_ASSERT(my_str->begin() == data->Buf); + my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 + data->Buf = my_str->begin(); + } + return 0; + } + + // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. + // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)' + static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) + { + IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); + return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); + } + }; + + // For this demo we are using ImVector as a string container. + // Note that because we need to store a terminating zero character, our size/capacity are 1 more + // than usually reported by a typical string class. + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; + ImGui::CheckboxFlags("ImGuiInputTextFlags_WordWrap", &flags, ImGuiInputTextFlags_WordWrap); + + static ImVector my_str; + if (my_str.empty()) + my_str.push_back(0); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); + ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment"); + if (ImGui::TreeNode("Eliding, Alignment")) + { + static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp"; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft; + ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft); + ImGui::InputText("Path", buf1, IM_COUNTOF(buf1), flags); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous"); + if (ImGui::TreeNode("Miscellaneous")) + { + static char buf1[16]; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_EscapeClearsAll; + ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_NoUndoRedo", &flags, ImGuiInputTextFlags_NoUndoRedo); + ImGui::InputText("Hello", buf1, IM_COUNTOF(buf1), flags); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTooltips() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsTooltips() +{ + IMGUI_DEMO_MARKER("Widgets/Tooltips"); + if (ImGui::TreeNode("Tooltips")) + { + // Tooltips are windows following the mouse. They do not take focus away. + ImGui::SeparatorText("General"); + + // Typical use cases: + // - Short-form (text only): SetItemTooltip("Hello"); + // - Short-form (any contents): if (BeginItemTooltip()) { Text("Hello"); EndTooltip(); } + + // - Full-form (text only): if (IsItemHovered(...)) { SetTooltip("Hello"); } + // - Full-form (any contents): if (IsItemHovered(...) && BeginTooltip()) { Text("Hello"); EndTooltip(); } + + HelpMarker( + "Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\n" + "We provide a helper SetItemTooltip() function to perform the two with standards flags."); + + ImVec2 sz = ImVec2(-FLT_MIN, 0.0f); + + ImGui::Button("Basic", sz); + ImGui::SetItemTooltip("I am a tooltip"); + + ImGui::Button("Fancy", sz); + if (ImGui::BeginItemTooltip()) + { + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_COUNTOF(arr)); + ImGui::Text("Sin(time) = %f", sinf((float)ImGui::GetTime())); + ImGui::EndTooltip(); + } + + ImGui::SeparatorText("Always On"); + + // Showcase NOT relying on a IsItemHovered() to emit a tooltip. + // Here the tooltip is always emitted when 'always_on == true'. + static int always_on = 0; + ImGui::RadioButton("Off", &always_on, 0); + ImGui::SameLine(); + ImGui::RadioButton("Always On (Simple)", &always_on, 1); + ImGui::SameLine(); + ImGui::RadioButton("Always On (Advanced)", &always_on, 2); + if (always_on == 1) + ImGui::SetTooltip("I am following you around."); + else if (always_on == 2 && ImGui::BeginTooltip()) + { + ImGui::ProgressBar(sinf((float)ImGui::GetTime()) * 0.5f + 0.5f, ImVec2(ImGui::GetFontSize() * 25, 0.0f)); + ImGui::EndTooltip(); + } + + ImGui::SeparatorText("Custom"); + + HelpMarker( + "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize " + "tooltip activation details across your application. You may however decide to use custom " + "flags for a specific tooltip instance."); + + // The following examples are passed for documentation purpose but may not be useful to most users. + // Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from + // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. + // With default settings, ImGuiHoveredFlags_ForTooltip is equivalent to ImGuiHoveredFlags_DelayShort + ImGuiHoveredFlags_Stationary. + ImGui::Button("Manual", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + ImGui::SetTooltip("I am a manually emitted tooltip."); + + ImGui::Button("DelayNone", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNone)) + ImGui::SetTooltip("I am a tooltip with no delay."); + + ImGui::Button("DelayShort", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_NoSharedDelay)) + ImGui::SetTooltip("I am a tooltip with a short delay (%0.2f sec).", ImGui::GetStyle().HoverDelayShort); + + ImGui::Button("DelayLong", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay)) + ImGui::SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui::GetStyle().HoverDelayNormal); + + ImGui::Button("Stationary", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary)) + ImGui::SetTooltip("I am a tooltip requiring mouse to be stationary before activating."); + + // Using ImGuiHoveredFlags_ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', + // which default value include the ImGuiHoveredFlags_AllowWhenDisabled flag. + ImGui::BeginDisabled(); + ImGui::Button("Disabled item", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + ImGui::SetTooltip("I am a a tooltip for a disabled item."); + ImGui::EndDisabled(); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTreeNodes() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsTreeNodes() +{ + IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); + if (ImGui::TreeNode("Tree Nodes")) + { + // See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + { + // Use SetNextItemOpen() so set the default state of a node to be open. We could + // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! + if (i == 0) + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + + // Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. + // An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode((void*)(intptr_t)i, ...)', + // aka generate a dummy pointer-sized value to be hashed. The demo below uses that technique. Both are fine. + ImGui::PushID(i); + if (ImGui::TreeNode("", "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("button")) {} + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Hierarchy lines"); + if (ImGui::TreeNode("Hierarchy lines")) + { + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DefaultOpen; + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + + if (ImGui::TreeNodeEx("Parent", base_flags)) + { + if (ImGui::TreeNodeEx("Child 1", base_flags)) + { + ImGui::Button("Button for Child 1"); + ImGui::TreePop(); + } + if (ImGui::TreeNodeEx("Child 2", base_flags)) + { + ImGui::Button("Button for Child 2"); + ImGui::TreePop(); + } + ImGui::Text("Remaining contents"); + ImGui::Text("Remaining contents"); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + HelpMarker( + "This is a more typical looking tree with selectable nodes.\n" + "Click to select, Ctrl+Click to toggle, click on arrows or double-click to open."); + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; + static bool align_label_with_current_x_position = false; + static bool test_drag_and_drop = false; + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &base_flags, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_FramePadding", &base_flags, ImGuiTreeNodeFlags_FramePadding); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); + + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + + ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); + ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + // 'selection_mask' is dumb representation of what may be user-side selection state. + // You may retain selection state inside or outside your objects in whatever format you see fit. + // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end + /// of the loop. May be a pointer to your own node type, etc. + static int selection_mask = (1 << 2); + int node_clicked = -1; + for (int i = 0; i < 6; i++) + { + // Disable the default "open on single-click behavior" + set Selected flag according to our selection. + // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection. + ImGuiTreeNodeFlags node_flags = base_flags; + const bool is_selected = (selection_mask & (1 << i)) != 0; + if (is_selected) + node_flags |= ImGuiTreeNodeFlags_Selected; + if (i < 3) + { + // Items 0..2 are Tree Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanLabelWidth)) + { + // Item 2 has an additional inline button to help demonstrate SpanLabelWidth. + ImGui::SameLine(); + if (ImGui::SmallButton("button")) {} + } + if (node_open) + { + ImGui::BulletText("Blah blah\nBlah Blah"); + ImGui::SameLine(); + ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + } + else + { + // Items 3..5 are Tree Leaves + // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + } + } + if (node_clicked != -1) + { + // Update selection state + // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // Ctrl+Click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsVerticalSliders() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgetsVerticalSliders() +{ + IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); + if (ImGui::TreeNode("Vertical Sliders")) + { + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx * rows + ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgets() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Widgets"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (!ImGui::CollapsingHeader("Widgets")) + return; + + const bool disable_all = demo_data->DisableSections; // The Checkbox for that is inside the "Disabled" section at the bottom + if (disable_all) + ImGui::BeginDisabled(); + + DemoWindowWidgetsBasic(); + DemoWindowWidgetsBullets(); + DemoWindowWidgetsCollapsingHeaders(); + DemoWindowWidgetsComboBoxes(); + DemoWindowWidgetsColorAndPickers(); + DemoWindowWidgetsDataTypes(); + + if (disable_all) + ImGui::EndDisabled(); + DemoWindowWidgetsDisableBlocks(demo_data); + if (disable_all) + ImGui::BeginDisabled(); + + DemoWindowWidgetsDragAndDrop(); + DemoWindowWidgetsDragsAndSliders(); + DemoWindowWidgetsFonts(); + DemoWindowWidgetsImages(); + DemoWindowWidgetsListBoxes(); + DemoWindowWidgetsMultiComponents(); + DemoWindowWidgetsPlotting(); + DemoWindowWidgetsProgressBars(); + DemoWindowWidgetsQueryingStatuses(); + DemoWindowWidgetsSelectables(); + DemoWindowWidgetsSelectionAndMultiSelect(demo_data); + DemoWindowWidgetsTabs(); + DemoWindowWidgetsText(); + DemoWindowWidgetsTextFilter(); + DemoWindowWidgetsTextInput(); + DemoWindowWidgetsTooltips(); + DemoWindowWidgetsTreeNodes(); + DemoWindowWidgetsVerticalSliders(); + + if (disable_all) + ImGui::EndDisabled(); +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowLayout() +//----------------------------------------------------------------------------- + +static void DemoWindowLayout() +{ + IMGUI_DEMO_MARKER("Layout"); + if (!ImGui::CollapsingHeader("Layout & Scrolling")) + return; + + IMGUI_DEMO_MARKER("Layout/Child windows"); + if (ImGui::TreeNode("Child windows")) + { + ImGui::SeparatorText("Child windows"); + + HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); + static bool disable_mouse_wheel = false; + static bool disable_menu = false; + ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); + ImGui::Checkbox("Disable Menu", &disable_menu); + + // Child 1: no border, enable horizontal scrollbar + { + ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), ImGuiChildFlags_None, window_flags); + for (int i = 0; i < 100; i++) + ImGui::Text("%04d: scrollable region", i); + ImGui::EndChild(); + } + + ImGui::SameLine(); + + // Child 2: rounded border + { + ImGuiWindowFlags window_flags = ImGuiWindowFlags_None; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + if (!disable_menu) + window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); + ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags); + if (!disable_menu && ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + if (ImGui::BeginTable("split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings)) + { + for (int i = 0; i < 100; i++) + { + char buf[32]; + sprintf(buf, "%03d", i); + ImGui::TableNextColumn(); + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + ImGui::EndTable(); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + } + + // Child 3: manual-resize + ImGui::SeparatorText("Manual-resize"); + { + HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents."); + //if (ImGui::Button("Set Height to 200")) + // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f)); + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); + if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) + for (int n = 0; n < 10; n++) + ImGui::Text("Line %04d", n); + ImGui::PopStyleColor(); + ImGui::EndChild(); + } + + // Child 4: auto-resizing height with a limit + ImGui::SeparatorText("Auto-resize with constraints"); + { + static int draw_lines = 3; + static int max_height_in_lines = 10; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("Lines Count", &draw_lines, 0.2f); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f); + + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 1), ImVec2(FLT_MAX, ImGui::GetTextLineHeightWithSpacing() * max_height_in_lines)); + if (ImGui::BeginChild("ConstrainedChild", ImVec2(-FLT_MIN, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) + for (int n = 0; n < draw_lines; n++) + ImGui::Text("Line %04d", n); + ImGui::EndChild(); + } + + ImGui::SeparatorText("Misc/Advanced"); + + // Demonstrate a few extra things + // - Changing ImGuiCol_ChildBg (which is transparent black in default styles) + // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + // You can also call SetNextWindowPos() to position the child window. The parent window will effectively + // layout from this position. + // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from + // the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details. + { + static int offset_x = 0; + static bool override_bg_color = true; + static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); + ImGui::Checkbox("Override ChildBg color", &override_bg_color); + ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders); + ImGui::CheckboxFlags("ImGuiChildFlags_AlwaysUseWindowPadding", &child_flags, ImGuiChildFlags_AlwaysUseWindowPadding); + ImGui::CheckboxFlags("ImGuiChildFlags_ResizeX", &child_flags, ImGuiChildFlags_ResizeX); + ImGui::CheckboxFlags("ImGuiChildFlags_ResizeY", &child_flags, ImGuiChildFlags_ResizeY); + ImGui::CheckboxFlags("ImGuiChildFlags_FrameStyle", &child_flags, ImGuiChildFlags_FrameStyle); + ImGui::SameLine(); HelpMarker("Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding."); + if (child_flags & ImGuiChildFlags_FrameStyle) + override_bg_color = false; + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); + if (override_bg_color) + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); + ImGui::BeginChild("Red", ImVec2(200, 100), child_flags, ImGuiWindowFlags_None); + if (override_bg_color) + ImGui::PopStyleColor(); + + for (int n = 0; n < 50; n++) + ImGui::Text("Some test %d", n); + ImGui::EndChild(); + bool child_is_hovered = ImGui::IsItemHovered(); + ImVec2 child_rect_min = ImGui::GetItemRectMin(); + ImVec2 child_rect_max = ImGui::GetItemRectMax(); + ImGui::Text("Hovered: %d", child_is_hovered); + ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Widgets Width"); + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + static bool show_indented_items = true; + ImGui::Checkbox("Show indented items", &show_indented_items); + + // Use SetNextItemWidth() to set the width of a single upcoming item. + // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + // In real code use you'll probably want to choose width values that are proportional to your font size + // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + + ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); + ImGui::SameLine(); HelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1b", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##1b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##2a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##2b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)"); + ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##3a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##3b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus half"); + ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##4a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##4b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))"); + ImGui::PushItemWidth(-IM_MIN(ImGui::GetFontSize() * 12, ImGui::GetContentRegionAvail().x * 0.40f)); + ImGui::DragFloat("float##5a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##5b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + // Demonstrate using PushItemWidth to surround three items. + // Calling SetNextItemWidth() before each of them would have the same effect. + ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); + ImGui::SameLine(); HelpMarker("Align to right edge"); + ImGui::PushItemWidth(-FLT_MIN); + ImGui::DragFloat("##float6a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##6b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout"); + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); + + // Text + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine"); + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor"); + + // Button + ImGui::AlignTextToFramePadding(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (with offset)"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (more)"); + static bool c1 = false, c2 = false, c3 = false, c4 = false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f; + ImGui::PushItemWidth(ImGui::CalcTextSize("AAAAAAA").x); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_COUNTOF(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f); + + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_COUNTOF(items)); + ImGui::PopID(); + //ImGui::SetItemTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy"); + ImVec2 button_sz(40, 40); + ImGui::Button("A", button_sz); ImGui::SameLine(); + ImGui::Dummy(button_sz); ImGui::SameLine(); + ImGui::Button("B", button_sz); + + // Manually wrapping + // (we should eventually provide this as an automatic layout feature, but for now you can do it manually) + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping"); + ImGui::Text("Manual wrapping:"); + ImGuiStyle& style = ImGui::GetStyle(); + int buttons_count = 20; + float window_visible_x2 = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x; + for (int n = 0; n < buttons_count; n++) + { + ImGui::PushID(n); + ImGui::Button("Box", button_sz); + float last_button_x2 = ImGui::GetItemRectMax().x; + float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line + if (n + 1 < buttons_count && next_button_x2 < window_visible_x2) + ImGui::SameLine(); + ImGui::PopID(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Groups"); + if (ImGui::TreeNode("Groups")) + { + HelpMarker( + "BeginGroup() basically locks the horizontal position for new line. " + "EndGroup() bundles the whole group so that you can use \"item\" functions such as " + "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group."); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + ImGui::SetItemTooltip("First group hovered"); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_COUNTOF(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + if (ImGui::BeginListBox("List", size)) + { + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Text Baseline Alignment"); + if (ImGui::TreeNode("Text Baseline Alignment")) + { + { + ImGui::BulletText("Text baseline:"); + ImGui::SameLine(); HelpMarker( + "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. " + "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets."); + ImGui::Indent(); + + ImGui::Text("KO Blahblah"); ImGui::SameLine(); + ImGui::Button("Some framed item"); ImGui::SameLine(); + HelpMarker("Baseline of button will look misaligned with text.."); + + // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + // (because we don't know what's coming after the Text() statement, we need to move the text baseline + // down by FramePadding.y ahead of time) + ImGui::AlignTextToFramePadding(); + ImGui::Text("OK Blahblah"); ImGui::SameLine(); + ImGui::Button("Some framed item##2"); ImGui::SameLine(); + HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y"); + + // SmallButton() uses the same vertical padding as Text + ImGui::Button("TEST##1"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST##2"); + + // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + ImGui::AlignTextToFramePadding(); + ImGui::Text("Text aligned to framed item"); ImGui::SameLine(); + ImGui::Button("Item##1"); ImGui::SameLine(); + ImGui::Text("Item"); ImGui::SameLine(); + ImGui::SmallButton("Item##2"); ImGui::SameLine(); + ImGui::Button("Item##3"); + + ImGui::Unindent(); + } + + ImGui::Spacing(); + + { + ImGui::BulletText("Multi-line text:"); + ImGui::Indent(); + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP##1"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP##2"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + ImGui::Unindent(); + } + + ImGui::Spacing(); + + { + ImGui::BulletText("Misc items:"); + ImGui::Indent(); + + // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. + ImGui::Button("80x80", ImVec2(80, 80)); + ImGui::SameLine(); + ImGui::Button("50x50", ImVec2(50, 50)); + ImGui::SameLine(); + ImGui::Button("Button()"); + ImGui::SameLine(); + ImGui::SmallButton("SmallButton()"); + + // Tree + // (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags_DrawLinesNone to disable hierarchy outline) + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); // Will make line higher + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNodeEx("Node##1", ImGuiTreeNodeFlags_DrawLinesNone)) + { + // Placeholder tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } + + const float padding = (float)(int)(ImGui::GetFontSize() * 1.20f); // Large padding + ImGui::PushStyleVarY(ImGuiStyleVar_FramePadding, padding); + ImGui::Button("Button##2"); + ImGui::PopStyleVar(); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNodeEx("Node##2", ImGuiTreeNodeFlags_DrawLinesNone)) + ImGui::TreePop(); + + // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + // Otherwise you can use SmallButton() (smaller fit). + ImGui::AlignTextToFramePadding(); + + // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + // other contents "inside" the node. + bool node_open = ImGui::TreeNode("Node##3"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##3"); + if (node_open) + { + // Placeholder tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } + + // Bullet + ImGui::Button("Button##4"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignTextToFramePadding(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##5"); + ImGui::Unindent(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Scrolling"); + if (ImGui::TreeNode("Scrolling")) + { + // Vertical scroll functions + IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical"); + HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position."); + + static int track_item = 50; + static bool enable_track = true; + static bool enable_extra_decorations = false; + static float scroll_to_off_px = 0.0f; + static float scroll_to_pos_px = 200.0f; + + ImGui::Checkbox("Decoration", &enable_extra_decorations); + + ImGui::PushItemWidth(ImGui::GetFontSize() * 10); + enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); + ImGui::SameLine(); + ImGui::Checkbox("Track", &enable_track); + + bool scroll_to_off = ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px"); + ImGui::SameLine(); + scroll_to_off |= ImGui::Button("Scroll Offset"); + + bool scroll_to_pos = ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px"); + ImGui::SameLine(); + scroll_to_pos |= ImGui::Button("Scroll To Pos"); + ImGui::PopItemWidth(); + + if (scroll_to_off || scroll_to_pos) + enable_track = false; + + ImGuiStyle& style = ImGui::GetStyle(); + float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; + if (child_w < 1.0f) + child_w = 1.0f; + ImGui::PushID("##VerticalScrolling"); + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; + ImGui::TextUnformatted(names[i]); + + const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; + const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), ImGuiChildFlags_Borders, child_flags); + if (ImGui::BeginMenuBar()) + { + ImGui::TextUnformatted("abc"); + ImGui::EndMenuBar(); + } + if (scroll_to_off) + ImGui::SetScrollY(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items + { + for (int item = 0; item < 100; item++) + { + if (enable_track && item == track_item) + { + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); + ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Item %d", item); + } + } + } + float scroll_y = ImGui::GetScrollY(); + float scroll_max_y = ImGui::GetScrollMaxY(); + ImGui::EndChild(); + ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y); + ImGui::EndGroup(); + } + ImGui::PopID(); + + // Horizontal scroll functions + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal"); + ImGui::Spacing(); + HelpMarker( + "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" + "Because the clipping rectangle of most window hides half worth of WindowPadding on the " + "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the " + "equivalent SetScrollFromPosY(+1) wouldn't."); + ImGui::PushID("##HorizontalScrolling"); + for (int i = 0; i < 5; i++) + { + float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; + ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); + ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), ImGuiChildFlags_Borders, child_flags); + if (scroll_to_off) + ImGui::SetScrollX(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f); + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items + { + for (int item = 0; item < 100; item++) + { + if (item > 0) + ImGui::SameLine(); + if (enable_track && item == track_item) + { + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); + ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right + } + else + { + ImGui::Text("Item %d", item); + } + } + } + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); + ImGui::EndChild(); + ImGui::SameLine(); + const char* names[] = { "Left", "25%", "Center", "75%", "Right" }; + ImGui::Text("%s\n%.0f/%.0f", names[i], scroll_x, scroll_max_x); + ImGui::Spacing(); + } + ImGui::PopID(); + + // Miscellaneous Horizontal Scrolling Demo + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal (more)"); + HelpMarker( + "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" + "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30); + ImGui::BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + // If you want to create your own time line for a real application you may be better off manipulating + // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + // yourself. You may also want to use the lower-level ImDrawList API. + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + sprintf(num_buf, "%d", n); + const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf; + float hue = n * 0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); + if (ImGui::IsItemActive()) + scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); + ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); + if (ImGui::IsItemActive()) + scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); + ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x); + if (scroll_x_delta != 0.0f) + { + // Demonstrate a trick: you can use Begin to set yourself in the context of another window + // (here we are already out of your child window) + ImGui::BeginChild("scrolling"); + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::EndChild(); + } + ImGui::Spacing(); + + static bool show_horizontal_contents_size_demo_window = false; + ImGui::Checkbox("Show Horizontal contents size demo window", &show_horizontal_contents_size_demo_window); + + if (show_horizontal_contents_size_demo_window) + { + static bool show_h_scrollbar = true; + static bool show_button = true; + static bool show_tree_nodes = true; + static bool show_text_wrapped = false; + static bool show_columns = true; + static bool show_tab_bar = true; + static bool show_child = false; + static bool explicit_content_size = false; + static float contents_size_x = 300.0f; + if (explicit_content_size) + ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f)); + ImGui::Begin("Horizontal contents size demo window", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0); + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal contents size demo window"); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0)); + HelpMarker( + "Test how different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\n" + "Use 'Metrics->Tools->Show windows rectangles' to visualize rectangles."); + ImGui::Checkbox("H-scrollbar", &show_h_scrollbar); + ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten) + ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width + ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size + ImGui::Checkbox("Columns", &show_columns); // Will use contents size + ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size + ImGui::Checkbox("Child", &show_child); // Will grow and use contents size + ImGui::Checkbox("Explicit content size", &explicit_content_size); + ImGui::Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY()); + if (explicit_content_size) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::CalcTextSize("123456").x); + ImGui::DragFloat("##csx", &contents_size_x); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE); + ImGui::Dummy(ImVec2(0, 10)); + } + ImGui::PopStyleVar(2); + ImGui::Separator(); + if (show_button) + { + ImGui::Button("this is a 300-wide button", ImVec2(300, 0)); + } + if (show_tree_nodes) + { + bool open = true; + if (ImGui::TreeNode("this is a tree node")) + { + if (ImGui::TreeNode("another one of those tree node...")) + { + ImGui::Text("Some tree contents"); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::CollapsingHeader("CollapsingHeader", &open); + } + if (show_text_wrapped) + { + ImGui::TextWrapped("This text should automatically wrap on the edge of the work rectangle."); + } + if (show_columns) + { + ImGui::Text("Tables:"); + if (ImGui::BeginTable("table", 4, ImGuiTableFlags_Borders)) + { + for (int n = 0; n < 4; n++) + { + ImGui::TableNextColumn(); + ImGui::Text("Width %.2f", ImGui::GetContentRegionAvail().x); + } + ImGui::EndTable(); + } + ImGui::Text("Columns:"); + ImGui::Columns(4); + for (int n = 0; n < 4; n++) + { + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::NextColumn(); + } + ImGui::Columns(1); + } + if (show_tab_bar && ImGui::BeginTabBar("Hello")) + { + if (ImGui::BeginTabItem("OneOneOne")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("TwoTwoTwo")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("ThreeThreeThree")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); } + ImGui::EndTabBar(); + } + if (show_child) + { + ImGui::BeginChild("child", ImVec2(0, 0), ImGuiChildFlags_Borders); + ImGui::EndChild(); + } + ImGui::End(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Text Clipping"); + if (ImGui::TreeNode("Text Clipping")) + { + static ImVec2 size(100.0f, 100.0f); + static ImVec2 offset(30.0f, 30.0f); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag to scroll)"); + + HelpMarker( + "(Left) Using ImGui::PushClipRect():\n" + "Will alter ImGui hit-testing logic + ImDrawList rendering.\n" + "(use this if you want your clipping rectangle to affect interactions)\n\n" + "(Center) Using ImDrawList::PushClipRect():\n" + "Will alter ImDrawList rendering only.\n" + "(use this as a shortcut if you are only using ImDrawList calls)\n\n" + "(Right) Using ImDrawList::AddText() with a fine ClipRect:\n" + "Will alter only this specific ImDrawList::AddText() rendering.\n" + "This is often used internally to avoid altering the clipping rectangle and minimize draw calls."); + + for (int n = 0; n < 3; n++) + { + if (n > 0) + ImGui::SameLine(); + + ImGui::PushID(n); + ImGui::InvisibleButton("##canvas", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } + ImGui::PopID(); + if (!ImGui::IsItemVisible()) // Skip rendering as ImDrawList elements are not clipped. + continue; + + const ImVec2 p0 = ImGui::GetItemRectMin(); + const ImVec2 p1 = ImGui::GetItemRectMax(); + const char* text_str = "Line 1 hello\nLine 2 clip me!"; + const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + switch (n) + { + case 0: + ImGui::PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + ImGui::PopClipRect(); + break; + case 1: + draw_list->PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + draw_list->PopClipRect(); + break; + case 2: + ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert. + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect); + break; + } + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Overlap Mode"); + if (ImGui::TreeNode("Overlap Mode")) + { + static bool enable_allow_overlap = true; + + HelpMarker( + "Hit-testing is by default performed in item submission order, which generally is perceived as 'back-to-front'.\n\n" + "By using SetNextItemAllowOverlap() you can notify that an item may be overlapped by another. " + "Doing so alters the hovering logic: items using AllowOverlap mode requires an extra frame to accept hovered state."); + ImGui::Checkbox("Enable AllowOverlap", &enable_allow_overlap); + + ImVec2 button1_pos = ImGui::GetCursorScreenPos(); + ImVec2 button2_pos = ImVec2(button1_pos.x + 50.0f, button1_pos.y + 50.0f); + if (enable_allow_overlap) + ImGui::SetNextItemAllowOverlap(); + ImGui::Button("Button 1", ImVec2(80, 80)); + ImGui::SetCursorScreenPos(button2_pos); + ImGui::Button("Button 2", ImVec2(80, 80)); + + // This is typically used with width-spanning items. + // (note that Selectable() has a dedicated flag ImGuiSelectableFlags_AllowOverlap, which is a shortcut + // for using SetNextItemAllowOverlap(). For demo purpose we use SetNextItemAllowOverlap() here.) + if (enable_allow_overlap) + ImGui::SetNextItemAllowOverlap(); + ImGui::Selectable("Some Selectable", false); + ImGui::SameLine(); + ImGui::SmallButton("++"); + + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowPopups() +//----------------------------------------------------------------------------- + +static void DemoWindowPopups() +{ + IMGUI_DEMO_MARKER("Popups"); + if (!ImGui::CollapsingHeader("Popups & Modal windows")) + return; + + // The properties of popups windows are: + // - They block normal mouse hovering detection outside them. (*) + // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + // we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even + // when normally blocked by a popup. + // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + // popups at any time. + + // Typical use for regular windows: + // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End(); + // Typical use for popups: + // if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup")) { [...] EndPopup(); } + + // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. + // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. + + IMGUI_DEMO_MARKER("Popups/Popups"); + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped( + "When a popup is active, it inhibits interacting with windows that are behind the popup. " + "Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + // Simple selection popup (if you want to show the current selection inside the Button itself, + // you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + if (ImGui::Button("Select..")) + ImGui::OpenPopup("my_select_popup"); + ImGui::SameLine(); + ImGui::TextUnformatted(selected_fish == -1 ? "" : names[selected_fish]); + if (ImGui::BeginPopup("my_select_popup")) + { + ImGui::SeparatorText("Aquarium"); + for (int i = 0; i < IM_COUNTOF(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + // Showing a menu with toggles + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("my_toggle_popup"); + if (ImGui::BeginPopup("my_toggle_popup")) + { + for (int i = 0; i < IM_COUNTOF(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + ImGui::SetItemTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_COUNTOF(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + ImGui::Text("I am the last one here."); + ImGui::EndPopup(); + } + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + // Call the more complete ShowExampleMenuFile which we use in various places of this demo + if (ImGui::Button("With a menu..")) + ImGui::OpenPopup("my_file_popup"); + if (ImGui::BeginPopup("my_file_popup", ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + ImGui::MenuItem("Dummy"); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + ImGui::Text("Hello from popup!"); + ImGui::Button("This is a dummy button.."); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Context menus"); + if (ImGui::TreeNode("Context menus")) + { + HelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier."); + + // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: + // if (id == 0) + // id = GetItemID(); // Use last item id + // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) + // OpenPopup(id); + // return BeginPopup(id); + // For advanced uses you may want to replicate and customize this code. + // See more details in BeginPopupContextItem(). + + // Example 1 + // When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(), + // and BeginPopupContextItem() will use the last item ID as the popup ID. + { + const char* names[5] = { "Label1", "Label2", "Label3", "Label4", "Label5" }; + static int selected = -1; + for (int n = 0; n < 5; n++) + { + if (ImGui::Selectable(names[n], selected == n)) + selected = n; + if (ImGui::BeginPopupContextItem()) // <-- use last item id as popup id + { + selected = n; + ImGui::Text("This is a popup for \"%s\"!", names[n]); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SetItemTooltip("Right-click to open popup"); + } + } + + // Example 2 + // Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem(). + // Using an explicit identifier is also convenient if you want to activate the popups from different locations. + { + HelpMarker("Text() elements don't have stable identifiers so we need to provide one."); + static float value = 0.5f; + ImGui::Text("Value = %.3f <-- (1) right-click this text", value); + if (ImGui::BeginPopupContextItem("my popup")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f); + ImGui::EndPopup(); + } + + // We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup. + // Here we make it that right-clicking this other text element opens the same popup as above. + // The popup itself will be submitted by the code above. + ImGui::Text("(2) Or right-click this text"); + ImGui::OpenPopupOnItemClick("my popup", ImGuiPopupFlags_MouseButtonRight); + + // Back to square one: manually open the same popup. + if (ImGui::Button("(3) Or click this button")) + ImGui::OpenPopup("my popup"); + } + + // Example 3 + // When using BeginPopupContextItem() with an implicit identifier (NULL == use last item ID), + // we need to make sure your item identifier is stable. + // In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ). + { + HelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator."); + static char name[32] = "Label1"; + char buf[64]; + sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label + ImGui::Button(buf); + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("Edit name:"); + ImGui::InputText("##edit", name, IM_COUNTOF(name)); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Modals"); + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + + // Always center this window when appearing + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!"); + ImGui::Separator(); + + //static int unused_i = 0; + //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1", NULL, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Some menu item")) {} + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDimBg] behind it."); + + // Testing behavior of widgets stacking their own regular popups over the modal. + static int item = 1; + static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + ImGui::ColorEdit4("Color", color); + + if (ImGui::Button("Add another modal..")) + ImGui::OpenPopup("Stacked 2"); + + // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which + // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + // of the bool actually doesn't matter here. + bool unused_open = true; + if (ImGui::BeginPopupModal("Stacked 2", &unused_open)) + { + ImGui::Text("Hello from Stacked The Second!"); + ImGui::ColorEdit4("Color", color); // Allow opening another nested popup + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Menus inside a regular window"); + if (ImGui::TreeNode("Menus inside a regular window")) + { + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + + ImGui::MenuItem("Menu item", "Ctrl+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::Separator(); + ImGui::TreePop(); + } +} + +// Dummy data structure that we use for the Table demo. +// (pre-C++11 doesn't allow us to instantiate ImVector template if this structure is defined inside the demo function) +namespace +{ +// We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +// This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +// But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +// If you don't use sorting, you will generally never care about giving column an ID! +enum MyItemColumnID +{ + MyItemColumnID_ID, + MyItemColumnID_Name, + MyItemColumnID_Action, + MyItemColumnID_Quantity, + MyItemColumnID_Description +}; + +struct MyItem +{ + int ID; + const char* Name; + int Quantity; + + // We have a problem which is affecting _only this demo_ and should not affect your code: + // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(), + // however qsort doesn't allow passing user data to comparing function. + // As a workaround, we are storing the sort specs in a static/global for the comparing function to access. + // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global. + // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called + // very often by the sorting algorithm it would be a little wasteful. + static const ImGuiTableSortSpecs* s_current_sort_specs; + + static void SortWithSortSpecs(ImGuiTableSortSpecs* sort_specs, MyItem* items, int items_count) + { + s_current_sort_specs = sort_specs; // Store in variable accessible by the sort function. + if (items_count > 1) + qsort(items, (size_t)items_count, sizeof(items[0]), MyItem::CompareWithSortSpecs); + s_current_sort_specs = NULL; + } + + // Compare function to be used by qsort() + static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs) + { + const MyItem* a = (const MyItem*)lhs; + const MyItem* b = (const MyItem*)rhs; + for (int n = 0; n < s_current_sort_specs->SpecsCount; n++) + { + // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler! + const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n]; + int delta = 0; + switch (sort_spec->ColumnUserID) + { + case MyItemColumnID_ID: delta = (a->ID - b->ID); break; + case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break; + case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break; + case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break; + default: IM_ASSERT(0); break; + } + if (delta > 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + if (delta < 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; + } + + // qsort() is instable so always return a way to differentiate items. + // Your own compare function may want to avoid fallback on implicit sort specs. + // e.g. a Name compare if it wasn't already part of the sort specs. + return a->ID - b->ID; + } +}; +const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; +} + +// Make the UI compact because there are so many fields +static void PushStyleCompact() +{ + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::PushStyleVarY(ImGuiStyleVar_FramePadding, (float)(int)(style.FramePadding.y * 0.60f)); + ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, (float)(int)(style.ItemSpacing.y * 0.60f)); +} + +static void PopStyleCompact() +{ + ImGui::PopStyleVar(2); +} + +// Show a combo box with a choice of sizing policies +static void EditTableSizingFlags(ImGuiTableFlags* p_flags) +{ + struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; + static const EnumDesc policies[] = + { + { ImGuiTableFlags_None, "Default", "Use default sizing policy:\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\n- ImGuiTableFlags_SizingStretchSame otherwise." }, + { ImGuiTableFlags_SizingFixedFit, "ImGuiTableFlags_SizingFixedFit", "Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width." }, + { ImGuiTableFlags_SizingFixedSame, "ImGuiTableFlags_SizingFixedSame", "Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible." }, + { ImGuiTableFlags_SizingStretchProp, "ImGuiTableFlags_SizingStretchProp", "Columns default to _WidthStretch with weights proportional to their widths." }, + { ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." } + }; + int idx; + for (idx = 0; idx < IM_COUNTOF(policies); idx++) + if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_)) + break; + const char* preview_text = (idx < IM_COUNTOF(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : ""; + if (ImGui::BeginCombo("Sizing Policy", preview_text)) + { + for (int n = 0; n < IM_COUNTOF(policies); n++) + if (ImGui::Selectable(policies[n].Name, idx == n)) + *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value; + ImGui::EndCombo(); + } + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::BeginItemTooltip()) + { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f); + for (int m = 0; m < IM_COUNTOF(policies); m++) + { + ImGui::Separator(); + ImGui::Text("%s:", policies[m].Name); + ImGui::Separator(); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetStyle().IndentSpacing * 0.5f); + ImGui::TextUnformatted(policies[m].Tooltip); + } + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +static void EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags) +{ + ImGui::CheckboxFlags("_Disabled", p_flags, ImGuiTableColumnFlags_Disabled); ImGui::SameLine(); HelpMarker("Master disable flag (also hide from context menu)"); + ImGui::CheckboxFlags("_DefaultHide", p_flags, ImGuiTableColumnFlags_DefaultHide); + ImGui::CheckboxFlags("_DefaultSort", p_flags, ImGuiTableColumnFlags_DefaultSort); + if (ImGui::CheckboxFlags("_WidthStretch", p_flags, ImGuiTableColumnFlags_WidthStretch)) + *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch); + if (ImGui::CheckboxFlags("_WidthFixed", p_flags, ImGuiTableColumnFlags_WidthFixed)) + *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed); + ImGui::CheckboxFlags("_NoResize", p_flags, ImGuiTableColumnFlags_NoResize); + ImGui::CheckboxFlags("_NoReorder", p_flags, ImGuiTableColumnFlags_NoReorder); + ImGui::CheckboxFlags("_NoHide", p_flags, ImGuiTableColumnFlags_NoHide); + ImGui::CheckboxFlags("_NoClip", p_flags, ImGuiTableColumnFlags_NoClip); + ImGui::CheckboxFlags("_NoSort", p_flags, ImGuiTableColumnFlags_NoSort); + ImGui::CheckboxFlags("_NoSortAscending", p_flags, ImGuiTableColumnFlags_NoSortAscending); + ImGui::CheckboxFlags("_NoSortDescending", p_flags, ImGuiTableColumnFlags_NoSortDescending); + ImGui::CheckboxFlags("_NoHeaderLabel", p_flags, ImGuiTableColumnFlags_NoHeaderLabel); + ImGui::CheckboxFlags("_NoHeaderWidth", p_flags, ImGuiTableColumnFlags_NoHeaderWidth); + ImGui::CheckboxFlags("_PreferSortAscending", p_flags, ImGuiTableColumnFlags_PreferSortAscending); + ImGui::CheckboxFlags("_PreferSortDescending", p_flags, ImGuiTableColumnFlags_PreferSortDescending); + ImGui::CheckboxFlags("_IndentEnable", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0"); + ImGui::CheckboxFlags("_IndentDisable", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0"); + ImGui::CheckboxFlags("_AngledHeader", p_flags, ImGuiTableColumnFlags_AngledHeader); +} + +static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags) +{ + ImGui::CheckboxFlags("_IsEnabled", &flags, ImGuiTableColumnFlags_IsEnabled); + ImGui::CheckboxFlags("_IsVisible", &flags, ImGuiTableColumnFlags_IsVisible); + ImGui::CheckboxFlags("_IsSorted", &flags, ImGuiTableColumnFlags_IsSorted); + ImGui::CheckboxFlags("_IsHovered", &flags, ImGuiTableColumnFlags_IsHovered); +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowTables() +//----------------------------------------------------------------------------- + +static void DemoWindowTables() +{ + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + IMGUI_DEMO_MARKER("Tables"); + if (!ImGui::CollapsingHeader("Tables & Columns")) + return; + + // Using those as a base value to create width/height that are factor of the size of our font + const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x; + const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing(); + + ImGui::PushID("Tables"); + + int open_action = -1; + if (ImGui::Button("Expand all")) + open_action = 1; + ImGui::SameLine(); + if (ImGui::Button("Collapse all")) + open_action = 0; + ImGui::SameLine(); + + // Options + static bool disable_indent = false; + ImGui::Checkbox("Disable tree indentation", &disable_indent); + ImGui::SameLine(); + HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width."); + ImGui::Separator(); + if (disable_indent) + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); + + // About Styling of tables + // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + // There are however a few settings that a shared and part of the ImGuiStyle structure: + // style.CellPadding // Padding within each cell + // style.Colors[ImGuiCol_TableHeaderBg] // Table header background + // style.Colors[ImGuiCol_TableBorderStrong] // Table outer and header borders + // style.Colors[ImGuiCol_TableBorderLight] // Table inner borders + // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + + // Demos + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Basic"); + if (ImGui::TreeNode("Basic")) + { + // Here we will showcase three different ways to output a table. + // They are very simple variations of a same thing! + + // [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + // In many situations, this is the most flexible and easy to use pattern. + HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop."); + if (ImGui::BeginTable("table1", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Row %d Column %d", row, column); + } + } + ImGui::EndTable(); + } + + // [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex(). + // This is generally more convenient when you have code manually submitting the contents of each column. + HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually."); + if (ImGui::BeginTable("table2", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("Row %d", row); + ImGui::TableNextColumn(); + ImGui::Text("Some contents"); + ImGui::TableNextColumn(); + ImGui::Text("123.456"); + } + ImGui::EndTable(); + } + + // [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(), + // as TableNextColumn() will automatically wrap around and create new rows as needed. + // This is generally more convenient when your cells all contains the same type of data. + HelpMarker( + "Only using TableNextColumn(), which tends to be convenient for tables where every cell contains " + "the same type of contents.\n This is also more similar to the old NextColumn() function of the " + "Columns API, and provided to facilitate the Columns->Tables API transition."); + if (ImGui::BeginTable("table3", 3)) + { + for (int item = 0; item < 14; item++) + { + ImGui::TableNextColumn(); + ImGui::Text("Item %d", item); + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Borders, background"); + if (ImGui::TreeNode("Borders, background")) + { + // Expose a few Borders related flags interactively + enum ContentsType { CT_Text, CT_FillButton }; + static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + static bool display_headers = false; + static int contents_type = CT_Text; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerH\n | ImGuiTableFlags_BordersOuterH"); + ImGui::Indent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner); + ImGui::Unindent(); + + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); + ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); + ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); + ImGui::Checkbox("Display headers", &display_headers); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + // Display headers so we can inspect their interaction with borders + // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them now. See other sections for details) + if (display_headers) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + char buf[32]; + sprintf(buf, "Hello %d,%d", column, row); + if (contents_type == CT_Text) + ImGui::TextUnformatted(buf); + else if (contents_type == CT_FillButton) + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, stretch"); + if (ImGui::TreeNode("Resizable, stretch")) + { + // By default, if we don't enable ScrollX the sizing policy for each column is "Stretch" + // All columns maintain a sizing weight, and they will occupy all available width. + static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::SameLine(); HelpMarker( + "Using the _Resizable flag automatically enables the _BordersInnerV flag as well, " + "this is why the resize borders are still showing when unchecking this."); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, fixed"); + if (ImGui::TreeNode("Resizable, fixed")) + { + // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set) + // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) + // If there is not enough available width to fit all columns, they will however be resized down. + // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings + HelpMarker( + "Using _Resizable + _SizingFixedFit flags.\n" + "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n" + "Double-click a column border to auto-fit the column to its contents."); + PushStyleCompact(); + static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody; + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, mixed"); + if (ImGui::TreeNode("Resizable, mixed")) + { + HelpMarker( + "Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n" + "When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch."); + static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + + if (ImGui::BeginTable("table1", 3, flags)) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableHeadersRow(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", column, row); + } + } + ImGui::EndTable(); + } + if (ImGui::BeginTable("table2", 6, flags)) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableHeadersRow(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 6; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Reorderable, hideable, with headers"); + if (ImGui::TreeNode("Reorderable, hideable, with headers")) + { + HelpMarker( + "Click and drag column headers to reorder columns.\n\n" + "Right-click on a header to open a context menu."); + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers)"); + ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. + // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + // Use outer_size.x == 0.0f instead of default to make the table as tight as possible + // (only valid when no scrolling and no stretch column) + if (ImGui::BeginTable("table2", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0f, 0.0f))) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Fixed %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Padding"); + if (ImGui::TreeNode("Padding")) + { + // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. + // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. + HelpMarker( + "We often want outer padding activated when any using features which makes the edges of a column visible:\n" + "e.g.:\n" + "- BorderOuterV\n" + "- any form of row selection\n" + "Because of this, activating BorderOuterV sets the default to PadOuterX. " + "Using PadOuterX or NoPadOuterX you can override the default.\n\n" + "Actual padding values are using style.CellPadding.\n\n" + "In this demo we don't show horizontal borders to emphasize how they don't affect default horizontal padding."); + + static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX); + ImGui::SameLine(); HelpMarker("Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags1, ImGuiTableFlags_NoPadOuterX); + ImGui::SameLine(); HelpMarker("Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags1, ImGuiTableFlags_NoPadInnerX); + ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)"); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV); + static bool show_headers = false; + ImGui::Checkbox("show_headers", &show_headers); + PopStyleCompact(); + + if (ImGui::BeginTable("table_padding", 3, flags1)) + { + if (show_headers) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + { + ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); + } + else + { + char buf[32]; + sprintf(buf, "Hello %d,%d", column, row); + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + //if (ImGui::TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) + // ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255)); + } + } + ImGui::EndTable(); + } + + // Second example: set style.CellPadding to (0.0) or a custom value. + // FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one... + HelpMarker("Setting style.CellPadding to (0,0) or a custom value."); + static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + static ImVec2 cell_padding(0.0f, 0.0f); + static bool show_widget_frame_bg = true; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags2, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags2, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags2, ImGuiTableFlags_BordersInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags2, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags2, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags2, ImGuiTableFlags_Resizable); + ImGui::Checkbox("show_widget_frame_bg", &show_widget_frame_bg); + ImGui::SliderFloat2("CellPadding", &cell_padding.x, 0.0f, 10.0f, "%.0f"); + PopStyleCompact(); + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding); + if (ImGui::BeginTable("table_padding_2", 3, flags2)) + { + static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells + static bool init = true; + if (!show_widget_frame_bg) + ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); + for (int cell = 0; cell < 3 * 5; cell++) + { + ImGui::TableNextColumn(); + if (init) + strcpy(text_bufs[cell], "edit me"); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushID(cell); + ImGui::InputText("##cell", text_bufs[cell], IM_COUNTOF(text_bufs[cell])); + ImGui::PopID(); + } + if (!show_widget_frame_bg) + ImGui::PopStyleColor(); + init = false; + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Explicit widths"); + if (ImGui::TreeNode("Sizing policies")) + { + static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags1, ImGuiTableFlags_NoHostExtendX); + PopStyleCompact(); + + static ImGuiTableFlags sizing_policy_flags[4] = { ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame }; + for (int table_n = 0; table_n < 4; table_n++) + { + ImGui::PushID(table_n); + ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 30); + EditTableSizingFlags(&sizing_policy_flags[table_n]); + + // To make it easier to understand the different sizing policy, + // For each policy: we display one table where the columns have equal contents width, + // and one where the columns have different contents width. + if (ImGui::BeginTable("table1", 3, sizing_policy_flags[table_n] | flags1)) + { + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + } + ImGui::EndTable(); + } + if (ImGui::BeginTable("table2", 3, sizing_policy_flags[table_n] | flags1)) + { + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); ImGui::Text("AAAA"); + ImGui::TableNextColumn(); ImGui::Text("BBBBBBBB"); + ImGui::TableNextColumn(); ImGui::Text("CCCCCCCCCCCC"); + } + ImGui::EndTable(); + } + ImGui::PopID(); + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Advanced"); + ImGui::SameLine(); + HelpMarker( + "This section allows you to interact and see the effect of various sizing policies " + "depending on whether Scroll is enabled and the contents of your columns."); + + enum ContentsType { CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText }; + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable; + static int contents_type = CT_ShowWidth; + static int column_count = 3; + + PushStyleCompact(); + ImGui::PushID("Advanced"); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30); + EditTableSizingFlags(&flags); + ImGui::Combo("Contents", &contents_type, "Show width\0Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); + if (contents_type == CT_FillButton) + { + ImGui::SameLine(); + HelpMarker( + "Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop " + "where contents width can feed into auto-column width can feed into contents width."); + } + ImGui::DragInt("Columns", &column_count, 0.1f, 1, 64, "%d", ImGuiSliderFlags_AlwaysClamp); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths); + ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth."); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip); + ImGui::PopItemWidth(); + ImGui::PopID(); + PopStyleCompact(); + + if (ImGui::BeginTable("table2", column_count, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 7))) + { + for (int cell = 0; cell < 10 * column_count; cell++) + { + ImGui::TableNextColumn(); + int column = ImGui::TableGetColumnIndex(); + int row = ImGui::TableGetRowIndex(); + + ImGui::PushID(cell); + char label[32]; + static char text_buf[32] = ""; + sprintf(label, "Hello %d,%d", column, row); + switch (contents_type) + { + case CT_ShortText: ImGui::TextUnformatted(label); break; + case CT_LongText: ImGui::Text("Some %s text %d,%d\nOver two lines..", column == 0 ? "long" : "longeeer", column, row); break; + case CT_ShowWidth: ImGui::Text("W: %.1f", ImGui::GetContentRegionAvail().x); break; + case CT_Button: ImGui::Button(label); break; + case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_COUNTOF(text_buf)); break; + } + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Vertical scrolling, with clipping"); + if (ImGui::TreeNode("Vertical scrolling, with clipping")) + { + HelpMarker( + "Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\n" + "We also demonstrate using ImGuiListClipper to virtualize the submission of many items."); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + PopStyleCompact(); + + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8); + if (ImGui::BeginTable("table_scrolly", 3, flags, outer_size)) + { + ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible + ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); + ImGui::TableHeadersRow(); + + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(1000); + while (clipper.Step()) + { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Horizontal scrolling"); + if (ImGui::TreeNode("Horizontal scrolling")) + { + HelpMarker( + "When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, " + "as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n" + "Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX, " + "because the container window won't automatically extend vertically to fix contents " + "(this may be improved in future versions)."); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + static int freeze_cols = 1; + static int freeze_rows = 1; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + PopStyleCompact(); + + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8); + if (ImGui::BeginTable("table_scrollx", 7, flags, outer_size)) + { + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); + ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze() + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableSetupColumn("Four"); + ImGui::TableSetupColumn("Five"); + ImGui::TableSetupColumn("Six"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 20; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 7; column++) + { + // Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement. + // Because here we know that: + // - A) all our columns are contributing the same to row height + // - B) column 0 is always visible, + // We only always submit this one column and can skip others. + // More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags(). + if (!ImGui::TableSetColumnIndex(column) && column > 0) + continue; + if (column == 0) + ImGui::Text("Line %d", row); + else + ImGui::Text("Hello world %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Stretch + ScrollX"); + ImGui::SameLine(); + HelpMarker( + "Showcase using Stretch columns + ScrollX together: " + "this is rather unusual and only makes sense when specifying an 'inner_width' for the table!\n" + "Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns " + "along with ScrollX doesn't make sense."); + static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody; + static float inner_width = 1000.0f; + PushStyleCompact(); + ImGui::PushID("flags3"); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags2, ImGuiTableFlags_ScrollX); + ImGui::DragFloat("inner_width", &inner_width, 1.0f, 0.0f, FLT_MAX, "%.1f"); + ImGui::PopItemWidth(); + ImGui::PopID(); + PopStyleCompact(); + if (ImGui::BeginTable("table2", 7, flags2, outer_size, inner_width)) + { + for (int cell = 0; cell < 20 * 7; cell++) + { + ImGui::TableNextColumn(); + ImGui::Text("Hello world %d,%d", ImGui::TableGetColumnIndex(), ImGui::TableGetRowIndex()); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Columns flags"); + if (ImGui::TreeNode("Columns flags")) + { + // Create a first table just to show all the options/flags we want to make visible in our example! + const int column_count = 3; + const char* column_names[column_count] = { "One", "Two", "Three" }; + static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide }; + static ImGuiTableColumnFlags column_flags_out[column_count] = { 0, 0, 0 }; // Output from TableGetColumnFlags() + + if (ImGui::BeginTable("table_columns_flags_checkboxes", column_count, ImGuiTableFlags_None)) + { + PushStyleCompact(); + for (int column = 0; column < column_count; column++) + { + ImGui::TableNextColumn(); + ImGui::PushID(column); + ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation across columns + ImGui::Text("'%s'", column_names[column]); + ImGui::Spacing(); + ImGui::Text("Input flags:"); + EditTableColumnsFlags(&column_flags[column]); + ImGui::Spacing(); + ImGui::Text("Output flags:"); + ImGui::BeginDisabled(); + ShowTableColumnsStatusFlags(column_flags_out[column]); + ImGui::EndDisabled(); + ImGui::PopID(); + } + PopStyleCompact(); + ImGui::EndTable(); + } + + // Create the real table we care about for the example! + // We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, + // otherwise in a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + // + resizing the parent window down). + const ImGuiTableFlags flags + = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV + | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable; + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 9); + if (ImGui::BeginTable("table_columns_flags", column_count, flags, outer_size)) + { + bool has_angled_header = false; + for (int column = 0; column < column_count; column++) + { + has_angled_header |= (column_flags[column] & ImGuiTableColumnFlags_AngledHeader) != 0; + ImGui::TableSetupColumn(column_names[column], column_flags[column]); + } + if (has_angled_header) + ImGui::TableAngledHeadersRow(); + ImGui::TableHeadersRow(); + for (int column = 0; column < column_count; column++) + column_flags_out[column] = ImGui::TableGetColumnFlags(column); + float indent_step = (float)((int)TEXT_BASE_WIDTH / 2); + for (int row = 0; row < 8; row++) + { + // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. + ImGui::Indent(indent_step); + ImGui::TableNextRow(); + for (int column = 0; column < column_count; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column)); + } + } + ImGui::Unindent(indent_step * 8.0f); + + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Columns widths"); + if (ImGui::TreeNode("Columns widths")) + { + HelpMarker("Using TableSetupColumn() to setup default width."); + + static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize); + PopStyleCompact(); + if (ImGui::BeginTable("table1", 3, flags1)) + { + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f + ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f + ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto + ImGui::TableHeadersRow(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); + else + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + HelpMarker( + "Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, " + "fixed columns with set width may still be shrunk down if there's not enough space in the host."); + + static ImGuiTableFlags flags2 = ImGuiTableFlags_None; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV); + PopStyleCompact(); + if (ImGui::BeginTable("table2", 4, flags2)) + { + // We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns + // will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 4; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); + else + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Nested tables"); + if (ImGui::TreeNode("Nested tables")) + { + HelpMarker("This demonstrates embedding a table into another table cell."); + + if (ImGui::BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("A0"); + ImGui::TableSetupColumn("A1"); + ImGui::TableHeadersRow(); + + ImGui::TableNextColumn(); + ImGui::Text("A0 Row 0"); + { + float rows_height = (TEXT_BASE_HEIGHT * 2.0f) + (ImGui::GetStyle().CellPadding.y * 2.0f); + if (ImGui::BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("B0"); + ImGui::TableSetupColumn("B1"); + ImGui::TableHeadersRow(); + + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); + ImGui::Text("B0 Row 0"); + ImGui::TableNextColumn(); + ImGui::Text("B1 Row 0"); + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); + ImGui::Text("B0 Row 1"); + ImGui::TableNextColumn(); + ImGui::Text("B1 Row 1"); + + ImGui::EndTable(); + } + } + ImGui::TableNextColumn(); ImGui::Text("A1 Row 0"); + ImGui::TableNextColumn(); ImGui::Text("A0 Row 1"); + ImGui::TableNextColumn(); ImGui::Text("A1 Row 1"); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Row height"); + if (ImGui::TreeNode("Row height")) + { + HelpMarker( + "You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, " + "so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\n" + "We cannot honor a _maximum_ row height as that would require a unique clipping rectangle per row."); + if (ImGui::BeginTable("table_row_height", 1, ImGuiTableFlags_Borders)) + { + for (int row = 0; row < 8; row++) + { + float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row + ImGui::GetStyle().CellPadding.y * 2.0f); + ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); + ImGui::TableNextColumn(); + ImGui::Text("min_row_height = %.2f", min_row_height); + } + ImGui::EndTable(); + } + + HelpMarker( + "Showcase using SameLine(0,0) to share Current Line Height between cells.\n\n" + "Please note that Tables Row Height is not the same thing as Current Line Height, " + "as a table cell may contains multiple lines."); + if (ImGui::BeginTable("table_share_lineheight", 2, ImGuiTableFlags_Borders)) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::ColorButton("##1", ImVec4(0.13f, 0.26f, 0.40f, 1.0f), ImGuiColorEditFlags_None, ImVec2(40, 40)); + ImGui::TableNextColumn(); + ImGui::Text("Line 1"); + ImGui::Text("Line 2"); + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::ColorButton("##2", ImVec4(0.13f, 0.26f, 0.40f, 1.0f), ImGuiColorEditFlags_None, ImVec2(40, 40)); + ImGui::TableNextColumn(); + ImGui::SameLine(0.0f, 0.0f); // Reuse line height from previous column + ImGui::Text("Line 1, with SameLine(0,0)"); + ImGui::Text("Line 2"); + + ImGui::EndTable(); + } + + HelpMarker("Showcase altering CellPadding.y between rows. Note that CellPadding.x is locked for the entire table."); + if (ImGui::BeginTable("table_changing_cellpadding_y", 1, ImGuiTableFlags_Borders)) + { + ImGuiStyle& style = ImGui::GetStyle(); + for (int row = 0; row < 8; row++) + { + if ((row % 3) == 2) + ImGui::PushStyleVarY(ImGuiStyleVar_CellPadding, 20.0f); + ImGui::TableNextRow(ImGuiTableRowFlags_None); + ImGui::TableNextColumn(); + ImGui::Text("CellPadding.y = %.2f", style.CellPadding.y); + if ((row % 3) == 2) + ImGui::PopStyleVar(); + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Outer size"); + if (ImGui::TreeNode("Outer size")) + { + // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY + // Important to that note how the two flags have slightly different behaviors! + ImGui::Text("Using NoHostExtendX and NoHostExtendY:"); + PushStyleCompact(); + static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX; + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY); + ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible."); + PopStyleCompact(); + + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 5.5f); + if (ImGui::BeginTable("table1", 3, flags, outer_size)) + { + for (int row = 0; row < 10; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::SameLine(); + ImGui::Text("Hello!"); + + ImGui::Spacing(); + + ImGui::Text("Using explicit size:"); + if (ImGui::BeginTable("table2", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f))) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::SameLine(); + if (ImGui::BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f))) + { + const float rows_height = TEXT_BASE_HEIGHT * 1.5f + ImGui::GetStyle().CellPadding.y * 2.0f; + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(0, rows_height); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Background color"); + if (ImGui::TreeNode("Background color")) + { + static ImGuiTableFlags flags = ImGuiTableFlags_RowBg; + static int row_bg_type = 1; + static int row_bg_target = 1; + static int cell_bg_type = 1; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style."); + ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0"); + ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them."); + ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here."); + IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2); + IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1); + IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 5, flags)) + { + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + + // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)' + // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. + if (row_bg_type != 0) + { + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); + } + + // Fill cells + for (int column = 0; column < 5; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%c%c", 'A' + row, '0' + column); + + // Change background of Cells B1->C2 + // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)' + // (the CellBg color will be blended over the RowBg and ColumnBg colors) + // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. + if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1) + { + ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f)); + ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Tree view"); + if (ImGui::TreeNode("Tree view")) + { + static ImGuiTableFlags table_flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; + + static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_DrawLinesFull; + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanLabelWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanAllColumns); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_LabelSpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_LabelSpanAllColumns); + ImGui::SameLine(); HelpMarker("Useful if you know that you aren't displaying contents in other columns"); + + HelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns."); + if (ImGui::BeginTable("3ways", 3, table_flags)) + { + // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); + ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f); + ImGui::TableHeadersRow(); + + // Simple storage to output a dummy file-system. + struct MyTreeNode + { + const char* Name; + const char* Type; + int Size; + int ChildIdx; + int ChildCount; + static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + const bool is_folder = (node->ChildCount > 0); + + ImGuiTreeNodeFlags node_flags = tree_node_flags_base; + if (node != &all_nodes[0]) + node_flags &= ~ImGuiTreeNodeFlags_LabelSpanAllColumns; // Only demonstrate this on the root node. + + if (is_folder) + { + bool open = ImGui::TreeNodeEx(node->Name, node_flags); + if ((node_flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) == 0) + { + ImGui::TableNextColumn(); + ImGui::TextDisabled("--"); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(node->Type); + } + if (open) + { + for (int child_n = 0; child_n < node->ChildCount; child_n++) + DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes); + ImGui::TreePop(); + } + } + else + { + ImGui::TreeNodeEx(node->Name, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen); + ImGui::TableNextColumn(); + ImGui::Text("%d", node->Size); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(node->Type); + } + } + }; + static const MyTreeNode nodes[] = + { + { "Root with Long Name", "Folder", -1, 1, 3 }, // 0 + { "Music", "Folder", -1, 4, 2 }, // 1 + { "Textures", "Folder", -1, 6, 3 }, // 2 + { "desktop.ini", "System file", 1024, -1,-1 }, // 3 + { "File1_a.wav", "Audio file", 123000, -1,-1 }, // 4 + { "File1_b.wav", "Audio file", 456000, -1,-1 }, // 5 + { "Image001.png", "Image file", 203128, -1,-1 }, // 6 + { "Copy of Image001.png", "Image file", 203256, -1,-1 }, // 7 + { "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 }, // 8 + }; + + MyTreeNode::DisplayNode(&nodes[0], nodes); + + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Item width"); + if (ImGui::TreeNode("Item width")) + { + HelpMarker( + "Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n" + "Note that on auto-resizing non-resizable fixed columns, querying the content width for " + "e.g. right-alignment doesn't make sense."); + if (ImGui::BeginTable("table_item_width", 3, ImGuiTableFlags_Borders)) + { + ImGui::TableSetupColumn("small"); + ImGui::TableSetupColumn("half"); + ImGui::TableSetupColumn("right-align"); + ImGui::TableHeadersRow(); + + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + if (row == 0) + { + // Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient) + ImGui::TableSetColumnIndex(0); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 3.0f); // Small + ImGui::TableSetColumnIndex(1); + ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::TableSetColumnIndex(2); + ImGui::PushItemWidth(-FLT_MIN); // Right-aligned + } + + // Draw our contents + static float dummy_f = 0.0f; + ImGui::PushID(row); + ImGui::TableSetColumnIndex(0); + ImGui::SliderFloat("float0", &dummy_f, 0.0f, 1.0f); + ImGui::TableSetColumnIndex(1); + ImGui::SliderFloat("float1", &dummy_f, 0.0f, 1.0f); + ImGui::TableSetColumnIndex(2); + ImGui::SliderFloat("##float2", &dummy_f, 0.0f, 1.0f); // No visible label since right-aligned + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // Demonstrate using TableHeader() calls instead of TableHeadersRow() + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Custom headers"); + if (ImGui::TreeNode("Custom headers")) + { + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("Apricot"); + ImGui::TableSetupColumn("Banana"); + ImGui::TableSetupColumn("Cherry"); + + // Dummy entire-column selection storage + // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. + static bool column_selected[3] = {}; + + // Instead of calling TableHeadersRow() we'll submit custom headers ourselves. + // (A different approach is also possible: + // - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call. + // - Call TableHeadersRow() normally. This will submit TableHeader() with no name. + // - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().) + ImGui::TableNextRow(ImGuiTableRowFlags_Headers); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn() + ImGui::PushID(column); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::Checkbox("##checkall", &column_selected[column]); + ImGui::PopStyleVar(); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::TableHeader(column_name); + ImGui::PopID(); + } + + // Submit table contents + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + char buf[32]; + sprintf(buf, "Cell %d,%d", column, row); + ImGui::TableSetColumnIndex(column); + ImGui::Selectable(buf, column_selected[column]); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Angled headers"); + if (ImGui::TreeNode("Angled headers")) + { + const char* column_names[] = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" }; + const int columns_count = IM_COUNTOF(column_names); + const int rows_count = 12; + + static ImGuiTableFlags table_flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_HighlightHoveredColumn; + static ImGuiTableColumnFlags column_flags = ImGuiTableColumnFlags_AngledHeader | ImGuiTableColumnFlags_WidthFixed; + static bool bools[columns_count * rows_count] = {}; // Dummy storage selection storage + static int frozen_cols = 1; + static int frozen_rows = 2; + ImGui::CheckboxFlags("_ScrollX", &table_flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("_ScrollY", &table_flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("_Resizable", &table_flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("_Sortable", &table_flags, ImGuiTableFlags_Sortable); + ImGui::CheckboxFlags("_NoBordersInBody", &table_flags, ImGuiTableFlags_NoBordersInBody); + ImGui::CheckboxFlags("_HighlightHoveredColumn", &table_flags, ImGuiTableFlags_HighlightHoveredColumn); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SliderInt("Frozen columns", &frozen_cols, 0, 2); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SliderInt("Frozen rows", &frozen_rows, 0, 2); + ImGui::CheckboxFlags("Disable header contributing to column width", &column_flags, ImGuiTableColumnFlags_NoHeaderWidth); + + if (ImGui::TreeNode("Style settings")) + { + ImGui::SameLine(); + HelpMarker("Giving access to some ImGuiStyle value in this demo for convenience."); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SliderAngle("style.TableAngledHeadersAngle", &ImGui::GetStyle().TableAngledHeadersAngle, -50.0f, +50.0f); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SliderFloat2("style.TableAngledHeadersTextAlign", (float*)&ImGui::GetStyle().TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); + ImGui::TreePop(); + } + + if (ImGui::BeginTable("table_angled_headers", columns_count, table_flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 12))) + { + ImGui::TableSetupColumn(column_names[0], ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_NoReorder); + for (int n = 1; n < columns_count; n++) + ImGui::TableSetupColumn(column_names[n], column_flags); + ImGui::TableSetupScrollFreeze(frozen_cols, frozen_rows); + + ImGui::TableAngledHeadersRow(); // Draw angled headers for all columns with the ImGuiTableColumnFlags_AngledHeader flag. + ImGui::TableHeadersRow(); // Draw remaining headers and allow access to context-menu and other functions. + for (int row = 0; row < rows_count; row++) + { + ImGui::PushID(row); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + ImGui::Text("Track %d", row); + for (int column = 1; column < columns_count; column++) + if (ImGui::TableSetColumnIndex(column)) + { + ImGui::PushID(column); + ImGui::Checkbox("", &bools[row * columns_count + column]); + ImGui::PopID(); + } + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // Demonstrate creating custom context menus inside columns, + // while playing it nice with context menus provided by TableHeadersRow()/TableHeader() + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Context menus"); + if (ImGui::TreeNode("Context menus")) + { + HelpMarker( + "By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\n" + "Using ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body."); + static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags1, ImGuiTableFlags_ContextMenuInBody); + PopStyleCompact(); + + // Context Menus: first example + // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("table_context_menu", COLUMNS_COUNT, flags1)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu. + ImGui::TableHeadersRow(); + + // Submit dummy contents + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + // Context Menus: second example + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [2.2] Right-click on the ".." to open a custom popup + // [2.3] Right-click in columns to open another custom popup + HelpMarker( + "Demonstrate mixing table context menu (over header), item context button (over button) " + "and custom per-column context menu (over column body)."); + ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + ImGui::TableHeadersRow(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + // Submit dummy contents + ImGui::TableSetColumnIndex(column); + ImGui::Text("Cell %d,%d", column, row); + ImGui::SameLine(); + + // [2.2] Right-click on the ".." to open a custom popup + ImGui::PushID(row * COLUMNS_COUNT + column); + ImGui::SmallButton(".."); + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + } + + // [2.3] Right-click anywhere in columns to open another custom popup + // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + // to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) + int hovered_column = -1; + for (int column = 0; column < COLUMNS_COUNT + 1; column++) + { + ImGui::PushID(column); + if (ImGui::TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered) + hovered_column = column; + if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1)) + ImGui::OpenPopup("MyPopup"); + if (ImGui::BeginPopup("MyPopup")) + { + if (column == COLUMNS_COUNT) + ImGui::Text("This is a custom popup for unused space after the last column."); + else + ImGui::Text("This is a custom popup for Column %d", column); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + + ImGui::EndTable(); + ImGui::Text("Hovered column: %d", hovered_column); + } + ImGui::TreePop(); + } + + // Demonstrate creating multiple tables with the same ID + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Synced instances"); + if (ImGui::TreeNode("Synced instances")) + { + HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc."); + + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings; + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("ImGuiTableFlags_SizingFixedFit", &flags, ImGuiTableFlags_SizingFixedFit); + ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn); + for (int n = 0; n < 3; n++) + { + char buf[32]; + sprintf(buf, "Synced Table %d", n); + bool open = ImGui::CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen); + if (open && ImGui::BeginTable("Table", 3, flags, ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 5))) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + const int cell_count = (n == 1) ? 27 : 9; // Make second table have a scrollbar to verify that additional decoration is not affecting column positions. + for (int cell = 0; cell < cell_count; cell++) + { + ImGui::TableNextColumn(); + ImGui::Text("this cell %d", cell); + } + ImGui::EndTable(); + } + } + ImGui::TreePop(); + } + + // Demonstrate using Sorting facilities + // This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. + // Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) + static const char* template_items_names[] = + { + "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", + "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" + }; + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Sorting"); + if (ImGui::TreeNode("Sorting")) + { + // Create item list + static ImVector items; + if (items.Size == 0) + { + items.resize(50, MyItem()); + for (int n = 0; n < items.Size; n++) + { + const int template_n = n % IM_COUNTOF(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (n * n - n) % 20; // Assign default quantities + } + } + + // Options + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody + | ImGuiTableFlags_ScrollY; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti); + ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1)."); + ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate); + ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0)."); + PopStyleCompact(); + + if (ImGui::BeginTable("table_sorting", 4, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 15), 0.0f)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + // Demonstrate using a mixture of flags among available sort-related flags: + // - ImGuiTableColumnFlags_DefaultSort + // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Quantity); + ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible + ImGui::TableHeadersRow(); + + // Sort our data if sort specs have been changed! + if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) + if (sort_specs->SpecsDirty) + { + MyItem::SortWithSortSpecs(sort_specs, items.Data, items.Size); + sort_specs->SpecsDirty = false; + } + + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) + { + // Display a data item + MyItem* item = &items[row_n]; + ImGui::PushID(item->ID); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("%04d", item->ID); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(item->Name); + ImGui::TableNextColumn(); + ImGui::SmallButton("None"); + ImGui::TableNextColumn(); + ImGui::Text("%d", item->Quantity); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // In this example we'll expose most table flags and settings. + // For specific flags and settings refer to the corresponding section for more detailed explanation. + // This section is mostly useful to experiment with combining certain flags or settings with each others. + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG] + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Advanced"); + if (ImGui::TreeNode("Advanced")) + { + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable + | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti + | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody + | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY + | ImGuiTableFlags_SizingFixedFit; + static ImGuiTableColumnFlags columns_base_flags = ImGuiTableColumnFlags_None; + + enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow }; + static int contents_type = CT_SelectableSpanRow; + const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" }; + static int freeze_cols = 1; + static int freeze_rows = 1; + static int items_count = IM_COUNTOF(template_items_names) * 2; + static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12); + static float row_min_height = 0.0f; // Auto + static float inner_width_with_scroll = 0.0f; // Auto-extend + static bool outer_size_enabled = true; + static bool show_headers = true; + static bool show_wrapped_text = false; + //static ImGuiTextFilter filter; + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affect column sizing + if (ImGui::TreeNode("Options")) + { + // Make the UI compact because there are so many fields + PushStyleCompact(); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f); + + if (ImGui::TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", &flags, ImGuiTableFlags_Sortable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", &flags, ImGuiTableFlags_NoSavedSettings); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags, ImGuiTableFlags_ContextMenuInBody); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Decorations:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers)"); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Sizing:", ImGuiTreeNodeFlags_DefaultOpen)) + { + EditTableSizingFlags(&flags); + ImGui::SameLine(); HelpMarker("In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY); + ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); + ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths); + ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip); + ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options."); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Padding:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags, ImGuiTableFlags_NoPadOuterX); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags, ImGuiTableFlags_NoPadInnerX); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Sorting:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti); + ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1)."); + ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate); + ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0)."); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Headers:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::Checkbox("show_headers", &show_headers); + ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn); + ImGui::CheckboxFlags("ImGuiTableColumnFlags_AngledHeader", &columns_base_flags, ImGuiTableColumnFlags_AngledHeader); + ImGui::SameLine(); HelpMarker("Enable AngledHeader on all columns. Best enabled on selected narrow columns (see \"Angled headers\" section of the demo)."); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); + + ImGui::DragFloat2("##OuterSize", &outer_size_value.x); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Checkbox("outer_size", &outer_size_enabled); + ImGui::SameLine(); + HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set):\n" + "- The table is output directly in the parent window.\n" + "- OuterSize.x < 0.0f will right-align the table.\n" + "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch columns.\n" + "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set)."); + + // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + // To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled. + ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); + + ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); + ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); + + ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999); + ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_COUNTOF(contents_type_names)); + //filter.Draw("filter"); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); + PopStyleCompact(); + ImGui::Spacing(); + ImGui::TreePop(); + } + + // Update item list if we changed the number of items + static ImVector items; + static ImVector selection; + static bool items_need_sort = false; + if (items.Size != items_count) + { + items.resize(items_count, MyItem()); + for (int n = 0; n < items_count; n++) + { + const int template_n = n % IM_COUNTOF(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities + } + } + + const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList(); + const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size; + ImVec2 table_scroll_cur, table_scroll_max; // For debug display + const ImDrawList* table_draw_list = NULL; // " + + // Submit table + const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f; + if (ImGui::BeginTable("table_advanced", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + ImGui::TableSetupColumn("ID", columns_base_flags | ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", columns_base_flags | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", columns_base_flags | ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity", columns_base_flags | ImGuiTableColumnFlags_PreferSortDescending, 0.0f, MyItemColumnID_Quantity); + ImGui::TableSetupColumn("Description", columns_base_flags | ((flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch), 0.0f, MyItemColumnID_Description); + ImGui::TableSetupColumn("Hidden", columns_base_flags | ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort); + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); + + // Sort our data if sort specs have been changed! + ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs(); + if (sort_specs && sort_specs->SpecsDirty) + items_need_sort = true; + if (sort_specs && items_need_sort && items.Size > 1) + { + MyItem::SortWithSortSpecs(sort_specs, items.Data, items.Size); + sort_specs->SpecsDirty = false; + } + items_need_sort = false; + + // Take note of whether we are currently sorting based on the Quantity field, + // we will use this to trigger sorting when we know the data of this column has been modified. + const bool sorts_specs_using_quantity = (ImGui::TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) != 0; + + // Show headers + if (show_headers && (columns_base_flags & ImGuiTableColumnFlags_AngledHeader) != 0) + ImGui::TableAngledHeadersRow(); + if (show_headers) + ImGui::TableHeadersRow(); + + // Show data + // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? +#if 1 + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + { + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) +#else + // Without clipper + { + for (int row_n = 0; row_n < items.Size; row_n++) +#endif + { + MyItem* item = &items[row_n]; + //if (!filter.PassFilter(item->Name)) + // continue; + + const bool item_is_selected = selection.contains(item->ID); + ImGui::PushID(item->ID); + ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height); + + // For the demo purpose we can select among different type of items submitted in the first column + ImGui::TableSetColumnIndex(0); + char label[32]; + sprintf(label, "%04d", item->ID); + if (contents_type == CT_Text) + ImGui::TextUnformatted(label); + else if (contents_type == CT_Button) + ImGui::Button(label); + else if (contents_type == CT_SmallButton) + ImGui::SmallButton(label); + else if (contents_type == CT_FillButton) + ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); + else if (contents_type == CT_Selectable || contents_type == CT_SelectableSpanRow) + { + ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap : ImGuiSelectableFlags_None; + if (ImGui::Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height))) + { + if (ImGui::GetIO().KeyCtrl) + { + if (item_is_selected) + selection.find_erase_unsorted(item->ID); + else + selection.push_back(item->ID); + } + else + { + selection.clear(); + selection.push_back(item->ID); + } + } + } + + if (ImGui::TableSetColumnIndex(1)) + ImGui::TextUnformatted(item->Name); + + // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + // and we are currently sorting on the column showing the Quantity. + // To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + // You will probably need some extra logic if you want to automatically sort when a specific entry changes. + if (ImGui::TableSetColumnIndex(2)) + { + if (ImGui::SmallButton("Chop")) { item->Quantity += 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + ImGui::SameLine(); + if (ImGui::SmallButton("Eat")) { item->Quantity -= 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + } + + if (ImGui::TableSetColumnIndex(3)) + ImGui::Text("%d", item->Quantity); + + ImGui::TableSetColumnIndex(4); + if (show_wrapped_text) + ImGui::TextWrapped("Lorem ipsum dolor sit amet"); + else + ImGui::Text("Lorem ipsum dolor sit amet"); + + if (ImGui::TableSetColumnIndex(5)) + ImGui::Text("1234"); + + ImGui::PopID(); + } + } + + // Store some info to display debug details below + table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); + table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY()); + table_draw_list = ImGui::GetWindowDrawList(); + ImGui::EndTable(); + } + static bool show_debug_details = false; + ImGui::Checkbox("Debug details", &show_debug_details); + if (show_debug_details && table_draw_list) + { + ImGui::SameLine(0.0f, 0.0f); + const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size; + if (table_draw_list == parent_draw_list) + ImGui::Text(": DrawCmd: +%d (in same window)", + table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count); + else + ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)", + table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y); + } + ImGui::TreePop(); + } + + ImGui::PopID(); + + DemoWindowColumns(); + + if (disable_indent) + ImGui::PopStyleVar(); +} + +// Demonstrate old/legacy Columns API! +// [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] +static void DemoWindowColumns() +{ + IMGUI_DEMO_MARKER("Columns (legacy API)"); + bool open = ImGui::TreeNode("Legacy Columns API"); + ImGui::SameLine(); + HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!"); + if (!open) + return; + + // Basic columns + IMGUI_DEMO_MARKER("Columns (legacy API)/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGui::Text("Without border:"); + ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border + ImGui::Separator(); + for (int n = 0; n < 14; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + if (ImGui::Selectable(label)) {} + //if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::Text("With border:"); + ImGui::Columns(4, "mycolumns"); // 4-ways, with border + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Hovered"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + bool hovered = ImGui::IsItemHovered(); + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("%d", hovered); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Borders"); + if (ImGui::TreeNode("Borders")) + { + // NB: Future columns API should allow automatic horizontal borders. + static bool h_borders = true; + static bool v_borders = true; + static int columns_count = 4; + const int lines_count = 3; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("##columns_count", &columns_count, 0.1f, 2, 10, "%d columns"); + if (columns_count < 2) + columns_count = 2; + ImGui::SameLine(); + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(columns_count, NULL, v_borders); + for (int i = 0; i < columns_count * lines_count; i++) + { + if (h_borders && ImGui::GetColumnIndex() == 0) + ImGui::Separator(); + ImGui::PushID(i); + ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i); + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); + ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); + ImGui::Text("Long text that is likely to clip"); + ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f)); + ImGui::PopID(); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) + ImGui::Separator(); + ImGui::TreePop(); + } + + // Create multiple items in a same cell before switching to next column + IMGUI_DEMO_MARKER("Columns (legacy API)/Mixed items"); + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, "%.3f"); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, "%.3f"); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + IMGUI_DEMO_MARKER("Columns (legacy API)/Word-wrapping"); + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Horizontal Scrolling"); + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); + ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f); + ImGui::BeginChild("##ScrollingRegion", child_size, ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar); + ImGui::Columns(10); + + // Also demonstrate using clipper for large vertical lists + int ITEMS_COUNT = 2000; + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + while (clipper.Step()) + { + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + for (int j = 0; j < 10; j++) + { + ImGui::Text("Line %d Column %d...", i, j); + ImGui::NextColumn(); + } + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Tree"); + if (ImGui::TreeNode("Tree")) + { + ImGui::Columns(2, "tree", true); + for (int x = 0; x < 3; x++) + { + bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + ImGui::NextColumn(); + if (open1) + { + for (int y = 0; y < 3; y++) + { + bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + if (open2) + { + ImGui::Text("Even more contents"); + if (ImGui::TreeNode("Tree in column")) + { + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::TreePop(); + } + } + ImGui::NextColumn(); + if (open2) + ImGui::TreePop(); + } + ImGui::TreePop(); + } + } + ImGui::Columns(1); + ImGui::TreePop(); + } + + ImGui::TreePop(); +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowInputs() +//----------------------------------------------------------------------------- + +static void DemoWindowInputs() +{ + IMGUI_DEMO_MARKER("Inputs & Focus"); + if (ImGui::CollapsingHeader("Inputs & Focus")) + { + ImGuiIO& io = ImGui::GetIO(); + + // Display inputs submitted to ImGuiIO + IMGUI_DEMO_MARKER("Inputs & Focus/Inputs"); + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + bool inputs_opened = ImGui::TreeNode("Inputs"); + ImGui::SameLine(); + HelpMarker( + "This is a simplified view. See more detailed input state:\n" + "- in 'Tools->Metrics/Debugger->Inputs'.\n" + "- in 'Tools->Debug Log->IO'."); + if (inputs_opened) + { + if (ImGui::IsMousePosValid()) + ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y); + else + ImGui::Text("Mouse pos: "); + ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); + ImGui::Text("Mouse down:"); + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); + ImGui::Text("Mouse clicked count:"); + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) if (io.MouseClickedCount[i] > 0) { ImGui::SameLine(); ImGui::Text("b%d: %d", i, io.MouseClickedCount[i]); } + + // We iterate both legacy native range and named ImGuiKey ranges. This is a little unusual/odd but this allows + // displaying the data for old/new backends. + // User code should never have to go through such hoops! + // You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END. + struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } }; + ImGuiKey start_key = ImGuiKey_NamedKey_BEGIN; + ImGui::Text("Keys down:"); for (ImGuiKey key = start_key; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !ImGui::IsKeyDown(key)) continue; ImGui::SameLine(); ImGui::Text((key < ImGuiKey_NamedKey_BEGIN) ? "\"%s\"" : "\"%s\" %d", ImGui::GetKeyName(key), key); } + ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. + + ImGui::TreePop(); + } + + // Display ImGuiIO output flags + IMGUI_DEMO_MARKER("Inputs & Focus/Outputs"); + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + bool outputs_opened = ImGui::TreeNode("Outputs"); + ImGui::SameLine(); + HelpMarker( + "The value of io.WantCaptureMouse and io.WantCaptureKeyboard are normally set by Dear ImGui " + "to instruct your application of how to route inputs. Typically, when a value is true, it means " + "Dear ImGui wants the corresponding inputs and we expect the underlying application to ignore them.\n\n" + "The most typical case is: when hovering a window, Dear ImGui set io.WantCaptureMouse to true, " + "and underlying application should ignore mouse inputs (in practice there are many and more subtle " + "rules leading to how those flags are set)."); + if (outputs_opened) + { + ImGui::Text("io.WantCaptureMouse: %d", io.WantCaptureMouse); + ImGui::Text("io.WantCaptureMouseUnlessPopupClose: %d", io.WantCaptureMouseUnlessPopupClose); + ImGui::Text("io.WantCaptureKeyboard: %d", io.WantCaptureKeyboard); + ImGui::Text("io.WantTextInput: %d", io.WantTextInput); + ImGui::Text("io.WantSetMousePos: %d", io.WantSetMousePos); + ImGui::Text("io.NavActive: %d, io.NavVisible: %d", io.NavActive, io.NavVisible); + + IMGUI_DEMO_MARKER("Inputs & Focus/Outputs/WantCapture override"); + if (ImGui::TreeNode("WantCapture override")) + { + HelpMarker( + "Hovering the colored canvas will override io.WantCaptureXXX fields.\n" + "Notice how normally (when set to none), the value of io.WantCaptureKeyboard would be false when hovering " + "and true when clicking."); + static int capture_override_mouse = -1; + static int capture_override_keyboard = -1; + const char* capture_override_desc[] = { "None", "Set to false", "Set to true" }; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); + ImGui::SliderInt("SetNextFrameWantCaptureMouse() on hover", &capture_override_mouse, -1, +1, capture_override_desc[capture_override_mouse + 1], ImGuiSliderFlags_AlwaysClamp); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); + ImGui::SliderInt("SetNextFrameWantCaptureKeyboard() on hover", &capture_override_keyboard, -1, +1, capture_override_desc[capture_override_keyboard + 1], ImGuiSliderFlags_AlwaysClamp); + + ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(128.0f, 96.0f)); // Dummy item + if (ImGui::IsItemHovered() && capture_override_mouse != -1) + ImGui::SetNextFrameWantCaptureMouse(capture_override_mouse == 1); + if (ImGui::IsItemHovered() && capture_override_keyboard != -1) + ImGui::SetNextFrameWantCaptureKeyboard(capture_override_keyboard == 1); + + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + // Demonstrate using Shortcut() and Routing Policies. + // The general flow is: + // - Code interested in a chord (e.g. "Ctrl+A") declares their intent. + // - Multiple locations may be interested in same chord! Routing helps find a winner. + // - Every frame, we resolve all claims and assign one owner if the modifiers are matching. + // - The lower-level function is 'bool SetShortcutRouting()', returns true when caller got the route. + // - Most of the times, SetShortcutRouting() is not called directly. User mostly calls Shortcut() with routing flags. + // - If you call Shortcut() WITHOUT any routing option, it uses ImGuiInputFlags_RouteFocused. + // TL;DR: Most uses will simply be: + // - Shortcut(ImGuiMod_Ctrl | ImGuiKey_A); // Use ImGuiInputFlags_RouteFocused policy. + IMGUI_DEMO_MARKER("Inputs & Focus/Shortcuts"); + if (ImGui::TreeNode("Shortcuts")) + { + static ImGuiInputFlags route_options = ImGuiInputFlags_Repeat; + static ImGuiInputFlags route_type = ImGuiInputFlags_RouteFocused; + ImGui::CheckboxFlags("ImGuiInputFlags_Repeat", &route_options, ImGuiInputFlags_Repeat); + ImGui::RadioButton("ImGuiInputFlags_RouteActive", &route_type, ImGuiInputFlags_RouteActive); + ImGui::RadioButton("ImGuiInputFlags_RouteFocused (default)", &route_type, ImGuiInputFlags_RouteFocused); + ImGui::RadioButton("ImGuiInputFlags_RouteGlobal", &route_type, ImGuiInputFlags_RouteGlobal); + ImGui::Indent(); + ImGui::BeginDisabled(route_type != ImGuiInputFlags_RouteGlobal); + ImGui::CheckboxFlags("ImGuiInputFlags_RouteOverFocused", &route_options, ImGuiInputFlags_RouteOverFocused); + ImGui::CheckboxFlags("ImGuiInputFlags_RouteOverActive", &route_options, ImGuiInputFlags_RouteOverActive); + ImGui::CheckboxFlags("ImGuiInputFlags_RouteUnlessBgFocused", &route_options, ImGuiInputFlags_RouteUnlessBgFocused); + ImGui::EndDisabled(); + ImGui::Unindent(); + ImGui::RadioButton("ImGuiInputFlags_RouteAlways", &route_type, ImGuiInputFlags_RouteAlways); + ImGuiInputFlags flags = route_type | route_options; // Merged flags + if (route_type != ImGuiInputFlags_RouteGlobal) + flags &= ~(ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused); + + ImGui::SeparatorText("Using SetNextItemShortcut()"); + ImGui::Text("Ctrl+S"); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_S, flags | ImGuiInputFlags_Tooltip); + ImGui::Button("Save"); + ImGui::Text("Alt+F"); + ImGui::SetNextItemShortcut(ImGuiMod_Alt | ImGuiKey_F, flags | ImGuiInputFlags_Tooltip); + static float f = 0.5f; + ImGui::SliderFloat("Factor", &f, 0.0f, 1.0f); + + ImGui::SeparatorText("Using Shortcut()"); + const float line_height = ImGui::GetTextLineHeightWithSpacing(); + const ImGuiKeyChord key_chord = ImGuiMod_Ctrl | ImGuiKey_A; + + ImGui::Text("Ctrl+A"); + ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(1.0f, 0.0f, 1.0f, 0.1f)); + + ImGui::BeginChild("WindowA", ImVec2(-FLT_MIN, line_height * 14), true); + ImGui::Text("Press Ctrl+A and see who receives it!"); + ImGui::Separator(); + + // 1: Window polling for Ctrl+A + ImGui::Text("(in WindowA)"); + ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); + + // 2: InputText also polling for Ctrl+A: it always uses _RouteFocused internally (gets priority when active) + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) + //char str[16] = "Press Ctrl+A"; + //ImGui::Spacing(); + //ImGui::InputText("InputTextB", str, IM_COUNTOF(str), ImGuiInputTextFlags_ReadOnly); + //ImGuiID item_id = ImGui::GetItemID(); + //ImGui::SameLine(); HelpMarker("Internal widgets always use _RouteFocused"); + //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, item_id) ? "PRESSED" : "..."); + + // 3: Dummy child is not claiming the route: focusing them shouldn't steal route away from WindowA + ImGui::BeginChild("ChildD", ImVec2(-FLT_MIN, line_height * 4), true); + ImGui::Text("(in ChildD: not using same Shortcut)"); + ImGui::Text("IsWindowFocused: %d", ImGui::IsWindowFocused()); + ImGui::EndChild(); + + // 4: Child window polling for Ctrl+A. It is deeper than WindowA and gets priority when focused. + ImGui::BeginChild("ChildE", ImVec2(-FLT_MIN, line_height * 4), true); + ImGui::Text("(in ChildE: using same Shortcut)"); + ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); + ImGui::EndChild(); + + // 5: In a popup + if (ImGui::Button("Open Popup")) + ImGui::OpenPopup("PopupF"); + if (ImGui::BeginPopup("PopupF")) + { + ImGui::Text("(in PopupF)"); + ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) + //ImGui::InputText("InputTextG", str, IM_COUNTOF(str), ImGuiInputTextFlags_ReadOnly); + //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, ImGui::GetItemID()) ? "PRESSED" : "..."); + ImGui::EndPopup(); + } + ImGui::EndChild(); + ImGui::PopStyleColor(); + + ImGui::TreePop(); + } + + // Display mouse cursors + IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors"); + if (ImGui::TreeNode("Mouse Cursors")) + { + const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "Progress", "NotAllowed" }; + IM_ASSERT(IM_COUNTOF(mouse_cursors_names) == ImGuiMouseCursor_COUNT); + + ImGuiMouseCursor current = ImGui::GetMouseCursor(); + const char* cursor_name = (current >= ImGuiMouseCursor_Arrow) && (current < ImGuiMouseCursor_COUNT) ? mouse_cursors_names[current] : "N/A"; + ImGui::Text("Current mouse cursor = %d: %s", current, cursor_name); + ImGui::BeginDisabled(true); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors); + ImGui::EndDisabled(); + + ImGui::Text("Hover to see mouse cursors:"); + ImGui::SameLine(); HelpMarker( + "Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. " + "If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, " + "otherwise your backend needs to handle it."); + for (int i = 0; i < ImGuiMouseCursor_COUNT; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs & Focus/Tabbing"); + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use Tab/Shift+Tab to cycle through keyboard editable fields."); + static char buf[32] = "hello"; + ImGui::InputText("1", buf, IM_COUNTOF(buf)); + ImGui::InputText("2", buf, IM_COUNTOF(buf)); + ImGui::InputText("3", buf, IM_COUNTOF(buf)); + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); + ImGui::InputText("4 (tab skip)", buf, IM_COUNTOF(buf)); + ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); + ImGui::PopItemFlag(); + ImGui::InputText("5", buf, IM_COUNTOF(buf)); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs & Focus/Focus from code"); + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_COUNTOF(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_COUNTOF(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_COUNTOF(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); + ImGui::PopItemFlag(); + + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + + // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item + static float f3[3] = { 0.0f, 0.0f, 0.0f }; + int focus_ahead = -1; + if (ImGui::Button("Focus on X")) { focus_ahead = 0; } ImGui::SameLine(); + if (ImGui::Button("Focus on Y")) { focus_ahead = 1; } ImGui::SameLine(); + if (ImGui::Button("Focus on Z")) { focus_ahead = 2; } + if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead); + ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f); + + ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs & Focus/Dragging"); + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); + for (int button = 0; button < 3; button++) + { + ImGui::Text("IsMouseDragging(%d):", button); + ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button)); + ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f)); + ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f)); + } + + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor + + // Drag operations gets "unlocked" when the mouse has moved past a certain threshold + // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher + // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta(). + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = io.MouseDelta; + ImGui::Text("GetMouseDragDelta(0):"); + ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y); + ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y); + ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y); + ImGui::TreePop(); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] About Window / ShowAboutWindow() +// Access from Dear ImGui Demo -> Tools -> About +//----------------------------------------------------------------------------- + +void ImGui::ShowAboutWindow(bool* p_open) +{ + if (!ImGui::Begin("About Dear ImGui", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Tools/About Dear ImGui"); + ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + + ImGui::TextLinkOpenURL("Homepage", "https://github.com/ocornut/imgui"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("FAQ", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Wiki", "https://github.com/ocornut/imgui/wiki"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Extensions", "https://github.com/ocornut/imgui/wiki/Useful-Extensions"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Releases", "https://github.com/ocornut/imgui/releases"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); + + ImGui::Separator(); + ImGui::Text("(c) 2014-2026 Omar Cornut"); + ImGui::Text("Developed by Omar Cornut and all Dear ImGui contributors."); + ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::Text("If your company uses this, please consider funding the project."); + + static bool show_config_info = false; + ImGui::Checkbox("Config/Build Information", &show_config_info); + if (show_config_info) + { + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + + bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); + ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18); + ImGui::BeginChild(ImGui::GetID("cfg_infos"), child_size, ImGuiChildFlags_FrameStyle); + if (copy_to_clipboard) + { + ImGui::LogToClipboard(); + ImGui::LogText("```cpp\n"); // Back quotes will make text appears without formatting when pasting on GitHub + } + + ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + ImGui::Separator(); + ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert)); + ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGui::Text("define: IMGUI_ENABLE_TEST_ENGINE"); +#endif +#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_FILE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS"); +#endif +#ifdef IMGUI_USE_BGRA_PACKED_COLOR + ImGui::Text("define: IMGUI_USE_BGRA_PACKED_COLOR"); +#endif +#ifdef _WIN32 + ImGui::Text("define: _WIN32"); +#endif +#ifdef _WIN64 + ImGui::Text("define: _WIN64"); +#endif +#ifdef __linux__ + ImGui::Text("define: __linux__"); +#endif +#ifdef __APPLE__ + ImGui::Text("define: __APPLE__"); +#endif +#ifdef _MSC_VER + ImGui::Text("define: _MSC_VER=%d", _MSC_VER); +#endif +#ifdef _MSVC_LANG + ImGui::Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG); +#endif +#ifdef __MINGW32__ + ImGui::Text("define: __MINGW32__"); +#endif +#ifdef __MINGW64__ + ImGui::Text("define: __MINGW64__"); +#endif +#ifdef __GNUC__ + ImGui::Text("define: __GNUC__=%d", (int)__GNUC__); +#endif +#ifdef __clang_version__ + ImGui::Text("define: __clang_version__=%s", __clang_version__); +#endif +#ifdef __EMSCRIPTEN__ + ImGui::Text("define: __EMSCRIPTEN__"); + ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); +#endif +#ifdef IMGUI_HAS_VIEWPORT + ImGui::Text("define: IMGUI_HAS_VIEWPORT"); +#endif +#ifdef IMGUI_HAS_DOCK + ImGui::Text("define: IMGUI_HAS_DOCK"); +#endif +#ifdef NDEBUG + ImGui::Text("define: NDEBUG"); +#endif + + // Heuristic to detect no-op IM_ASSERT() macros + // - This is designed so people opening bug reports would convey and notice that they have disabled asserts for Dear ImGui code. + // - 16 is > strlen("((void)(_EXPR))") which we suggested in our imconfig.h template as a possible way to disable. + int assert_runs_expression = 0; + IM_ASSERT(++assert_runs_expression); + int assert_expand_len = (int)strlen(IM_STRINGIFY((IM_ASSERT(true)))); + bool assert_maybe_disabled = (!assert_runs_expression || assert_expand_len <= 16); + ImGui::Text("IM_ASSERT: runs expression: %s. expand size: %s%s", + assert_runs_expression ? "OK" : "KO", (assert_expand_len > 16) ? "OK" : "KO", assert_maybe_disabled ? " (MAYBE DISABLED?!)" : ""); + if (assert_maybe_disabled) + { + ImGui::SameLine(); + HelpMarker("IM_ASSERT() calls assert() by default. Compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes!"); + } + + ImGui::Separator(); + ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); + ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL"); + ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange"); + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) ImGui::Text(" NoKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ImGui::Text(" DockingEnable"); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui::Text(" ViewportsEnable"); + if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); + if (io.ConfigDpiScaleFonts) ImGui::Text("io.ConfigDpiScaleFonts"); + if (io.ConfigDpiScaleViewports) ImGui::Text("io.ConfigDpiScaleViewports"); + if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); + if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); + if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); + if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent"); + if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit"); + if (io.ConfigDockingNoDockingOver) ImGui::Text("io.ConfigDockingNoDockingOver"); + if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); + if (io.ConfigDockingAlwaysTabBar) ImGui::Text("io.ConfigDockingAlwaysTabBar"); + if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload"); + if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); + if (io.ConfigNavMoveSetMousePos) ImGui::Text("io.ConfigNavMoveSetMousePos"); + if (io.ConfigNavCaptureKeyboard) ImGui::Text("io.ConfigNavCaptureKeyboard"); + if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); + if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); + if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); + if (io.ConfigMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigMemoryCompactTimer = %.1f", io.ConfigMemoryCompactTimer); + ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); + if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); + if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); + if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) ImGui::Text(" PlatformHasViewports"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)ImGui::Text(" HasMouseHoveredViewport"); + if (io.BackendFlags & ImGuiBackendFlags_HasParentViewport) ImGui::Text(" HasParentViewport"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) ImGui::Text(" RendererHasTextures"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasViewports) ImGui::Text(" RendererHasViewports"); + ImGui::Separator(); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexData->Width, io.Fonts->TexData->Height); + ImGui::Text("io.Fonts->FontLoaderName: %s", io.Fonts->FontLoaderName ? io.Fonts->FontLoaderName : "NULL"); + ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); + ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + ImGui::Separator(); + ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); + ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); + ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y); + ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding); + ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize); + ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y); + ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y); + + if (copy_to_clipboard) + { + ImGui::LogText("\n```\n"); + ImGui::LogFinish(); + } + ImGui::EndChild(); + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Style Editor / ShowStyleEditor() +//----------------------------------------------------------------------------- +// - ShowStyleSelector() +// - ShowStyleEditor() +//----------------------------------------------------------------------------- + +// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. +bool ImGui::ShowStyleSelector(const char* label) +{ + // FIXME: This is a bit tricky to get right as style are functions, they don't register a name nor the fact that one is active. + // So we keep track of last active one among our limited selection. + static int style_idx = -1; + const char* style_names[] = { "Dark", "Light", "Classic" }; + bool ret = false; + if (ImGui::BeginCombo(label, (style_idx >= 0 && style_idx < IM_COUNTOF(style_names)) ? style_names[style_idx] : "")) + { + for (int n = 0; n < IM_COUNTOF(style_names); n++) + { + if (ImGui::Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags_SelectOnNav)) + { + style_idx = n; + ret = true; + switch (style_idx) + { + case 0: ImGui::StyleColorsDark(); break; + case 1: ImGui::StyleColorsLight(); break; + case 2: ImGui::StyleColorsClassic(); break; + } + } + else if (style_idx == n) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + return ret; +} + +static const char* GetTreeLinesFlagsName(ImGuiTreeNodeFlags flags) +{ + if (flags == ImGuiTreeNodeFlags_DrawLinesNone) return "DrawLinesNone"; + if (flags == ImGuiTreeNodeFlags_DrawLinesFull) return "DrawLinesFull"; + if (flags == ImGuiTreeNodeFlags_DrawLinesToNodes) return "DrawLinesToNodes"; + return ""; +} + +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + IMGUI_DEMO_MARKER("Tools/Style Editor"); + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + // (without a reference style pointer, we will use one compared locally as a reference) + ImGuiStyle& style = GetStyle(); + static ImGuiStyle ref_saved_style; + + // Default to using internal storage as reference + static bool init = true; + if (init && ref == NULL) + ref_saved_style = style; + init = false; + if (ref == NULL) + ref = &ref_saved_style; + + PushItemWidth(GetWindowWidth() * 0.50f); + + { + // General + SeparatorText("General"); + if ((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } + + if (ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + ShowFontSelector("Fonts##Selector"); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + //BeginDisabled(GetIO().ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); + + // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) + if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) + style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding + { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + } + + // Save/Revert button + if (Button("Save Ref")) + *ref = ref_saved_style = style; + SameLine(); + if (Button("Revert Ref")) + style = *ref; + SameLine(); + HelpMarker( + "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); + + SeparatorText("Details"); + if (BeginTabBar("##tabs", ImGuiTabBarFlags_None)) + { + if (BeginTabItem("Sizes")) + { + SeparatorText("Main"); + SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + + SeparatorText("Borders"); + SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + + SeparatorText("Rounding"); + SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + + SeparatorText("Scrollbar"); + SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ScrollbarPadding", &style.ScrollbarPadding, 0.0f, 10.0f, "%.0f"); + + SeparatorText("Tabs"); + SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); + SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); + DragFloat("TabMinWidthBase", &style.TabMinWidthBase, 0.5f, 1.0f, 500.0f, "%.0f"); + DragFloat("TabMinWidthShrink", &style.TabMinWidthShrink, 0.5f, 1.0f, 500.0f, "%0.f"); + DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); + DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); + SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); + + SeparatorText("Tables"); + SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); + SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); + SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); + + SeparatorText("Trees"); + bool combo_open = BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags)); + SameLine(); + HelpMarker("[Experimental] Tree lines may not work in all situations (e.g. using a clipper) and may incurs slight traversal overhead.\n\nImGuiTreeNodeFlags_DrawLinesFull is faster than ImGuiTreeNodeFlags_DrawLinesToNode."); + if (combo_open) + { + const ImGuiTreeNodeFlags options[] = { ImGuiTreeNodeFlags_DrawLinesNone, ImGuiTreeNodeFlags_DrawLinesFull, ImGuiTreeNodeFlags_DrawLinesToNodes }; + for (ImGuiTreeNodeFlags option : options) + if (Selectable(GetTreeLinesFlagsName(option), style.TreeLinesFlags == option)) + style.TreeLinesFlags = option; + EndCombo(); + } + SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); + + SeparatorText("Windows"); + SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); + int window_menu_button_position = style.WindowMenuButtonPosition + 1; + if (Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) + style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); + + SeparatorText("Widgets"); + SliderFloat("ColorMarkerSize", &style.ColorMarkerSize, 0.0f, 8.0f, "%.0f"); + Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); + SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); + SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); + SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f"); + SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); + SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); + + SeparatorText("Docking"); + //SetCursorPosX(GetCursorPosX() + CalcItemWidth() - GetFrameHeight()); + Checkbox("DockingNodeHasCloseButton", &style.DockingNodeHasCloseButton); + SliderFloat("DockingSeparatorSize", &style.DockingSeparatorSize, 0.0f, 12.0f, "%.0f"); + + SeparatorText("Tooltips"); + for (int n = 0; n < 2; n++) + if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) + { + ImGuiHoveredFlags* p = (n == 0) ? &style.HoverFlagsForTooltipMouse : &style.HoverFlagsForTooltipNav; + CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone); + CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort); + CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal); + CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary); + CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay); + TreePop(); + } + + SeparatorText("Misc"); + SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen."); + SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); + + EndTabItem(); + } + + if (BeginTabItem("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = true; + if (Button("Export")) + { + if (output_dest == 0) + LogToClipboard(); + else + LogToTTY(); + LogText("ImVec4* colors = GetStyle().Colors;" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = GetStyleColorName(i); + if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) + LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, + name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + LogFinish(); + } + SameLine(); SetNextItemWidth(GetFontSize() * 10); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + SameLine(); Checkbox("Only Modified Colors", &output_only_modified); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", GetFontSize() * 16); + + static ImGuiColorEditFlags alpha_flags = 0; + if (RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } SameLine(); + if (RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } SameLine(); + if (RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } SameLine(); + HelpMarker( + "In the color list:\n" + "Left-click on color square to open color picker,\n" + "Right-click to open edit options menu."); + + SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); + BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + PushItemWidth(GetFontSize() * -12); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; + PushID(i); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (Button("?")) + DebugFlashStyleColor((ImGuiCol)i); + SetItemTooltip("Flash given color to identify places where it is used."); + SameLine(); +#endif + ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); + if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) + { + // Tips: in a real user application, you may want to merge and use an icon font into the main font, + // so instead of "Save"/"Revert" you'd use icons! + // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Save")) { ref->Colors[i] = style.Colors[i]; } + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Revert")) { style.Colors[i] = ref->Colors[i]; } + } + SameLine(0.0f, style.ItemInnerSpacing.x); + TextUnformatted(name); + PopID(); + } + PopItemWidth(); + EndChild(); + + EndTabItem(); + } + + if (BeginTabItem("Fonts")) + { + ImGuiIO& io = GetIO(); + ImFontAtlas* atlas = io.Fonts; + ShowFontAtlas(atlas); + + // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. + // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows Ctrl+Click text to get out of bounds). + /* + SeparatorText("Legacy Scaling"); + const float MIN_SCALE = 0.3f; + const float MAX_SCALE = 2.0f; + HelpMarker( + "Those are old settings provided for convenience.\n" + "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " + "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" + "Using those settings here will give you poor quality results."); + PushItemWidth(GetFontSize() * 8); + DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything + //static float window_scale = 1.0f; + //if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window + // SetWindowFontScale(window_scale); + PopItemWidth(); + */ + + EndTabItem(); + } + + if (BeginTabItem("Rendering")) + { + Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + SameLine(); + HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + + Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); + SameLine(); + HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); + + Checkbox("Anti-aliased fill", &style.AntiAliasedFill); + PushItemWidth(GetFontSize() * 8); + DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); + if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; + + // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. + DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); + const bool show_samples = IsItemActive(); + if (show_samples) + SetNextWindowPos(GetCursorScreenPos()); + if (show_samples && BeginTooltip()) + { + TextUnformatted("(R = radius, N = approx number of segments)"); + Spacing(); + ImDrawList* draw_list = GetWindowDrawList(); + const float min_widget_width = CalcTextSize("R: MMM\nN: MMM").x; + for (int n = 0; n < 8; n++) + { + const float RAD_MIN = 5.0f; + const float RAD_MAX = 70.0f; + const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f); + + BeginGroup(); + + // N is not always exact here due to how PathArcTo() function work internally + Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); + + const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f); + const float offset_x = floorf(canvas_width * 0.5f); + const float offset_y = floorf(RAD_MAX); + + const ImVec2 p1 = GetCursorScreenPos(); + draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + + /* + const ImVec2 p2 = GetCursorScreenPos(); + draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + */ + + EndGroup(); + SameLine(); + } + EndTooltip(); + } + SameLine(); + HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically."); + + DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); + PopItemWidth(); + + EndTabItem(); + } + + EndTabBar(); + } + PopItemWidth(); +} + +//----------------------------------------------------------------------------- +// [SECTION] User Guide / ShowUserGuide() +//----------------------------------------------------------------------------- + +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. +void ImGui::ShowUserGuide() +{ + ImGuiIO& io = GetIO(); + BulletText("Double-click on title bar to collapse window."); + BulletText( + "Click and drag on lower corner or border to resize window.\n" + "(double-click to auto fit window to its contents)"); + BulletText("Ctrl+Click on a slider or drag box to input value as text."); + BulletText("Tab/Shift+Tab to cycle through keyboard editable fields."); + BulletText("Ctrl+Tab/Ctrl+Shift+Tab to focus windows."); + if (io.FontAllowUserScaling) + BulletText("Ctrl+Mouse Wheel to zoom window contents."); + BulletText("While inputting text:\n"); + Indent(); + BulletText("Ctrl+Left/Right to word jump."); + BulletText("Ctrl+A or double-click to select all."); + BulletText("Ctrl+X/C/V to use clipboard cut/copy/paste."); + BulletText("Ctrl+Z to undo, Ctrl+Y/Ctrl+Shift+Z to redo."); + BulletText("Escape to revert."); + Unindent(); + BulletText("With keyboard navigation enabled:"); + Indent(); + BulletText("Arrow keys or Home/End/PageUp/PageDown to navigate."); + BulletText("Space to activate a widget."); + BulletText("Return to input text into a widget."); + BulletText("Escape to deactivate a widget, close popup,\nexit a child window or the menu layer, clear focus."); + BulletText("Alt to jump to the menu layer of a window."); + Unindent(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +//----------------------------------------------------------------------------- +// - ShowExampleAppMainMenuBar() +// - ShowExampleMenuFile() +//----------------------------------------------------------------------------- + +// Demonstrate creating a "main" fullscreen menu bar and populating it. +// Note the difference between BeginMainMenuBar() and BeginMenuBar(): +// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!) +// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "Ctrl+Z")) {} + if (ImGui::MenuItem("Redo", "Ctrl+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "Ctrl+X")) {} + if (ImGui::MenuItem("Copy", "Ctrl+C")) {} + if (ImGui::MenuItem("Paste", "Ctrl+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +// Note that shortcuts are currently provided for display only +// (future version will add explicit flags to BeginMenu() to request processing shortcuts) +static void ShowExampleMenuFile() +{ + IMGUI_DEMO_MARKER("Examples/Menu"); + ImGui::MenuItem("(demo menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + + ImGui::Separator(); + IMGUI_DEMO_MARKER("Examples/Menu/Options"); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), ImGuiChildFlags_Borders); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + + IMGUI_DEMO_MARKER("Examples/Menu/Colors"); + if (ImGui::BeginMenu("Colors")) + { + float sz = ImGui::GetTextLineHeight(); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColorName((ImGuiCol)i); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i)); + ImGui::Dummy(ImVec2(sz, sz)); + ImGui::SameLine(); + ImGui::MenuItem(name); + } + ImGui::EndMenu(); + } + + // Here we demonstrate appending again to the "Options" menu (which we already created above) + // Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice. + // In a real code-base using it would make senses to use this feature from very different code locations. + if (ImGui::BeginMenu("Options")) // <-- Append! + { + IMGUI_DEMO_MARKER("Examples/Menu/Append to an existing menu"); + static bool b = true; + ImGui::Checkbox("SomeOption", &b); + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + ImGui::Separator(); + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Debug Console / ShowExampleAppConsole() +//----------------------------------------------------------------------------- + +// Demonstrate creating a simple console window, with scrolling, filtering, completion and history. +// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector Items; + ImVector Commands; + ImVector History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImGuiTextFilter Filter; + bool AutoScroll; + bool ScrollToBottom; + + ExampleAppConsole() + { + IMGUI_DEMO_MARKER("Examples/Console"); + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + + // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); + AutoScroll = true; + ScrollToBottom = false; + AddLog("Welcome to Dear ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + ImGui::MemFree(History[i]); + } + + // Portable helpers + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = ImGui::MemAlloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } + static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + ImGui::MemFree(Items[i]); + Items.clear(); + } + + void AddLog(const char* fmt, ...) IM_FMTARGS(2) + { + // FIXME-OPT + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_COUNTOF(buf), fmt, args); + buf[IM_COUNTOF(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + // So e.g. IsItemHovered() will return true when hovering the title bar. + // Here we create a context menu only available from the title bar. + if (ImGui::BeginPopupContextItem()) + { + if (ImGui::MenuItem("Close Console")) + *p_open = false; + ImGui::EndPopup(); + } + + ImGui::TextWrapped( + "This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate " + "implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) { ClearLog(); } + ImGui::SameLine(); + bool copy_to_clipboard = ImGui::SmallButton("Copy"); + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + // Options menu + if (ImGui::BeginPopup("Options")) + { + ImGui::Checkbox("Auto-scroll", &AutoScroll); + ImGui::EndPopup(); + } + + // Options, Filter + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_O, ImGuiInputFlags_Tooltip); + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::Separator(); + + // Reserve enough left-over height for 1 separator + 1 input text + const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); + if (ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_HorizontalScrollbar)) + { + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. + // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + // to only process visible items. The clipper will automatically measure the height of your first item and then + // "seek" to display only items in the visible area. + // To use the clipper we can replace your standard loop: + // for (int i = 0; i < Items.Size; i++) + // With: + // ImGuiListClipper clipper; + // clipper.Begin(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // - That your items are evenly spaced (same height) + // - That you have cheap random access to your elements (you can access them given their index, + // without processing all the ones before) + // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + // We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + // or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage + // to improve this example code! + // If your items are of variable height: + // - Split them into same height items would be simpler and facilitate random-seeking into your list. + // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing + if (copy_to_clipboard) + ImGui::LogToClipboard(); + for (const char* item : Items) + { + if (!Filter.PassFilter(item)) + continue; + + // Normally you would store more information in your item than just a string. + // (e.g. make Items[] an array of structure, store color/type etc.) + ImVec4 color; + bool has_color = false; + if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; } + else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; } + if (has_color) + ImGui::PushStyleColor(ImGuiCol_Text, color); + ImGui::TextUnformatted(item); + if (has_color) + ImGui::PopStyleColor(); + } + if (copy_to_clipboard) + ImGui::LogFinish(); + + // Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + // Using a scrollbar or mouse-wheel will take away from the bottom edge. + if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())) + ImGui::SetScrollHereY(1.0f); + ScrollToBottom = false; + + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + bool reclaim_focus = false; + ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_EscapeClearsAll | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory; + if (ImGui::InputText("Input", InputBuf, IM_COUNTOF(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) + { + char* s = InputBuf; + Strtrim(s); + if (s[0]) + ExecCommand(s); + strcpy(s, ""); + reclaim_focus = true; + } + + // Auto-focus on window apparition + ImGui::SetItemDefaultFocus(); + if (reclaim_focus) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. + // This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size - 1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + ImGui::MemFree(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + int first = History.Size - 10; + for (int i = first > 0 ? first : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + + // On command input, we scroll to bottom even if AutoScroll==false + ScrollToBottom = true; + } + + // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks + static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiInputTextCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can.. + // So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c == 0 || c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : ""; + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, history_str); + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Debug Log / ShowExampleAppLog() +//----------------------------------------------------------------------------- + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls. + bool AutoScroll; // Keep scrolling if already at the bottom. + + ExampleAppLog() + { + AutoScroll = true; + Clear(); + } + + void Clear() + { + Buf.clear(); + LineOffsets.clear(); + LineOffsets.push_back(0); + } + + void AddLog(const char* fmt, ...) IM_FMTARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendfv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size + 1); + } + + void Draw(const char* title, bool* p_open = NULL) + { + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + // Options menu + if (ImGui::BeginPopup("Options")) + { + ImGui::Checkbox("Auto-scroll", &AutoScroll); + ImGui::EndPopup(); + } + + // Main window + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + bool clear = ImGui::Button("Clear"); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + + ImGui::Separator(); + + if (ImGui::BeginChild("scrolling", ImVec2(0, 0), ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar)) + { + if (clear) + Clear(); + if (copy) + ImGui::LogToClipboard(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + const char* buf = Buf.begin(); + const char* buf_end = Buf.end(); + if (Filter.IsActive()) + { + // In this example we don't use the clipper when Filter is enabled. + // This is because we don't have random access to the result of our filter. + // A real application processing logs with ten of thousands of entries may want to store the result of + // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). + for (int line_no = 0; line_no < LineOffsets.Size; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + if (Filter.PassFilter(line_start, line_end)) + ImGui::TextUnformatted(line_start, line_end); + } + } + else + { + // The simplest and easy way to display the entire buffer: + // ImGui::TextUnformatted(buf_begin, buf_end); + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + // within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + // on your side is recommended. Using ImGuiListClipper requires + // - A) random access into your data + // - B) items all being the same height, + // both of which we can handle since we have an array pointing to the beginning of each line of text. + // When using the filter (in the block of code above) we don't have random access into the data to display + // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + // it possible (and would be recommended if you want to search through tens of thousands of entries). + ImGuiListClipper clipper; + clipper.Begin(LineOffsets.Size); + while (clipper.Step()) + { + for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + ImGui::TextUnformatted(line_start, line_end); + } + } + clipper.End(); + } + ImGui::PopStyleVar(); + + // Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + // Using a scrollbar or mouse-wheel will take away from the bottom edge. + if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) + ImGui::SetScrollHereY(1.0f); + } + ImGui::EndChild(); + ImGui::End(); + } +}; + +// Demonstrate creating a simple log window with basic filtering. +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // For the demo: add a debug button _BEFORE_ the normal log window contents + // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. + // Most of the contents of the window will be added by the log.Draw() call. + ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); + ImGui::Begin("Example: Log", p_open); + IMGUI_DEMO_MARKER("Examples/Log"); + if (ImGui::SmallButton("[Debug] Add 5 entries")) + { + static int counter = 0; + const char* categories[3] = { "info", "warn", "error" }; + const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; + for (int n = 0; n < 5; n++) + { + const char* category = categories[counter % IM_COUNTOF(categories)]; + const char* word = words[counter % IM_COUNTOF(words)]; + log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", + ImGui::GetFrameCount(), category, ImGui::GetTime(), word); + counter++; + } + } + ImGui::End(); + + // Actually call in the regular Log helper (which will Begin() into the same window as we just did) + log.Draw("Example: Log", p_open); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +//----------------------------------------------------------------------------- + +// Demonstrate create a window with multiple child windows. +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Example: Simple layout", p_open, ImGuiWindowFlags_MenuBar)) + { + IMGUI_DEMO_MARKER("Examples/Simple layout"); + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close", "Ctrl+W")) { *p_open = false; } + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // Left + static int selected = 0; + { + ImGui::BeginChild("left pane", ImVec2(150, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SelectOnNav)) + selected = i; + } + ImGui::EndChild(); + } + ImGui::SameLine(); + + // Right + { + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + { + if (ImGui::BeginTabItem("Description")) + { + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Details")) + { + ImGui::Text("ID: 0123456789"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::EndChild(); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndGroup(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +//----------------------------------------------------------------------------- +// Some of the interactions are a bit lack-luster: +// - We would want pressing validating or leaving the filter to somehow restore focus. +// - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. +// - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties. +//----------------------------------------------------------------------------- + +struct ExampleAppPropertyEditor +{ + ImGuiTextFilter Filter; + ExampleTreeNode* VisibleNode = NULL; + + void Draw(ExampleTreeNode* root_node) + { + // Left side: draw tree + // - Currently using a table to benefit from RowBg feature + if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened)) + { + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); + ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + Filter.Build(); + ImGui::PopItemFlag(); + + if (ImGui::BeginTable("##bg", 1, ImGuiTableFlags_RowBg)) + { + for (ExampleTreeNode* node : root_node->Childs) + if (Filter.PassFilter(node->Name)) // Filter root node + DrawTreeNode(node); + ImGui::EndTable(); + } + } + ImGui::EndChild(); + + // Right side: draw properties + ImGui::SameLine(); + + ImGui::BeginGroup(); // Lock X position + if (ExampleTreeNode* node = VisibleNode) + { + ImGui::Text("%s", node->Name); + ImGui::TextDisabled("UID: 0x%08X", node->UID); + ImGui::Separator(); + if (ImGui::BeginTable("##properties", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) + { + // Push object ID after we entered the table, so table is shared for all objects + ImGui::PushID((int)node->UID); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger + if (node->HasData) + { + // In a typical application, the structure description would be derived from a data-driven system. + // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + // - Limits and some details are hard-coded to simplify the demo. + for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) + { + ImGui::TableNextRow(); + ImGui::PushID(field_desc.Name); + ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(field_desc.Name); + ImGui::TableNextColumn(); + void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); + switch (field_desc.DataType) + { + case ImGuiDataType_Bool: + { + IM_ASSERT(field_desc.DataCount == 1); + ImGui::Checkbox("##Editor", (bool*)field_ptr); + break; + } + case ImGuiDataType_S32: + { + int v_min = INT_MIN, v_max = INT_MAX; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); + break; + } + case ImGuiDataType_Float: + { + float v_min = 0.0f, v_max = 1.0f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); + break; + } + case ImGuiDataType_String: + { + ImGui::InputText("##Editor", reinterpret_cast(field_ptr), 28); + break; + } + } + ImGui::PopID(); + } + } + ImGui::PopID(); + ImGui::EndTable(); + } + } + ImGui::EndGroup(); + } + + void DrawTreeNode(ExampleTreeNode* node) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushID(node->UID); + ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; + tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;// Standard opening mode as we are likely to want to add selection afterwards + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_SpanFullWidth; // Span full width for easier mouse reach + tree_flags |= ImGuiTreeNodeFlags_DrawLinesToNodes; // Always draw hierarchy outlines + if (node == VisibleNode) + tree_flags |= ImGuiTreeNodeFlags_Selected; + if (node->Childs.Size == 0) + tree_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; + if (node->DataMyBool == false) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]); + bool node_open = ImGui::TreeNodeEx("", tree_flags, "%s", node->Name); + if (node->DataMyBool == false) + ImGui::PopStyleColor(); + if (ImGui::IsItemFocused()) + VisibleNode = node; + if (node_open) + { + for (ExampleTreeNode* child : node->Childs) + DrawTreeNode(child); + ImGui::TreePop(); + } + ImGui::PopID(); + } +}; + +// Demonstrate creating a simple property editor. +static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data) +{ + ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + + IMGUI_DEMO_MARKER("Examples/Property Editor"); + static ExampleAppPropertyEditor property_editor; + if (demo_data->DemoTree == NULL) + demo_data->DemoTree = ExampleTree_CreateDemoTree(); + property_editor.Draw(demo_data->DemoTree); + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Long Text / ShowExampleAppLongText() +//----------------------------------------------------------------------------- + +// Demonstrate/test rendering huge amount of text, and the incidence of clipping. +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Long text display"); + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, + "Single call to TextUnformatted()\0" + "Multiple calls to Text(), clipped\0" + "Multiple calls to Text(), not clipped (slow)\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGuiListClipper clipper; + clipper.Begin(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window which gets auto-resized according to its content. +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Auto-resizing window"); + + static int lines = 10; + ImGui::TextUnformatted( + "Window will resize every-frame to the size of its content.\n" + "Note that you probably don't want to query the window size to\n" + "output your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window with custom resize constraints. +// Note that size constraints currently don't work on a docked window (when in 'docking' branch) +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints + { + // Helper functions to demonstrate programmatic constraints + // FIXME: This doesn't take account of decoration size (e.g. title bar), library should make this easier. + // FIXME: None of the three demos works consistently when resizing from borders. + static void AspectRatio(ImGuiSizeCallbackData* data) + { + float aspect_ratio = *(float*)data->UserData; + data->DesiredSize.y = (float)(int)(data->DesiredSize.x / aspect_ratio); + } + static void Square(ImGuiSizeCallbackData* data) + { + data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); + } + static void Step(ImGuiSizeCallbackData* data) + { + float step = *(float*)data->UserData; + data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); + } + }; + + const char* test_desc[] = + { + "Between 100x100 and 500x500", + "At least 100x100", + "Resize vertical + lock current width", + "Resize horizontal + lock current height", + "Width Between 400 and 500", + "Height at least 400", + "Custom: Aspect Ratio 16:9", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + + // Options + static bool auto_resize = false; + static bool window_padding = true; + static int type = 6; // Aspect Ratio + static int display_lines = 10; + + // Submit constraint + float aspect_ratio = 16.0f / 9.0f; + float fixed_step = 100.0f; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)); // Between 100x100 and 500x500 + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Resize vertical + lock current width + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Resize horizontal + lock current height + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width Between and 400 and 500 + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)); // Height at least 400 + if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::AspectRatio, (void*)&aspect_ratio); // Aspect ratio + if (type == 7) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 8) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)&fixed_step); // Fixed Step + + // Submit window + if (!window_padding) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + const ImGuiWindowFlags window_flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; + const bool window_open = ImGui::Begin("Example: Constrained Resize", p_open, window_flags); + if (!window_padding) + ImGui::PopStyleVar(); + if (window_open) + { + IMGUI_DEMO_MARKER("Examples/Constrained Resizing window"); + if (ImGui::GetIO().KeyShift) + { + // Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture) + ImVec2 avail_size = ImGui::GetContentRegionAvail(); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::ColorButton("viewport", ImVec4(0.5f, 0.2f, 0.5f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, avail_size); + ImGui::SetCursorScreenPos(ImVec2(pos.x + 10, pos.y + 10)); + ImGui::Text("%.2f x %.2f", avail_size.x, avail_size.y); + } + else + { + ImGui::Text("(Hold Shift to display a dummy viewport)"); + if (ImGui::IsWindowDocked()) + ImGui::Text("Warning: Sizing Constraints won't work if the window is docked!"); + if (ImGui::Button("Set 200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); + if (ImGui::Button("Set 500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); + if (ImGui::Button("Set 800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + ImGui::Combo("Constraint", &type, test_desc, IM_COUNTOF(test_desc)); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); + ImGui::Checkbox("Auto-resize", &auto_resize); + ImGui::Checkbox("Window padding", &window_padding); + for (int i = 0; i < display_lines; i++) + ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, ""); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +//----------------------------------------------------------------------------- + +// Demonstrate creating a simple static window with no decoration +// + a context-menu to choose which corner of the screen to use. +static void ShowExampleAppSimpleOverlay(bool* p_open) +{ + static int location = 0; + ImGuiIO& io = ImGui::GetIO(); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; + if (location >= 0) + { + const float PAD = 10.0f; + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any! + ImVec2 work_size = viewport->WorkSize; + ImVec2 window_pos, window_pos_pivot; + window_pos.x = (location & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD); + window_pos.y = (location & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD); + window_pos_pivot.x = (location & 1) ? 1.0f : 0.0f; + window_pos_pivot.y = (location & 2) ? 1.0f : 0.0f; + ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); + ImGui::SetNextWindowViewport(viewport->ID); + window_flags |= ImGuiWindowFlags_NoMove; + } + else if (location == -2) + { + // Center window + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + window_flags |= ImGuiWindowFlags_NoMove; + } + ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background + if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) + { + IMGUI_DEMO_MARKER("Examples/Simple Overlay"); + ImGui::Text("Simple overlay\n" "(right-click to change position)"); + ImGui::Separator(); + if (ImGui::IsMousePosValid()) + ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y); + else + ImGui::Text("Mouse Position: "); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::MenuItem("Custom", NULL, location == -1)) location = -1; + if (ImGui::MenuItem("Center", NULL, location == -2)) location = -2; + if (ImGui::MenuItem("Top-left", NULL, location == 0)) location = 0; + if (ImGui::MenuItem("Top-right", NULL, location == 1)) location = 1; + if (ImGui::MenuItem("Bottom-left", NULL, location == 2)) location = 2; + if (ImGui::MenuItem("Bottom-right", NULL, location == 3)) location = 3; + if (p_open && ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndPopup(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window covering the entire screen/viewport +static void ShowExampleAppFullscreen(bool* p_open) +{ + static bool use_work_area = true; + static ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; + + // We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.) + // Based on your use case you may want one or the other. + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos); + ImGui::SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size); + + if (ImGui::Begin("Example: Fullscreen window", p_open, flags)) + { + ImGui::Checkbox("Use work area instead of main area", &use_work_area); + ImGui::SameLine(); + HelpMarker("Main Area = entire viewport,\nWork Area = entire viewport minus sections used by the main menu bars, task bars etc.\n\nEnable the main-menu bar in Examples menu to see the difference."); + + ImGui::CheckboxFlags("ImGuiWindowFlags_NoBackground", &flags, ImGuiWindowFlags_NoBackground); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoDecoration", &flags, ImGuiWindowFlags_NoDecoration); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoTitleBar", &flags, ImGuiWindowFlags_NoTitleBar); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoCollapse", &flags, ImGuiWindowFlags_NoCollapse); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoScrollbar", &flags, ImGuiWindowFlags_NoScrollbar); + ImGui::Unindent(); + + if (p_open && ImGui::Button("Close this window")) + *p_open = false; + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles() +//----------------------------------------------------------------------------- + +// Demonstrate the use of "##" and "###" in identifiers to manipulate ID generation. +// This applies to all regular items as well. +// Read FAQ section "How can I have multiple widgets with the same label?" for details. +static void ShowExampleAppWindowTitles(bool*) +{ + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + const ImVec2 base_pos = viewport->Pos; + + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + IMGUI_DEMO_MARKER("Examples/Manipulating window titles"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 200), ImGuiCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount()); + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 300), ImGuiCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +//----------------------------------------------------------------------------- + +// Add a |_| looking shape +static void PathConcaveShape(ImDrawList* draw_list, float x, float y, float sz) +{ + const ImVec2 pos_norms[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; + for (const ImVec2& p : pos_norms) + draw_list->PathLineTo(ImVec2(x + 0.5f + (int)(sz * p.x), y + 0.5f + (int)(sz * p.y))); +} + +// Demonstrate using the low-level ImDrawList to draw custom shapes. +static void ShowExampleAppCustomRendering(bool* p_open) +{ + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Custom Rendering"); + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of + // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your + // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not + // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! + + if (ImGui::BeginTabBar("##TabBar")) + { + if (ImGui::BeginTabItem("Primitives")) + { + ImGui::PushItemWidth(-ImGui::GetFontSize() * 15); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Draw gradients + // (note that those are currently exacerbating our sRGB/Linear issues) + // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. + ImGui::Text("Gradients"); + ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); + { + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient1", gradient_size); + } + { + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient2", gradient_size); + } + + // Draw a bunch of primitives + ImGui::Text("All primitives"); + static float sz = 36.0f; + static float thickness = 3.0f; + static int ngon_sides = 6; + static bool circle_segments_override = false; + static int circle_segments_override_v = 12; + static bool curve_segments_override = false; + static int curve_segments_override_v = 8; + static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f"); + ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); + ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); + ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40); + ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); + ImGui::ColorEdit4("Color", &colf.x); + + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col = ImColor(colf); + const float spacing = 10.0f; + const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; + const float rounding = sz / 5.0f; + const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; + const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; + const ImVec2 cp3[3] = { ImVec2(0.0f, sz * 0.6f), ImVec2(sz * 0.5f, -sz * 0.4f), ImVec2(sz, sz) }; // Control points for curves + const ImVec2 cp4[4] = { ImVec2(0.0f, 0.0f), ImVec2(sz * 1.3f, sz * 0.3f), ImVec2(sz - sz * 1.3f, sz - sz * 0.3f), ImVec2(sz, sz) }; + + float x = p.x + 4.0f; + float y = p.y + 4.0f; + for (int n = 0; n < 2; n++) + { + // First line uses a thickness of 1.0f, second line uses the configurable thickness + float th = (n == 0) ? 1.0f : thickness; + draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle + draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, ImDrawFlags_None, th); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle + //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, ImDrawFlags_Closed, th); x += sz + spacing; // Concave Shape + //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line + + // Path + draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f); + draw_list->PathStroke(col, ImDrawFlags_None, th); + x += sz + spacing; + + // Quadratic Bezier Curve (3 control points) + draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments); + x += sz + spacing; + + // Cubic Bezier Curve (4 control points) + draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments); + + x = p.x + 4; + y += sz + spacing; + } + + // Filled shapes + draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments); x += sz + spacing; // Circle + draw_list->AddEllipseFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), ImVec2(sz * 0.5f, sz * 0.3f), col, -0.3f, circle_segments); x += sz + spacing;// Ellipse + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle + //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) + + // Path + draw_list->PathArcTo(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, 3.141592f * -0.5f, 3.141592f); + draw_list->PathFillConvex(col); + x += sz + spacing; + + // Quadratic Bezier Curve (3 control points) + draw_list->PathLineTo(ImVec2(x + cp3[0].x, y + cp3[0].y)); + draw_list->PathBezierQuadraticCurveTo(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), curve_segments); + draw_list->PathFillConvex(col); + x += sz + spacing; + + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); + x += sz + spacing; + + ImGui::Dummy(ImVec2((sz + spacing) * 13.2f, (sz + spacing) * 3.0f)); + ImGui::PopItemWidth(); + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Canvas")) + { + static ImVector points; + static ImVec2 scrolling(0.0f, 0.0f); + static bool opt_enable_grid = true; + static bool opt_enable_context_menu = true; + static bool adding_line = false; + + ImGui::Checkbox("Enable grid", &opt_enable_grid); + ImGui::Checkbox("Enable context menu", &opt_enable_context_menu); + ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); + + // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + // To use a child window instead we could use, e.g: + // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding + // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color + // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); + // ImGui::PopStyleColor(); + // ImGui::PopStyleVar(); + // [...] + // ImGui::EndChild(); + + // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; + if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; + ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y); + + // Draw border and background color + ImGuiIO& io = ImGui::GetIO(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)); + draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)); + + // This will catch our interactions + ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight); + const bool is_hovered = ImGui::IsItemHovered(); // Hovered + const bool is_active = ImGui::IsItemActive(); // Held + const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin + const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y); + + // Add first and second point + if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (adding_line) + { + points.back() = mouse_pos_in_canvas; + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) + adding_line = false; + } + + // Pan (we use a zero mouse threshold when there's no context menu) + // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. + const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f; + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan)) + { + scrolling.x += io.MouseDelta.x; + scrolling.y += io.MouseDelta.y; + } + + // Context menu (under default mouse threshold) + ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); + if (opt_enable_context_menu && drag_delta.x == 0.0f && drag_delta.y == 0.0f) + ImGui::OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + if (ImGui::BeginPopup("context")) + { + if (adding_line) + points.resize(points.size() - 2); + adding_line = false; + if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); } + if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); } + ImGui::EndPopup(); + } + + // Draw grid + all lines in the canvas + draw_list->PushClipRect(canvas_p0, canvas_p1, true); + if (opt_enable_grid) + { + const float GRID_STEP = 64.0f; + for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40)); + for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); + } + for (int n = 0; n < points.Size; n += 2) + draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + draw_list->PopClipRect(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("BG/FG draw lists")) + { + static bool draw_bg = true; + static bool draw_fg = true; + ImGui::Checkbox("Draw in Background draw list", &draw_bg); + ImGui::SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows."); + ImGui::Checkbox("Draw in Foreground draw list", &draw_fg); + ImGui::SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows."); + ImVec2 window_pos = ImGui::GetWindowPos(); + ImVec2 window_size = ImGui::GetWindowSize(); + ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); + if (draw_bg) + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4); + if (draw_fg) + ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10); + ImGui::EndTabItem(); + } + + // Demonstrate out-of-order rendering via channels splitting + // We use functions in ImDrawList as each draw list contains a convenience splitter, + // but you can also instantiate your own ImDrawListSplitter if you need to nest them. + if (ImGui::BeginTabItem("Draw Channels")) + { + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + { + ImGui::Text("Blue shape is drawn first: appears in back"); + ImGui::Text("Red shape is drawn after: appears in front"); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + draw_list->AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)); // Blue + draw_list->AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)); // Red + ImGui::Dummy(ImVec2(75, 75)); + } + ImGui::Separator(); + { + ImGui::Text("Blue shape is drawn first, into channel 1: appears in front"); + ImGui::Text("Red shape is drawn after, into channel 0: appears in back"); + ImVec2 p1 = ImGui::GetCursorScreenPos(); + + // Create 2 channels and draw a Blue shape THEN a Red shape. + // You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. + draw_list->ChannelsSplit(2); + draw_list->ChannelsSetCurrent(1); + draw_list->AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)); // Blue + draw_list->ChannelsSetCurrent(0); + draw_list->AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)); // Red + + // Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. + // This works by copying draw indices only (vertices are not copied). + draw_list->ChannelsMerge(); + ImGui::Dummy(ImVec2(75, 75)); + ImGui::Text("After reordering, contents of channel 0 appears below channel 1."); + } + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +//----------------------------------------------------------------------------- + +struct ImGuiDemoDockspaceArgs +{ + bool IsFullscreen = true; + bool KeepWindowPadding = false; // Keep WindowPadding to help understand that DockSpace() is a widget inside the window. + ImGuiDockNodeFlags DockSpaceFlags = ImGuiDockNodeFlags_None; +}; + +// THIS IS A DEMO FOR ADVANCED USAGE OF DockSpace(). +// MOST REGULAR APPLICATIONS WANTING TO ALLOW DOCKING WINDOWS ON THE EDGE OF YOUR SCREEN CAN SIMPLY USE: +// ImGui::NewFrame(); + ImGui::DockSpaceOverViewport(); // Create a dockspace in main viewport +// OR: +// ImGui::NewFrame(); + ImGui::DockSpaceOverViewport(0, nullptr, ImGuiDockNodeFlags_PassthruCentralNode); // Create a dockspace in main viewport, where central node is transparent. +// Demonstrate using DockSpace() to create an explicit docking node within an existing window, with various options. +// Read https://github.com/ocornut/imgui/wiki/Docking for details. +// The reasons we do not use DockSpaceOverViewport() in this demo is because: +// - (1) we allow the host window to be floating/moveable instead of filling the viewport (when args->IsFullscreen == false) +// which is mostly to showcase the idea that DockSpace() may be submitted anywhere. +// Also see 'Demo->Examples->Documents' for a less abstract version of this. +// - (2) we allow the host window to have padding (when args->UsePadding == true) +// - (3) we expose variety of other flags. +static void ShowExampleAppDockSpaceAdvanced(ImGuiDemoDockspaceArgs* args, bool* p_open) +{ + ImGuiDockNodeFlags dockspace_flags = args->DockSpaceFlags; + + // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, + // because it would be confusing to have two docking targets within each others. + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDocking; + if (args->IsFullscreen) + { + // Fullscreen dockspace: practically the same as calling DockSpaceOverViewport(); + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->WorkPos); + ImGui::SetNextWindowSize(viewport->WorkSize); + ImGui::SetNextWindowViewport(viewport->ID); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; + window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; + window_flags |= ImGuiWindowFlags_NoBackground; + } + else + { + // Floating dockspace + dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; + } + + // Important: note that we proceed even if Begin() returns false (aka window is collapsed). + // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + // all active windows docked into it will lose their parent and become undocked. + // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. + if (!args->KeepWindowPadding) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::Begin("Window with a DockSpace", p_open, window_flags); + if (!args->KeepWindowPadding) + ImGui::PopStyleVar(); + + if (args->IsFullscreen) + ImGui::PopStyleVar(2); + + // Submit the DockSpace widget inside our window + // - Note that the id here is different from the one used by DockSpaceOverViewport(), so docking state won't get transfered between "Basic" and "Advanced" demos. + // - If we made the ShowExampleAppDockSpaceBasic() calculate its own ID and pass it to DockSpaceOverViewport() the ID could easily match. + ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); + ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); + + ImGui::End(); +} + +static void ShowExampleAppDockSpaceBasic(ImGuiDockNodeFlags flags) +{ + // Basic version which you can use in many apps: + // e.g: + // ImGui::DockSpaceOverViewport(); + // or: + // ImGui::DockSpaceOverViewport(0, nullptr, ImGuiDockNodeFlags_PassthruCentralNode); // Central node will be transparent + // or: + // ImGuiViewport* viewport = ImGui::GetMainViewport(); + // ImGui::DockSpaceOverViewport(0, viewport, ImGuiDockNodeFlags_None); + + ImGui::DockSpaceOverViewport(0, nullptr, flags); +} + +void ShowExampleAppDockSpace(bool* p_open) +{ + static int opt_demo_mode = 0; + static bool opt_demo_mode_changed = false; + static ImGuiDemoDockspaceArgs args; + + if (opt_demo_mode == 0) + ShowExampleAppDockSpaceBasic(args.DockSpaceFlags); + else + ShowExampleAppDockSpaceAdvanced(&args, p_open); + + // Refocus our window to minimize perceived loss of focus when changing mode (caused by the fact that each use a different window, which would not happen in a real app) + if (opt_demo_mode_changed) + ImGui::SetNextWindowFocus(); + ImGui::Begin("Examples: Dockspace", p_open, ImGuiWindowFlags_MenuBar); + opt_demo_mode_changed = false; + opt_demo_mode_changed |= ImGui::RadioButton("Basic demo mode", &opt_demo_mode, 0); + opt_demo_mode_changed |= ImGui::RadioButton("Advanced demo mode", &opt_demo_mode, 1); + + ImGui::SeparatorText("Options"); + + if ((ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) == 0) + { + ShowDockingDisabledMessage(); + } + else if (opt_demo_mode == 0) + { + args.DockSpaceFlags &= ImGuiDockNodeFlags_PassthruCentralNode; // Allowed flags + ImGui::CheckboxFlags("Flag: PassthruCentralNode", &args.DockSpaceFlags, ImGuiDockNodeFlags_PassthruCentralNode); + } + else if (opt_demo_mode == 1) + { + ImGui::Checkbox("Fullscreen", &args.IsFullscreen); + ImGui::Checkbox("Keep Window Padding", &args.KeepWindowPadding); + ImGui::SameLine(); + HelpMarker("This is mostly exposed to facilitate understanding that a DockSpace() is _inside_ a window."); + ImGui::BeginDisabled(args.IsFullscreen == false); + ImGui::CheckboxFlags("Flag: PassthruCentralNode", &args.DockSpaceFlags, ImGuiDockNodeFlags_PassthruCentralNode); + ImGui::EndDisabled(); + ImGui::CheckboxFlags("Flag: NoDockingOverCentralNode", &args.DockSpaceFlags, ImGuiDockNodeFlags_NoDockingOverCentralNode); + ImGui::CheckboxFlags("Flag: NoDockingSplit", &args.DockSpaceFlags, ImGuiDockNodeFlags_NoDockingSplit); + ImGui::CheckboxFlags("Flag: NoUndocking", &args.DockSpaceFlags, ImGuiDockNodeFlags_NoUndocking); + ImGui::CheckboxFlags("Flag: NoResize", &args.DockSpaceFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("Flag: AutoHideTabBar", &args.DockSpaceFlags, ImGuiDockNodeFlags_AutoHideTabBar); + } + + // Show demo options and help + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Help")) + { + ImGui::TextUnformatted( + "This demonstrates the use of ImGui::DockSpace() which allows you to manually\ncreate a docking node _within_ another window." "\n" + "The \"Basic\" version uses the ImGui::DockSpaceOverViewport() helper. Most applications can probably use this."); + ImGui::Separator(); + ImGui::TextUnformatted("When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n" + "- Drag from window title bar or their tab to dock/undock." "\n" + "- Drag from window menu button (upper-left button) to undock an entire node (all windows)." "\n" + "- Hold SHIFT to disable docking (if io.ConfigDockingWithShift == false, default)" "\n" + "- Hold SHIFT to enable docking (if io.ConfigDockingWithShift == true)"); + ImGui::Separator(); + ImGui::TextUnformatted("More details:"); ImGui::Bullet(); ImGui::SameLine(); ImGui::TextLinkOpenURL("Docking Wiki page", "https://github.com/ocornut/imgui/wiki/Docking"); + ImGui::BulletText("Read comments in ShowExampleAppDockSpace()"); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() +//----------------------------------------------------------------------------- + +// Simplified structure to mimic a Document model +struct MyDocument +{ + char Name[32]; // Document title + int UID; // Unique ID (necessary as we can change title) + bool Open; // Set when open (we keep an array of all available documents to simplify demo code!) + bool OpenPrev; // Copy of Open from last update. + bool Dirty; // Set when the document has been modified + ImVec4 Color; // An arbitrary variable associated to the document + + MyDocument(int uid, const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)) + { + UID = uid; + snprintf(Name, sizeof(Name), "%s", name); + Open = OpenPrev = open; + Dirty = false; + Color = color; + } + void DoOpen() { Open = true; } + void DoForceClose() { Open = false; Dirty = false; } + void DoSave() { Dirty = false; } +}; + +struct ExampleAppDocuments +{ + ImVector Documents; + ImVector CloseQueue; + MyDocument* RenamingDoc = NULL; + bool RenamingStarted = false; + + ExampleAppDocuments() + { + Documents.push_back(MyDocument(0, "Lettuce", true, ImVec4(0.4f, 0.8f, 0.4f, 1.0f))); + Documents.push_back(MyDocument(1, "Eggplant", true, ImVec4(0.8f, 0.5f, 1.0f, 1.0f))); + Documents.push_back(MyDocument(2, "Carrot", true, ImVec4(1.0f, 0.8f, 0.5f, 1.0f))); + Documents.push_back(MyDocument(3, "Tomato", false, ImVec4(1.0f, 0.3f, 0.4f, 1.0f))); + Documents.push_back(MyDocument(4, "A Rather Long Title", false, ImVec4(0.4f, 0.8f, 0.8f, 1.0f))); + Documents.push_back(MyDocument(5, "Some Document", false, ImVec4(0.8f, 0.8f, 1.0f, 1.0f))); + } + + // As we allow to change document name, we append a never-changing document ID so tabs are stable + void GetTabName(MyDocument* doc, char* out_buf, size_t out_buf_size) + { + snprintf(out_buf, out_buf_size, "%s###doc%d", doc->Name, doc->UID); + } + + // Display placeholder contents for the Document + void DisplayDocContents(MyDocument* doc) + { + ImGui::PushID(doc); + ImGui::Text("Document \"%s\"", doc->Name); + ImGui::PushStyleColor(ImGuiCol_Text, doc->Color); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); + ImGui::PopStyleColor(); + + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_R, ImGuiInputFlags_Tooltip); + if (ImGui::Button("Rename..")) + { + RenamingDoc = doc; + RenamingStarted = true; + } + ImGui::SameLine(); + + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_M, ImGuiInputFlags_Tooltip); + if (ImGui::Button("Modify")) + doc->Dirty = true; + + ImGui::SameLine(); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_S, ImGuiInputFlags_Tooltip); + if (ImGui::Button("Save")) + doc->DoSave(); + + ImGui::SameLine(); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_W, ImGuiInputFlags_Tooltip); + if (ImGui::Button("Close")) + CloseQueue.push_back(doc); + ImGui::ColorEdit3("color", &doc->Color.x); // Useful to test drag and drop and hold-dragged-to-open-tab behavior. + ImGui::PopID(); + } + + // Display context menu for the Document + void DisplayDocContextMenu(MyDocument* doc) + { + if (!ImGui::BeginPopupContextItem()) + return; + + char buf[256]; + sprintf(buf, "Save %s", doc->Name); + if (ImGui::MenuItem(buf, "Ctrl+S", false, doc->Open)) + doc->DoSave(); + if (ImGui::MenuItem("Rename...", "Ctrl+R", false, doc->Open)) + RenamingDoc = doc; + if (ImGui::MenuItem("Close", "Ctrl+W", false, doc->Open)) + CloseQueue.push_back(doc); + ImGui::EndPopup(); + } + + // [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. + // If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, + // as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for + // the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has + // disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively + // give the impression of a flicker for one frame. + // We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. + // Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag. + void NotifyOfDocumentsClosedElsewhere() + { + for (MyDocument& doc : Documents) + { + if (!doc.Open && doc.OpenPrev) + ImGui::SetTabItemClosed(doc.Name); + doc.OpenPrev = doc.Open; + } + } +}; + +void ShowExampleAppDocuments(bool* p_open) +{ + static ExampleAppDocuments app; + + // Options + enum Target + { + Target_None, + Target_Tab, // Create documents as local tab into a local tab bar + Target_DockSpaceAndWindow // Create documents as regular windows, and create an embedded dockspace + }; + static Target opt_target = Target_Tab; + static bool opt_reorderable = true; + static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_; + + // When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + // that we emit gets docked into the same spot as the parent window ("Example: Documents"). + // This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab + // not visible, which in turn would stop submitting the "Eggplant" window. + // We avoid this problem by submitting our documents window even if our parent window is not currently visible. + // Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking. + + bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar); + if (!window_contents_visible && opt_target != Target_DockSpaceAndWindow) + { + ImGui::End(); + return; + } + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + int open_count = 0; + for (MyDocument& doc : app.Documents) + open_count += doc.Open ? 1 : 0; + + if (ImGui::BeginMenu("Open", open_count < app.Documents.Size)) + { + for (MyDocument& doc : app.Documents) + if (!doc.Open && ImGui::MenuItem(doc.Name)) + doc.DoOpen(); + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Close All Documents", NULL, false, open_count > 0)) + for (MyDocument& doc : app.Documents) + app.CloseQueue.push_back(&doc); + if (ImGui::MenuItem("Exit") && p_open) + *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // [Debug] List documents with one checkbox for each + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument& doc = app.Documents[doc_n]; + if (doc_n > 0) + ImGui::SameLine(); + ImGui::PushID(&doc); + if (ImGui::Checkbox(doc.Name, &doc.Open)) + if (!doc.Open) + doc.DoForceClose(); + ImGui::PopID(); + } + ImGui::PushItemWidth(ImGui::GetFontSize() * 12); + ImGui::Combo("Output", (int*)&opt_target, "None\0TabBar+Tabs\0DockSpace+Window\0"); + ImGui::PopItemWidth(); + bool redock_all = false; + if (opt_target == Target_Tab) { ImGui::SameLine(); ImGui::Checkbox("Reorderable Tabs", &opt_reorderable); } + if (opt_target == Target_DockSpaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); } + + ImGui::Separator(); + + // About the ImGuiWindowFlags_UnsavedDocument / ImGuiTabItemFlags_UnsavedDocument flags. + // They have multiple effects: + // - Display a dot next to the title. + // - Tab is selected when clicking the X close button. + // - Closure is not assumed (will wait for user to stop submitting the tab). + // Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + // We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty + // hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + // The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + + // Tabs + if (opt_target == Target_Tab) + { + ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); + tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline; + if (ImGui::BeginTabBar("##tabs", tab_bar_flags)) + { + if (opt_reorderable) + app.NotifyOfDocumentsClosedElsewhere(); + + // [DEBUG] Stress tests + //if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1; // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on. + //if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name); // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway.. + + // Submit Tabs + for (MyDocument& doc : app.Documents) + { + if (!doc.Open) + continue; + + // As we allow to change document name, we append a never-changing document id so tabs are stable + char doc_name_buf[64]; + app.GetTabName(&doc, doc_name_buf, sizeof(doc_name_buf)); + ImGuiTabItemFlags tab_flags = (doc.Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0); + bool visible = ImGui::BeginTabItem(doc_name_buf, &doc.Open, tab_flags); + + // Cancel attempt to close when unsaved add to save queue so we can display a popup. + if (!doc.Open && doc.Dirty) + { + doc.Open = true; + app.CloseQueue.push_back(&doc); + } + + app.DisplayDocContextMenu(&doc); + if (visible) + { + app.DisplayDocContents(&doc); + ImGui::EndTabItem(); + } + } + + ImGui::EndTabBar(); + } + } + else if (opt_target == Target_DockSpaceAndWindow) + { + if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + app.NotifyOfDocumentsClosedElsewhere(); + + // Create a DockSpace node where any window can be docked + ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); + ImGui::DockSpace(dockspace_id); + + // Create Windows + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (!doc->Open) + continue; + + ImGui::SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver); + ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0); + bool visible = ImGui::Begin(doc->Name, &doc->Open, window_flags); + + // Cancel attempt to close when unsaved add to save queue so we can display a popup. + if (!doc->Open && doc->Dirty) + { + doc->Open = true; + app.CloseQueue.push_back(doc); + } + + app.DisplayDocContextMenu(doc); + if (visible) + app.DisplayDocContents(doc); + + ImGui::End(); + } + } + else + { + ShowDockingDisabledMessage(); + } + } + + // Early out other contents + if (!window_contents_visible) + { + ImGui::End(); + return; + } + + // Display renaming UI + if (app.RenamingDoc != NULL) + { + if (app.RenamingStarted) + ImGui::OpenPopup("Rename"); + if (ImGui::BeginPopup("Rename")) + { + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 30); + if (ImGui::InputText("###Name", app.RenamingDoc->Name, IM_COUNTOF(app.RenamingDoc->Name), ImGuiInputTextFlags_EnterReturnsTrue)) + { + ImGui::CloseCurrentPopup(); + app.RenamingDoc = NULL; + } + if (app.RenamingStarted) + ImGui::SetKeyboardFocusHere(-1); + ImGui::EndPopup(); + } + else + { + app.RenamingDoc = NULL; + } + app.RenamingStarted = false; + } + + // Display closing confirmation UI + if (!app.CloseQueue.empty()) + { + int close_queue_unsaved_documents = 0; + for (int n = 0; n < app.CloseQueue.Size; n++) + if (app.CloseQueue[n]->Dirty) + close_queue_unsaved_documents++; + + if (close_queue_unsaved_documents == 0) + { + // Close documents when all are unsaved + for (int n = 0; n < app.CloseQueue.Size; n++) + app.CloseQueue[n]->DoForceClose(); + app.CloseQueue.clear(); + } + else + { + if (!ImGui::IsPopupOpen("Save?")) + ImGui::OpenPopup("Save?"); + if (ImGui::BeginPopupModal("Save?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("Save change to the following items?"); + float item_height = ImGui::GetTextLineHeightWithSpacing(); + if (ImGui::BeginChild(ImGui::GetID("frame"), ImVec2(-FLT_MIN, 6.25f * item_height), ImGuiChildFlags_FrameStyle)) + for (MyDocument* doc : app.CloseQueue) + if (doc->Dirty) + ImGui::Text("%s", doc->Name); + ImGui::EndChild(); + + ImVec2 button_size(ImGui::GetFontSize() * 7.0f, 0.0f); + if (ImGui::Button("Yes", button_size)) + { + for (MyDocument* doc : app.CloseQueue) + { + if (doc->Dirty) + doc->DoSave(); + doc->DoForceClose(); + } + app.CloseQueue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button("No", button_size)) + { + for (MyDocument* doc : app.CloseQueue) + doc->DoForceClose(); + app.CloseQueue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button("Cancel", button_size)) + { + app.CloseQueue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + } + } + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser() +//----------------------------------------------------------------------------- + +//#include "imgui_internal.h" // NavMoveRequestTryWrapping() + +struct ExampleAsset +{ + ImGuiID ID; + int Type; + + ExampleAsset(ImGuiID id, int type) { ID = id; Type = type; } + + static const ImGuiTableSortSpecs* s_current_sort_specs; + + static void SortWithSortSpecs(ImGuiTableSortSpecs* sort_specs, ExampleAsset* items, int items_count) + { + s_current_sort_specs = sort_specs; // Store in variable accessible by the sort function. + if (items_count > 1) + qsort(items, (size_t)items_count, sizeof(items[0]), ExampleAsset::CompareWithSortSpecs); + s_current_sort_specs = NULL; + } + + // Compare function to be used by qsort() + static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs) + { + const ExampleAsset* a = (const ExampleAsset*)lhs; + const ExampleAsset* b = (const ExampleAsset*)rhs; + for (int n = 0; n < s_current_sort_specs->SpecsCount; n++) + { + const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n]; + int delta = 0; + if (sort_spec->ColumnIndex == 0) + delta = ((int)a->ID - (int)b->ID); + else if (sort_spec->ColumnIndex == 1) + delta = (a->Type - b->Type); + if (delta > 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + if (delta < 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; + } + return (int)a->ID - (int)b->ID; + } +}; +const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL; + +struct ExampleAssetsBrowser +{ + // Options + bool ShowTypeOverlay = true; + bool AllowSorting = true; + bool AllowDragUnselected = false; + bool AllowBoxSelect = true; + float IconSize = 32.0f; + int IconSpacing = 10; + int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. + bool StretchSpacing = true; + + // State + ImVector Items; // Our items + ExampleSelectionWithDeletion Selection; // Our selection (ImGuiSelectionBasicStorage + helper funcs to handle deletion) + ImGuiID NextItemId = 0; // Unique identifier when creating new items + bool RequestDelete = false; // Deferred deletion request + bool RequestSort = false; // Deferred sort request + float ZoomWheelAccum = 0.0f; // Mouse wheel accumulator to handle smooth wheels better + + // Calculated sizes for layout, output of UpdateLayoutSizes(). Could be locals but our code is simpler this way. + ImVec2 LayoutItemSize; + ImVec2 LayoutItemStep; // == LayoutItemSize + LayoutItemSpacing + float LayoutItemSpacing = 0.0f; + float LayoutSelectableSpacing = 0.0f; + float LayoutOuterPadding = 0.0f; + int LayoutColumnCount = 0; + int LayoutLineCount = 0; + + // Functions + ExampleAssetsBrowser() + { + AddItems(10000); + } + void AddItems(int count) + { + if (Items.Size == 0) + NextItemId = 0; + Items.reserve(Items.Size + count); + for (int n = 0; n < count; n++, NextItemId++) + Items.push_back(ExampleAsset(NextItemId, (NextItemId % 20) < 15 ? 0 : (NextItemId % 20) < 18 ? 1 : 2)); + RequestSort = true; + } + void ClearItems() + { + Items.clear(); + Selection.Clear(); + } + + // Logic would be written in the main code BeginChild() and outputting to local variables. + // We extracted it into a function so we can call it easily from multiple places. + void UpdateLayoutSizes(float avail_width) + { + // Layout: when not stretching: allow extending into right-most spacing. + LayoutItemSpacing = (float)IconSpacing; + if (StretchSpacing == false) + avail_width += floorf(LayoutItemSpacing * 0.5f); + + // Layout: calculate number of icon per line and number of lines + LayoutItemSize = ImVec2(floorf(IconSize), floorf(IconSize)); + LayoutColumnCount = IM_MAX((int)(avail_width / (LayoutItemSize.x + LayoutItemSpacing)), 1); + LayoutLineCount = (Items.Size + LayoutColumnCount - 1) / LayoutColumnCount; + + // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer. + if (StretchSpacing && LayoutColumnCount > 1) + LayoutItemSpacing = floorf(avail_width - LayoutItemSize.x * LayoutColumnCount) / LayoutColumnCount; + + LayoutItemStep = ImVec2(LayoutItemSize.x + LayoutItemSpacing, LayoutItemSize.y + LayoutItemSpacing); + LayoutSelectableSpacing = IM_MAX(floorf(LayoutItemSpacing) - IconHitSpacing, 0.0f); + LayoutOuterPadding = floorf(LayoutItemSpacing * 0.5f); + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(IconSize * 25, IconSize * 15), ImGuiCond_FirstUseEver); + if (!ImGui::Begin(title, p_open, ImGuiWindowFlags_MenuBar)) + { + ImGui::End(); + return; + } + + // Menu bar + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Add 10000 items")) + AddItems(10000); + if (ImGui::MenuItem("Clear items")) + ClearItems(); + ImGui::Separator(); + if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) + *p_open = false; + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0)) + RequestDelete = true; + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Options")) + { + ImGui::PushItemWidth(ImGui::GetFontSize() * 10); + + ImGui::SeparatorText("Contents"); + ImGui::Checkbox("Show Type Overlay", &ShowTypeOverlay); + ImGui::Checkbox("Allow Sorting", &AllowSorting); + + ImGui::SeparatorText("Selection Behavior"); + ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected); + ImGui::Checkbox("Allow box-selection", &AllowBoxSelect); + + ImGui::SeparatorText("Layout"); + ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); + ImGui::SameLine(); HelpMarker("Use Ctrl+Wheel to zoom"); + ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); + ImGui::SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32); + ImGui::Checkbox("Stretch Spacing", &StretchSpacing); + ImGui::PopItemWidth(); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI + if (AllowSorting) + { + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) + { + ImGui::TableSetupColumn("Index"); + ImGui::TableSetupColumn("Type"); + ImGui::TableHeadersRow(); + if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) + if (sort_specs->SpecsDirty || RequestSort) + { + ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size); + sort_specs->SpecsDirty = RequestSort = false; + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + } + + ImGuiIO& io = ImGui::GetIO(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.y + LayoutItemSpacing))); + if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove)) + { + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + const float avail_width = ImGui::GetContentRegionAvail().x; + UpdateLayoutSizes(avail_width); + + // Calculate and store start position. + ImVec2 start_pos = ImGui::GetCursorScreenPos(); + start_pos = ImVec2(start_pos.x + LayoutOuterPadding, start_pos.y + LayoutOuterPadding); + ImGui::SetCursorScreenPos(start_pos); + + // Multi-select + ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid; + + // - Enable box-select (in 2D mode, so that changing box-select rectangle X1/X2 boundaries will affect clipped items) + if (AllowBoxSelect) + ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; + + // - This feature allows dragging an unselected item without selecting it (rarely used) + if (AllowDragUnselected) + ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; + + // - Enable keyboard wrapping on X axis + // (FIXME-MULTISELECT: We haven't designed/exposed a general nav wrapping api yet, so this flag is provided as a courtesy to avoid doing: + // ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); + // When we finish implementing a more general API for this, we will obsolete this flag in favor of the new system) + ms_flags |= ImGuiMultiSelectFlags_NavWrapX; + + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size, Items.Size); + + // Use custom selection adapter: store ID in selection (recommended) + Selection.UserData = this; + Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->UserData; return self->Items[idx].ID; }; + Selection.ApplyRequests(ms_io); + + const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (Selection.Size > 0)) || RequestDelete; + const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1; + RequestDelete = false; + + // Push LayoutSelectableSpacing (which is LayoutItemSpacing minus hit-spacing, if we decide to have hit gaps between items) + // Altering style ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... + // But it is necessary for two reasons: + // - Selectables uses it by default to visually fill the space between two items. + // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do). + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(LayoutSelectableSpacing, LayoutSelectableSpacing)); + + // Rendering parameters + const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) }; + const ImU32 icon_bg_color = ImGui::GetColorU32(IM_COL32(35, 35, 35, 220)); + const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f); + const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x); + + const int column_count = LayoutColumnCount; + ImGuiListClipper clipper; + clipper.Begin(LayoutLineCount, LayoutItemStep.y); + if (item_curr_idx_to_focus != -1) + clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count); // Ensure focused item line is not clipped. + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem / column_count); // Ensure RangeSrc item line is not clipped. + while (clipper.Step()) + { + for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd; line_idx++) + { + const int item_min_idx_for_current_line = line_idx * column_count; + const int item_max_idx_for_current_line = IM_MIN((line_idx + 1) * column_count, Items.Size); + for (int item_idx = item_min_idx_for_current_line; item_idx < item_max_idx_for_current_line; ++item_idx) + { + ExampleAsset* item_data = &Items[item_idx]; + ImGui::PushID((int)item_data->ID); + + // Position item + ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x, start_pos.y + line_idx * LayoutItemStep.y); + ImGui::SetCursorScreenPos(pos); + + ImGui::SetNextItemSelectionUserData(item_idx); + bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID); + bool item_is_visible = ImGui::IsRectVisible(LayoutItemSize); + ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, LayoutItemSize); + + // Update our selection state immediately (without waiting for EndMultiSelect() requests) + // because we use this to alter the color of our text/icon. + if (ImGui::IsItemToggledSelection()) + item_is_selected = !item_is_selected; + + // Focus (for after deletion) + if (item_curr_idx_to_focus == item_idx) + ImGui::SetKeyboardFocusHere(-1); + + // Drag and drop + if (ImGui::BeginDragDropSource()) + { + // Create payload with full selection OR single unselected item. + // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) + if (ImGui::GetDragDropPayload() == NULL) + { + ImVector payload_items; + void* it = NULL; + ImGuiID id = 0; + if (!item_is_selected) + payload_items.push_back(item_data->ID); + else + while (Selection.GetNextSelectedItem(&it, &id)) + payload_items.push_back(id); + ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); + } + + // Display payload content in tooltip, by extracting it from the payload data + // (we could read from selection, but it is more correct and reusable to read from payload) + const ImGuiPayload* payload = ImGui::GetDragDropPayload(); + const int payload_count = (int)payload->DataSize / (int)sizeof(ImGuiID); + ImGui::Text("%d assets", payload_count); + + ImGui::EndDragDropSource(); + } + + // Render icon (a real app would likely display an image/thumbnail here) + // Because we use ImGuiMultiSelectFlags_BoxSelect2d, clipping vertical may occasionally be larger, so we coarse-clip our rendering as well. + if (item_is_visible) + { + ImVec2 box_min(pos.x - 1, pos.y - 1); + ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); // Dubious + draw_list->AddRectFilled(box_min, box_max, icon_bg_color); // Background color + if (ShowTypeOverlay && item_data->Type != 0) + { + ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_COUNTOF(icon_type_overlay_colors)]; + draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col); + } + if (display_label) + { + ImU32 label_col = ImGui::GetColorU32(item_is_selected ? ImGuiCol_Text : ImGuiCol_TextDisabled); + char label[32]; + sprintf(label, "%d", item_data->ID); + draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label); + } + } + + ImGui::PopID(); + } + } + } + clipper.End(); + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing + + // Context menu + if (ImGui::BeginPopupContextWindow()) + { + ImGui::Text("Selection: %d items", Selection.Size); + ImGui::Separator(); + if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0)) + RequestDelete = true; + ImGui::EndPopup(); + } + + ms_io = ImGui::EndMultiSelect(); + Selection.ApplyRequests(ms_io); + if (want_delete) + Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); + + // Zooming with Ctrl+Wheel + if (ImGui::IsWindowAppearing()) + ZoomWheelAccum = 0.0f; + if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) + { + ZoomWheelAccum += io.MouseWheel; + if (fabsf(ZoomWheelAccum) >= 1.0f) + { + // Calculate hovered item index from mouse location + // FIXME: Locking aiming on 'hovered_item_idx' (with a cool-down timer) would ensure zoom keeps on it. + const float hovered_item_nx = (io.MousePos.x - start_pos.x + LayoutItemSpacing * 0.5f) / LayoutItemStep.x; + const float hovered_item_ny = (io.MousePos.y - start_pos.y + LayoutItemSpacing * 0.5f) / LayoutItemStep.y; + const int hovered_item_idx = ((int)hovered_item_ny * LayoutColumnCount) + (int)hovered_item_nx; + //ImGui::SetTooltip("%f,%f -> item %d", hovered_item_nx, hovered_item_ny, hovered_item_idx); // Move those 4 lines in block above for easy debugging + + // Zoom + IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); + IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); + ZoomWheelAccum -= (int)ZoomWheelAccum; + UpdateLayoutSizes(avail_width); + + // Manipulate scroll to that we will land at the same Y location of currently hovered item. + // - Calculate next frame position of item under mouse + // - Set new scroll position to be used in next ImGui::BeginChild() call. + float hovered_item_rel_pos_y = ((float)(hovered_item_idx / LayoutColumnCount) + fmodf(hovered_item_ny, 1.0f)) * LayoutItemStep.y; + hovered_item_rel_pos_y += ImGui::GetStyle().WindowPadding.y; + float mouse_local_y = io.MousePos.y - ImGui::GetWindowPos().y; + ImGui::SetScrollY(hovered_item_rel_pos_y - mouse_local_y); + } + } + } + ImGui::EndChild(); + + ImGui::Text("Selected: %d/%d items", Selection.Size, Items.Size); + ImGui::End(); + } +}; + +void ShowExampleAppAssetsBrowser(bool* p_open) +{ + IMGUI_DEMO_MARKER("Examples/Assets Browser"); + static ExampleAssetsBrowser assets_browser; + assets_browser.Draw("Example: Assets Browser", p_open); +} + +// End of Demo code +#else + +void ImGui::ShowAboutWindow(bool*) {} +void ImGui::ShowDemoWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} +bool ImGui::ShowStyleSelector(const char*) { return false; } + +#endif // #ifndef IMGUI_DISABLE_DEMO_WINDOWS + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui_draw.cpp b/libs/imgui/imgui_draw.cpp new file mode 100644 index 0000000..2b5f331 --- /dev/null +++ b/libs/imgui/imgui_draw.cpp @@ -0,0 +1,6824 @@ +// dear imgui, v1.92.6 WIP +// (drawing and font code) + +/* + +Index of this file: + +// [SECTION] STB libraries implementation +// [SECTION] Style functions +// [SECTION] ImDrawList +// [SECTION] ImTriangulator, ImDrawList concave polygon fill +// [SECTION] ImDrawListSplitter +// [SECTION] ImDrawData +// [SECTION] Helpers ShadeVertsXXX functions +// [SECTION] ImFontConfig +// [SECTION] ImFontAtlas, ImFontAtlasBuilder +// [SECTION] ImFontAtlas: backend for stb_truetype +// [SECTION] ImFontAtlas: glyph ranges helpers +// [SECTION] ImFontGlyphRangesBuilder +// [SECTION] ImFontBaked, ImFont +// [SECTION] ImGui Internal Render Helpers +// [SECTION] Decompression code +// [SECTION] Default font data (ProggyClean.ttf) +// [SECTION] Default font data (ProggyVector-minimal.ttf) + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_internal.h" +#ifdef IMGUI_ENABLE_FREETYPE +#include "misc/freetype/imgui_freetype.h" +#endif + +#include // vsnprintf, sscanf, printf +#include // intptr_t + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result +#endif + +//------------------------------------------------------------------------- +// [SECTION] STB libraries implementation (for stb_truetype and stb_rect_pack) +//------------------------------------------------------------------------- + +// Compile time options: +//#define IMGUI_STB_NAMESPACE ImStb +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#pragma warning (disable: 6011) // (stb_rectpack) Dereferencing NULL pointer 'cur->next'. +#pragma warning (disable: 5262) // (stb_truetype) implicit fall-through occurs here; are you missing a break statement? +#pragma warning (disable: 6385) // (stb_truetype) Reading invalid data from 'buffer': the readable size is '_Old_3`kernel_width' bytes, but '3' bytes may be read. +#pragma warning (disable: 28182) // (stb_rectpack) Dereferencing NULL pointer. 'cur' contains the same NULL value as 'cur->next' did. +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wimplicit-fallthrough" +#endif + +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#pragma GCC diagnostic ignored "-Wimplicit-fallthrough" // warning: this statement may fall through +#endif + +#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in another compilation unit +#define STBRP_STATIC +#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0) +#define STBRP_SORT ImQsort +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#ifdef IMGUI_STB_RECT_PACK_FILENAME +#include IMGUI_STB_RECT_PACK_FILENAME +#else +#include "imstb_rectpack.h" +#endif +#endif + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in another compilation unit +#define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x)) +#define STBTT_free(x,u) ((void)(u), IM_FREE(x)) +#define STBTT_assert(x) do { IM_ASSERT(x); } while(0) +#define STBTT_fmod(x,y) ImFmod(x,y) +#define STBTT_sqrt(x) ImSqrt(x) +#define STBTT_pow(x,y) ImPow(x,y) +#define STBTT_fabs(x) ImFabs(x) +#define STBTT_ifloor(x) ((int)ImFloor(x)) +#define STBTT_iceil(x) ((int)ImCeil(x)) +#define STBTT_strlen(x) ImStrlen(x) +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#ifdef IMGUI_STB_TRUETYPE_FILENAME +#include IMGUI_STB_TRUETYPE_FILENAME +#else +#include "imstb_truetype.h" +#endif +#endif +#endif // IMGUI_ENABLE_STB_TRUETYPE + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Style functions +//----------------------------------------------------------------------------- + +void ImGui::StyleColorsDark(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = colors[ImGuiCol_Border]; + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 0.00f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_HeaderActive] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); +} + +void ImGui::StyleColorsClassic(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); + colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f); + colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); + colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 0.60f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.53f, 0.53f, 0.87f, 0.00f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +// Those light colors are better suited with a thicker font than the default one + FrameBorder +void ImGui::StyleColorsLight(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); + colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 0.00f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.57f, 0.57f, 0.64f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; + colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList +//----------------------------------------------------------------------------- + +ImDrawListSharedData::ImDrawListSharedData() +{ + memset(this, 0, sizeof(*this)); + InitialFringeScale = 1.0f; + for (int i = 0; i < IM_COUNTOF(ArcFastVtx); i++) + { + const float a = ((float)i * 2 * IM_PI) / (float)IM_COUNTOF(ArcFastVtx); + ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); + } + ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); +} + +ImDrawListSharedData::~ImDrawListSharedData() +{ + IM_ASSERT(DrawLists.Size == 0); +} + +void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) +{ + if (CircleSegmentMaxError == max_error) + return; + + IM_ASSERT(max_error > 0.0f); + CircleSegmentMaxError = max_error; + for (int i = 0; i < IM_COUNTOF(CircleSegmentCounts); i++) + { + const float radius = (float)i; + CircleSegmentCounts[i] = (ImU8)((i > 0) ? IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError) : IM_DRAWLIST_ARCFAST_SAMPLE_MAX); + } + ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); +} + +ImDrawList::ImDrawList(ImDrawListSharedData* shared_data) +{ + memset(this, 0, sizeof(*this)); + _SetDrawListSharedData(shared_data); +} + +ImDrawList::~ImDrawList() +{ + _ClearFreeMemory(); + _SetDrawListSharedData(NULL); +} + +void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data) +{ + if (_Data != NULL) + _Data->DrawLists.find_erase_unsorted(this); + _Data = data; + if (_Data != NULL) + _Data->DrawLists.push_back(this); +} + +// Initialize before use in a new frame. We always have a command ready in the buffer. +// In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. +void ImDrawList::_ResetForNewFrame() +{ + // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory to match ImDrawCmdHeader. + IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == sizeof(ImVec4)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureRef)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == offsetof(ImDrawCmdHeader, ClipRect)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == offsetof(ImDrawCmdHeader, TexRef)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == offsetof(ImDrawCmdHeader, VtxOffset)); + if (_Splitter._Count > 1) + _Splitter.Merge(this); + + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + Flags = _Data->InitialFlags; + memset(&_CmdHeader, 0, sizeof(_CmdHeader)); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureStack.resize(0); + _CallbacksDataBuf.resize(0); + _Path.resize(0); + _Splitter.Clear(); + CmdBuffer.push_back(ImDrawCmd()); + _FringeScale = _Data->InitialFringeScale; +} + +void ImDrawList::_ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + Flags = ImDrawListFlags_None; + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureStack.clear(); + _CallbacksDataBuf.clear(); + _Path.clear(); + _Splitter.ClearFreeMemory(); +} + +// Note: For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club +ImDrawList* ImDrawList::CloneOutput() const +{ + ImDrawList* dst = IM_NEW(ImDrawList(NULL)); + dst->CmdBuffer = CmdBuffer; + dst->IdxBuffer = IdxBuffer; + dst->VtxBuffer = VtxBuffer; + dst->Flags = Flags; + return dst; +} + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() + draw_cmd.TexRef = _CmdHeader.TexRef; + draw_cmd.VtxOffset = _CmdHeader.VtxOffset; + draw_cmd.IdxOffset = IdxBuffer.Size; + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +// Pop trailing draw command (used before merging or presenting to user) +// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL +void ImDrawList::_PopUnusedDrawCmd() +{ + while (CmdBuffer.Size > 0) + { + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) + return;// break; + CmdBuffer.pop_back(); + } +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t userdata_size) +{ + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + IM_ASSERT(callback != NULL); + IM_ASSERT(curr_cmd->UserCallback == NULL); + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + } + + curr_cmd->UserCallback = callback; + if (userdata_size == 0) + { + // Store user data directly in command (no indirection) + curr_cmd->UserCallbackData = userdata; + curr_cmd->UserCallbackDataSize = 0; + curr_cmd->UserCallbackDataOffset = -1; + } + else + { + // Copy and store user data in a buffer + IM_ASSERT(userdata != NULL); + IM_ASSERT(userdata_size < (1u << 31)); + curr_cmd->UserCallbackData = NULL; // Will be resolved during Render() + curr_cmd->UserCallbackDataSize = (int)userdata_size; + curr_cmd->UserCallbackDataOffset = _CallbacksDataBuf.Size; + _CallbacksDataBuf.resize(_CallbacksDataBuf.Size + (int)userdata_size); + memcpy(_CallbacksDataBuf.Data + (size_t)curr_cmd->UserCallbackDataOffset, userdata, userdata_size); + } + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Compare ClipRect, TexRef and VtxOffset with a single memcmp() +#define ImDrawCmd_HeaderSize (offsetof(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) +#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TexRef, VtxOffset +#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TexRef, VtxOffset +#define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset) + +// Try to merge two last draw commands +void ImDrawList::_TryMergeDrawCmds() +{ + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (ImDrawCmd_HeaderCompare(curr_cmd, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && curr_cmd->UserCallback == NULL && prev_cmd->UserCallback == NULL) + { + prev_cmd->ElemCount += curr_cmd->ElemCount; + CmdBuffer.pop_back(); + } +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::_OnChangedClipRect() +{ + // If current command is used with different settings we need to add a new command + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + curr_cmd->ClipRect = _CmdHeader.ClipRect; +} + +void ImDrawList::_OnChangedTexture() +{ + // If current command is used with different settings we need to add a new command + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 && curr_cmd->TexRef != _CmdHeader.TexRef) + { + AddDrawCmd(); + return; + } + + // Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. + if (curr_cmd->UserCallback != NULL) + return; + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + curr_cmd->TexRef = _CmdHeader.TexRef; +} + +void ImDrawList::_OnChangedVtxOffset() +{ + // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. + _VtxCurrentIdx = 0; + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + //IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349 + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + curr_cmd->VtxOffset = _CmdHeader.VtxOffset; +} + +int ImDrawList::_CalcCircleAutoSegmentCount(float radius) const +{ + // Automatic segment count + const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy + if (radius_idx >= 0 && radius_idx < IM_COUNTOF(_Data->CircleSegmentCounts)) + return _Data->CircleSegmentCounts[radius_idx]; // Use cached value + else + return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError); +} + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(const ImVec2& cr_min, const ImVec2& cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect) + { + ImVec4 current = _CmdHeader.ClipRect; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + _CmdHeader.ClipRect = cr; + _OnChangedClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w)); +} + +void ImDrawList::PopClipRect() +{ + _ClipRectStack.pop_back(); + _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; + _OnChangedClipRect(); +} + +void ImDrawList::PushTexture(ImTextureRef tex_ref) +{ + _TextureStack.push_back(tex_ref); + _CmdHeader.TexRef = tex_ref; + if (tex_ref._TexData != NULL) + IM_ASSERT(tex_ref._TexData->WantDestroyNextFrame == false); + _OnChangedTexture(); +} + +void ImDrawList::PopTexture() +{ + _TextureStack.pop_back(); + _CmdHeader.TexRef = (_TextureStack.Size == 0) ? ImTextureRef() : _TextureStack.Data[_TextureStack.Size - 1]; + _OnChangedTexture(); +} + +// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). +void ImDrawList::_SetTexture(ImTextureRef tex_ref) +{ + if (_CmdHeader.TexRef == tex_ref) + return; + _CmdHeader.TexRef = tex_ref; + _TextureStack.back() = tex_ref; + _OnChangedTexture(); +} + +// Reserve space for a number of vertices and indices. +// You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or +// submit the intermediate results. PrimUnreserve() can be used to release unused allocations. +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + // Large mesh support (when enabled) + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); + if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) + { + // FIXME: In theory we should be testing that vtx_count <64k here. + // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + // to not make that check until we rework the text functions to handle clipping and large horizontal lines better. + _CmdHeader.VtxOffset = VtxBuffer.Size; + _OnChangedVtxOffset(); + } + + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount += idx_count; + + int vtx_buffer_old_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_old_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; + + int idx_buffer_old_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_old_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; +} + +// Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). +void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) +{ + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); + + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount -= idx_count; + VtxBuffer.shrink(VtxBuffer.Size - vtx_count); + IdxBuffer.shrink(IdxBuffer.Size - idx_count); +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. +// - Those macros expects l-values and need to be used as their own statement. +// - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers. +#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = ImRsqrt(d2); VX *= inv_len; VY *= inv_len; } } (void)0 +#define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) +#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags, float thickness) +{ + if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) + return; + + const bool closed = (flags & ImDrawFlags_Closed) != 0; + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw + const bool thick_line = (thickness > _FringeScale); + + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + // Anti-aliased stroke + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + // Thicknesses <1.0 should behave like thickness 1.0 + thickness = ImMax(thickness, 1.0f); + const int integer_thickness = (int)thickness; + const float fractional_thickness = thickness - integer_thickness; + + // Do we want to draw this line using a texture? + // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. + // - If AA_SIZE is not 1.0f we cannot use the texture path. + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); + + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); + + const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point + _Data->TempBuffer.reserve_discard(points_count * ((use_texture || !thick_line) ? 3 : 5)); + ImVec2* temp_normals = _Data->TempBuffer.Data; + ImVec2* temp_points = temp_normals + points_count; + + // Calculate normals (tangents) for each line segment + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + float dx = points[i2].x - points[i1].x; + float dy = points[i2].y - points[i1].y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i1].x = dy; + temp_normals[i1].y = -dx; + } + if (!closed) + temp_normals[points_count - 1] = temp_normals[points_count - 2]; + + // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point + if (use_texture || !thick_line) + { + // [PATH 1] Texture-based lines (thick or non-thick) + // [PATH 2] Non texture-based lines (non-thick) + + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. + // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture + // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. + // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to + // allow scaling geometry while preserving one-screen-pixel AA fringe). + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * half_draw_size; + temp_points[1] = points[0] - temp_normals[0] * half_draw_size; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size; + } + + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment + const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment + + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area + dm_y *= half_draw_size; + + // Add temporary vertices for the outer edges + ImVec2* out_vtx = &temp_points[i2 * 2]; + out_vtx[0].x = points[i2].x + dm_x; + out_vtx[0].y = points[i2].y + dm_y; + out_vtx[1].x = points[i2].x - dm_x; + out_vtx[1].y = points[i2].y - dm_y; + + if (use_texture) + { + // Add indices for two triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri + _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri + _IdxWritePtr += 6; + } + else + { + // Add indexes for four triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 + _IdxWritePtr += 12; + } + + idx1 = idx2; + } + + // Add vertices for each point on the line + if (use_texture) + { + // If we're using textures we only need to emit the left/right edge vertices + ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; + /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false! + { + const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; + tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() + tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; + tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; + tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; + }*/ + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); + ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr += 2; + } + } + else + { + // If we're not using a texture, we need the center vertex as well + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line + _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge + _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge + _VtxWritePtr += 3; + } + } + } + else + { + // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) + { + const int points_last = points_count - 1; + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + } + + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment + + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); + float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); + float dm_in_x = dm_x * half_inner_thickness; + float dm_in_y = dm_y * half_inner_thickness; + + // Add temporary vertices + ImVec2* out_vtx = &temp_points[i2 * 4]; + out_vtx[0].x = points[i2].x + dm_out_x; + out_vtx[0].y = points[i2].y + dm_out_y; + out_vtx[1].x = points[i2].x + dm_in_x; + out_vtx[1].y = points[i2].y + dm_in_y; + out_vtx[2].x = points[i2].x - dm_in_x; + out_vtx[2].y = points[i2].y - dm_in_y; + out_vtx[3].x = points[i2].x - dm_out_x; + out_vtx[3].y = points[i2].y - dm_out_y; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertices + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // [PATH 4] Non texture-based, Non anti-aliased lines + const int idx_count = count * 6; + const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + + float dx = p2.x - p1.x; + float dy = p2.y - p1.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + dx *= (thickness * 0.5f); + dy *= (thickness * 0.5f); + + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +// - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. +// - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col) +{ + if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + + if (Flags & ImDrawListFlags_AntiAliasedFill) + { + // Anti-aliased Fill + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + const int idx_count = (points_count - 2)*3 + points_count * 6; + const int vtx_count = (points_count * 2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); + _IdxWritePtr += 3; + } + + // Compute normals + _Data->TempBuffer.reserve_discard(points_count); + ImVec2* temp_normals = _Data->TempBuffer.Data; + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + float dx = p1.x - p0.x; + float dy = p1.y - p0.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i0].x = dy; + temp_normals[i0].y = -dx; + } + + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + float dm_x = (n0.x + n1.x) * 0.5f; + float dm_y = (n0.y + n1.y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= AA_SIZE * 0.5f; + dm_y *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count - 2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + // Calculate arc auto segment step size + if (a_step <= 0) + a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); + + // Make sure we never do steps larger than one quarter of the circle + a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + + const int sample_range = ImAbs(a_max_sample - a_min_sample); + const int a_next_step = a_step; + + int samples = sample_range + 1; + bool extra_max_sample = false; + if (a_step > 1) + { + samples = sample_range / a_step + 1; + const int overstep = sample_range % a_step; + + if (overstep > 0) + { + extra_max_sample = true; + samples++; + + // When we have overstep to avoid awkwardly looking one long line and one tiny one at the end, + // distribute first step range evenly between them by reducing first step size. + if (sample_range > 0) + a_step -= (a_step - overstep) / 2; + } + } + + _Path.resize(_Path.Size + samples); + ImVec2* out_ptr = _Path.Data + (_Path.Size - samples); + + int sample_index = a_min_sample; + if (sample_index < 0 || sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX) + { + sample_index = sample_index % IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + if (sample_index < 0) + sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + } + + if (a_max_sample >= a_min_sample) + { + for (int a = a_min_sample; a <= a_max_sample; a += a_step, sample_index += a_step, a_step = a_next_step) + { + // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more + if (sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX) + sample_index -= IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[sample_index]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + } + else + { + for (int a = a_min_sample; a >= a_max_sample; a -= a_step, sample_index -= a_step, a_step = a_next_step) + { + // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more + if (sample_index < 0) + sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[sample_index]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + } + + if (extra_max_sample) + { + int normalized_max_sample = a_max_sample % IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + if (normalized_max_sample < 0) + normalized_max_sample += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[normalized_max_sample]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + + IM_ASSERT_PARANOID(_Path.Data + _Path.Size == out_ptr); +} + +void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + // Note that we are adding a point at both a_min and a_max. + // If you are trying to draw a full closed circle you don't want the overlapping points! + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); + _Path.push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius)); + } +} + +// 0: East, 3: South, 6: West, 9: North, 12: East +void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + _PathArcToFastEx(center, radius, a_min_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, a_max_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, 0); +} + +void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + if (num_segments > 0) + { + _PathArcToN(center, radius, a_min, a_max, num_segments); + return; + } + + // Automatic segment count + if (radius <= _Data->ArcFastRadiusCutoff) + { + const bool a_is_reverse = a_max < a_min; + + // We are going to use precomputed values for mid samples. + // Determine first and last sample in lookup table that belong to the arc. + const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f); + const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f); + + const int a_min_sample = a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f); + const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f); + const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0); + + const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + const float a_max_segment_angle = a_max_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + const bool a_emit_start = ImAbs(a_min_segment_angle - a_min) >= 1e-5f; + const bool a_emit_end = ImAbs(a_max - a_max_segment_angle) >= 1e-5f; + + _Path.reserve(_Path.Size + (a_mid_samples + 1 + (a_emit_start ? 1 : 0) + (a_emit_end ? 1 : 0))); + if (a_emit_start) + _Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius)); + if (a_mid_samples > 0) + _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0); + if (a_emit_end) + _Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius)); + } + else + { + const float arc_length = ImAbs(a_max - a_min); + const int circle_segment_count = _CalcCircleAutoSegmentCount(radius); + const int arc_segment_count = ImMax((int)ImCeil(circle_segment_count * arc_length / (IM_PI * 2.0f)), (int)(2.0f * IM_PI / arc_length)); + _PathArcToN(center, radius, a_min, a_max, arc_segment_count); + } +} + +void ImDrawList::PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments) +{ + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + + _Path.reserve(_Path.Size + (num_segments + 1)); + + const float cos_rot = ImCos(rot); + const float sin_rot = ImSin(rot); + for (int i = 0; i <= num_segments; i++) + { + const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); + ImVec2 point(ImCos(a) * radius.x, ImSin(a) * radius.y); + const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot)); + point.x = rel.x + center.x; + point.y = rel.y + center.y; + _Path.push_back(point); + } +} + +ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t) +{ + float u = 1.0f - t; + float w1 = u * u * u; + float w2 = 3 * u * u * t; + float w3 = 3 * u * t * t; + float w4 = t * t * t; + return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y); +} + +ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t) +{ + float u = 1.0f - t; + float w1 = u * u; + float w2 = 2 * u * t; + float w3 = t * t; + return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y); +} + +// Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp +static void PathBezierCubicCurveToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = (x2 - x4) * dy - (y2 - y4) * dx; + float d3 = (x3 - x4) * dy - (y3 - y4) * dx; + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f; + float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f; + float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f; + float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f; + float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f; + float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f; + PathBezierCubicCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + PathBezierCubicCurveToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); + } +} + +static void PathBezierQuadraticCurveToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float tess_tol, int level) +{ + float dx = x3 - x1, dy = y3 - y1; + float det = (x2 - x3) * dy - (y2 - y3) * dx; + if (det * det * 4.0f < tess_tol * (dx * dx + dy * dy)) + { + path->push_back(ImVec2(x3, y3)); + } + else if (level < 10) + { + float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f; + float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f; + float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f; + PathBezierQuadraticCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, tess_tol, level + 1); + PathBezierQuadraticCurveToCasteljau(path, x123, y123, x23, y23, x3, y3, tess_tol, level + 1); + } +} + +void ImDrawList::PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + IM_ASSERT(_Data->CurveTessellationTol > 0.0f); + PathBezierCubicCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); // Auto-tessellated + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + _Path.push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step)); + } +} + +void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + IM_ASSERT(_Data->CurveTessellationTol > 0.0f); + PathBezierQuadraticCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, _Data->CurveTessellationTol, 0);// Auto-tessellated + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + _Path.push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step)); + } +} + +static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags) +{ + /* + IM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4)); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Obsoleted in 1.82 (from February 2021). This code was stripped/simplified and mostly commented in 1.90 (from September 2023) + // - Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All) + if (flags == ~0) { return ImDrawFlags_RoundCornersAll; } + // - Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations). Read details in older version of this code. + if (flags >= 0x01 && flags <= 0x0F) { return (flags << 4); } + // We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f' +#endif + */ + // If this assert triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values. + // Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc. anyway. + // See details in 1.82 Changelog as well as 2021/03/12 and 2023/09/08 entries in "API BREAKING CHANGES" section. + IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!"); + + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + + return flags; +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags) +{ + if (rounding >= 0.5f) + { + flags = FixRectCornerFlags(flags); + rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + } + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x, a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x, b.y)); + } + else + { + const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? rounding : 0.0f; + PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); + PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); + PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); + PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathLineTo(p1 + ImVec2(0.5f, 0.5f)); + PathLineTo(p2 + ImVec2(0.5f, 0.5f)); + PathStroke(col, 0, thickness); +} + +// p_min = upper-left, p_max = lower-right +// Note we don't render 1 pixels sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); + else + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PrimReserve(6, 4); + PrimRect(p_min, p_max, col); + } + else + { + PathRect(p_min, p_max, rounding, flags); + PathFillConvex(col); + } +} + +// p_min = upper-left, p_max = lower-right +void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3)); + PrimWriteVtx(p_min, uv, col_upr_left); + PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right); + PrimWriteVtx(p_max, uv, col_bot_right); + PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathFillConvex(col); +} + +void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathFillConvex(col); +} + +void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + return; + + if (num_segments <= 0) + { + // Use arc with automatic segment count + _PathArcToFastEx(center, radius - 0.5f, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + _Path.Size--; + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + } + + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + return; + + if (num_segments <= 0) + { + // Use arc with automatic segment count + _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + _Path.Size--; + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + } + + PathFillConvex(col); +} + +// Guaranteed to honor 'num_segments' +void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) + return; + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +// Guaranteed to honor 'num_segments' +void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) + return; + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + PathFillConvex(col); +} + +// Ellipse +void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathFillConvex(col); +} + +// Cubic Bezier takes 4 controls points +void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathBezierCubicCurveTo(p2, p3, p4, num_segments); + PathStroke(col, 0, thickness); +} + +// Quadratic Bezier takes 3 controls points +void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathBezierQuadraticCurveTo(p2, p3, num_segments); + PathStroke(col, 0, thickness); +} + +void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + // Accept null ranges + if (text_begin == text_end || text_begin[0] == 0) + return; + // No need to strlen() here: font->RenderText() will do it and may early out. + + // Pull default font/size from the shared ImDrawListSharedData instance + if (font == NULL) + font = _Data->Font; + if (font_size == 0.0f) + font_size = _Data->FontSize; + + ImVec4 clip_rect = _CmdHeader.ClipRect; + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, (cpu_fine_clip_rect != NULL) ? ImDrawTextFlags_CpuFineClip : ImDrawTextFlags_None); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; + if (push_texture_id) + PushTexture(tex_ref); + + PrimReserve(6, 4); + PrimRectUV(p_min, p_max, uv_min, uv_max, col); + + if (push_texture_id) + PopTexture(); +} + +void ImDrawList::AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; + if (push_texture_id) + PushTexture(tex_ref); + + PrimReserve(6, 4); + PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); + + if (push_texture_id) + PopTexture(); +} + +void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + flags = FixRectCornerFlags(flags); + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col); + return; + } + + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; + if (push_texture_id) + PushTexture(tex_ref); + + int vert_start_idx = VtxBuffer.Size; + PathRect(p_min, p_max, rounding, flags); + PathFillConvex(col); + int vert_end_idx = VtxBuffer.Size; + ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); + + if (push_texture_id) + PopTexture(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImTriangulator, ImDrawList concave polygon fill +//----------------------------------------------------------------------------- +// Triangulate concave polygons. Based on "Triangulation by Ear Clipping" paper, O(N^2) complexity. +// Reference: https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf +// Provided as a convenience for user but not used by main library. +//----------------------------------------------------------------------------- +// - ImTriangulator [Internal] +// - AddConcavePolyFilled() +//----------------------------------------------------------------------------- + +enum ImTriangulatorNodeType +{ + ImTriangulatorNodeType_Convex, + ImTriangulatorNodeType_Ear, + ImTriangulatorNodeType_Reflex +}; + +struct ImTriangulatorNode +{ + ImTriangulatorNodeType Type; + int Index; + ImVec2 Pos; + ImTriangulatorNode* Next; + ImTriangulatorNode* Prev; + + void Unlink() { Next->Prev = Prev; Prev->Next = Next; } +}; + +struct ImTriangulatorNodeSpan +{ + ImTriangulatorNode** Data = NULL; + int Size = 0; + + void push_back(ImTriangulatorNode* node) { Data[Size++] = node; } + void find_erase_unsorted(int idx) { for (int i = Size - 1; i >= 0; i--) if (Data[i]->Index == idx) { Data[i] = Data[Size - 1]; Size--; return; } } +}; + +struct ImTriangulator +{ + static int EstimateTriangleCount(int points_count) { return (points_count < 3) ? 0 : points_count - 2; } + static int EstimateScratchBufferSize(int points_count) { return sizeof(ImTriangulatorNode) * points_count + sizeof(ImTriangulatorNode*) * points_count * 2; } + + void Init(const ImVec2* points, int points_count, void* scratch_buffer); + void GetNextTriangle(unsigned int out_triangle[3]); // Return relative indexes for next triangle + + // Internal functions + void BuildNodes(const ImVec2* points, int points_count); + void BuildReflexes(); + void BuildEars(); + void FlipNodeList(); + bool IsEar(int i0, int i1, int i2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2) const; + void ReclassifyNode(ImTriangulatorNode* node); + + // Internal members + int _TrianglesLeft = 0; + ImTriangulatorNode* _Nodes = NULL; + ImTriangulatorNodeSpan _Ears; + ImTriangulatorNodeSpan _Reflexes; +}; + +// Distribute storage for nodes, ears and reflexes. +// FIXME-OPT: if everything is convex, we could report it to caller and let it switch to an convex renderer +// (this would require first building reflexes to bail to convex if empty, without even building nodes) +void ImTriangulator::Init(const ImVec2* points, int points_count, void* scratch_buffer) +{ + IM_ASSERT(scratch_buffer != NULL && points_count >= 3); + _TrianglesLeft = EstimateTriangleCount(points_count); + _Nodes = (ImTriangulatorNode*)scratch_buffer; // points_count x Node + _Ears.Data = (ImTriangulatorNode**)(_Nodes + points_count); // points_count x Node* + _Reflexes.Data = (ImTriangulatorNode**)(_Nodes + points_count) + points_count; // points_count x Node* + BuildNodes(points, points_count); + BuildReflexes(); + BuildEars(); +} + +void ImTriangulator::BuildNodes(const ImVec2* points, int points_count) +{ + for (int i = 0; i < points_count; i++) + { + _Nodes[i].Type = ImTriangulatorNodeType_Convex; + _Nodes[i].Index = i; + _Nodes[i].Pos = points[i]; + _Nodes[i].Next = _Nodes + i + 1; + _Nodes[i].Prev = _Nodes + i - 1; + } + _Nodes[0].Prev = _Nodes + points_count - 1; + _Nodes[points_count - 1].Next = _Nodes; +} + +void ImTriangulator::BuildReflexes() +{ + ImTriangulatorNode* n1 = _Nodes; + for (int i = _TrianglesLeft; i >= 0; i--, n1 = n1->Next) + { + if (ImTriangleIsClockwise(n1->Prev->Pos, n1->Pos, n1->Next->Pos)) + continue; + n1->Type = ImTriangulatorNodeType_Reflex; + _Reflexes.push_back(n1); + } +} + +void ImTriangulator::BuildEars() +{ + ImTriangulatorNode* n1 = _Nodes; + for (int i = _TrianglesLeft; i >= 0; i--, n1 = n1->Next) + { + if (n1->Type != ImTriangulatorNodeType_Convex) + continue; + if (!IsEar(n1->Prev->Index, n1->Index, n1->Next->Index, n1->Prev->Pos, n1->Pos, n1->Next->Pos)) + continue; + n1->Type = ImTriangulatorNodeType_Ear; + _Ears.push_back(n1); + } +} + +void ImTriangulator::GetNextTriangle(unsigned int out_triangle[3]) +{ + if (_Ears.Size == 0) + { + FlipNodeList(); + + ImTriangulatorNode* node = _Nodes; + for (int i = _TrianglesLeft; i >= 0; i--, node = node->Next) + node->Type = ImTriangulatorNodeType_Convex; + _Reflexes.Size = 0; + BuildReflexes(); + BuildEars(); + + // If we still don't have ears, it means geometry is degenerated. + if (_Ears.Size == 0) + { + // Return first triangle available, mimicking the behavior of convex fill. + IM_ASSERT(_TrianglesLeft > 0); // Geometry is degenerated + _Ears.Data[0] = _Nodes; + _Ears.Size = 1; + } + } + + ImTriangulatorNode* ear = _Ears.Data[--_Ears.Size]; + out_triangle[0] = ear->Prev->Index; + out_triangle[1] = ear->Index; + out_triangle[2] = ear->Next->Index; + + ear->Unlink(); + if (ear == _Nodes) + _Nodes = ear->Next; + + ReclassifyNode(ear->Prev); + ReclassifyNode(ear->Next); + _TrianglesLeft--; +} + +void ImTriangulator::FlipNodeList() +{ + ImTriangulatorNode* prev = _Nodes; + ImTriangulatorNode* temp = _Nodes; + ImTriangulatorNode* current = _Nodes->Next; + prev->Next = prev; + prev->Prev = prev; + while (current != _Nodes) + { + temp = current->Next; + + current->Next = prev; + prev->Prev = current; + _Nodes->Next = current; + current->Prev = _Nodes; + + prev = current; + current = temp; + } + _Nodes = prev; +} + +// A triangle is an ear is no other vertex is inside it. We can test reflexes vertices only (see reference algorithm) +bool ImTriangulator::IsEar(int i0, int i1, int i2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2) const +{ + ImTriangulatorNode** p_end = _Reflexes.Data + _Reflexes.Size; + for (ImTriangulatorNode** p = _Reflexes.Data; p < p_end; p++) + { + ImTriangulatorNode* reflex = *p; + if (reflex->Index != i0 && reflex->Index != i1 && reflex->Index != i2) + if (ImTriangleContainsPoint(v0, v1, v2, reflex->Pos)) + return false; + } + return true; +} + +void ImTriangulator::ReclassifyNode(ImTriangulatorNode* n1) +{ + // Classify node + ImTriangulatorNodeType type; + const ImTriangulatorNode* n0 = n1->Prev; + const ImTriangulatorNode* n2 = n1->Next; + if (!ImTriangleIsClockwise(n0->Pos, n1->Pos, n2->Pos)) + type = ImTriangulatorNodeType_Reflex; + else if (IsEar(n0->Index, n1->Index, n2->Index, n0->Pos, n1->Pos, n2->Pos)) + type = ImTriangulatorNodeType_Ear; + else + type = ImTriangulatorNodeType_Convex; + + // Update lists when a type changes + if (type == n1->Type) + return; + if (n1->Type == ImTriangulatorNodeType_Reflex) + _Reflexes.find_erase_unsorted(n1->Index); + else if (n1->Type == ImTriangulatorNodeType_Ear) + _Ears.find_erase_unsorted(n1->Index); + if (type == ImTriangulatorNodeType_Reflex) + _Reflexes.push_back(n1); + else if (type == ImTriangulatorNodeType_Ear) + _Ears.push_back(n1); + n1->Type = type; +} + +// Use ear-clipping algorithm to triangulate a simple polygon (no self-interaction, no holes). +// (Reminder: we don't perform any coarse clipping/culling in ImDrawList layer! +// It is up to caller to ensure not making costly calls that will be outside of visible area. +// As concave fill is noticeably more expensive than other primitives, be mindful of this... +// Caller can build AABB of points, and avoid filling if 'draw_list->_CmdHeader.ClipRect.Overlays(points_bb) == false') +void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_count, ImU32 col) +{ + if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + ImTriangulator triangulator; + unsigned int triangle[3]; + if (Flags & ImDrawListFlags_AntiAliasedFill) + { + // Anti-aliased Fill + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + const int idx_count = (points_count - 2) * 3 + points_count * 6; + const int vtx_count = (points_count * 2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; + + _Data->TempBuffer.reserve_discard((ImTriangulator::EstimateScratchBufferSize(points_count) + sizeof(ImVec2)) / sizeof(ImVec2)); + triangulator.Init(points, points_count, _Data->TempBuffer.Data); + while (triangulator._TrianglesLeft > 0) + { + triangulator.GetNextTriangle(triangle); + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (triangle[0] << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (triangle[1] << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (triangle[2] << 1)); + _IdxWritePtr += 3; + } + + // Compute normals + _Data->TempBuffer.reserve_discard(points_count); + ImVec2* temp_normals = _Data->TempBuffer.Data; + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + float dx = p1.x - p0.x; + float dy = p1.y - p0.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i0].x = dy; + temp_normals[i0].y = -dx; + } + + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + float dm_x = (n0.x + n1.x) * 0.5f; + float dm_y = (n0.y + n1.y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= AA_SIZE * 0.5f; + dm_y *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count - 2) * 3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + _Data->TempBuffer.reserve_discard((ImTriangulator::EstimateScratchBufferSize(points_count) + sizeof(ImVec2)) / sizeof(ImVec2)); + triangulator.Init(points, points_count, _Data->TempBuffer.Data); + while (triangulator._TrianglesLeft > 0) + { + triangulator.GetNextTriangle(triangle); + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx + triangle[0]); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + triangle[1]); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + triangle[2]); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawListSplitter +//----------------------------------------------------------------------------- +// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +//----------------------------------------------------------------------------- + +void ImDrawListSplitter::ClearFreeMemory() +{ + for (int i = 0; i < _Channels.Size; i++) + { + if (i == _Current) + memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i]._CmdBuffer.clear(); + _Channels[i]._IdxBuffer.clear(); + } + _Current = 0; + _Count = 1; + _Channels.clear(); +} + +void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) +{ + IM_UNUSED(draw_list); + IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter."); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + { + _Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable + _Channels.resize(channels_count); + } + _Count = channels_count; + + // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer + // The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i]._CmdBuffer.resize(0); + _Channels[i]._IdxBuffer.resize(0); + } + } +} + +void ImDrawListSplitter::Merge(ImDrawList* draw_list) +{ + // Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_Count <= 1) + return; + + SetCurrentChannel(draw_list, 0); + draw_list->_PopUnusedDrawCmd(); + + // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. + int new_cmd_buffer_count = 0; + int new_idx_buffer_count = 0; + ImDrawCmd* last_cmd = (_Count > 0 && draw_list->CmdBuffer.Size > 0) ? &draw_list->CmdBuffer.back() : NULL; + int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0 && ch._CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd() + ch._CmdBuffer.pop_back(); + + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL) + { + // Do not include ImDrawCmd_AreSequentialIdxOffset() in the compare as we rebuild IdxOffset values ourselves. + // Manipulating IdxOffset (e.g. by reordering draw commands like done by RenderDimmedBackgroundBehindWindow()) is not supported within a splitter. + ImDrawCmd* next_cmd = &ch._CmdBuffer[0]; + if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL) + { + // Merge previous channel last draw command with current channel first draw command if matching. + last_cmd->ElemCount += next_cmd->ElemCount; + idx_offset += next_cmd->ElemCount; + ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges. + } + } + if (ch._CmdBuffer.Size > 0) + last_cmd = &ch._CmdBuffer.back(); + new_cmd_buffer_count += ch._CmdBuffer.Size; + new_idx_buffer_count += ch._IdxBuffer.Size; + for (int cmd_n = 0; cmd_n < ch._CmdBuffer.Size; cmd_n++) + { + ch._CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; + idx_offset += ch._CmdBuffer.Data[cmd_n].ElemCount; + } + } + draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count); + draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count); + + // Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices) + ImDrawCmd* cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count; + ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } + } + draw_list->_IdxWritePtr = idx_write; + + // Ensure there's always a non-callback draw command trailing the command-buffer + if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) + draw_list->AddDrawCmd(); + + // If current command is used with different settings we need to add a new command + ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); + + _Count = 1; +} + +void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) +{ + IM_ASSERT(idx >= 0 && idx < _Count); + if (_Current == idx) + return; + + // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() + memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); + _Current = idx; + memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer)); + draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; + + // If current command is used with different settings we need to add a new command + ImDrawCmd* curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd == NULL) + draw_list->AddDrawCmd(); + else if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawData +//----------------------------------------------------------------------------- + +void ImDrawData::Clear() +{ + Valid = false; + CmdListsCount = TotalIdxCount = TotalVtxCount = 0; + CmdLists.resize(0); // The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. + DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.0f, 0.0f); + OwnerViewport = NULL; + Textures = NULL; +} + +// Important: 'out_list' is generally going to be draw_data->CmdLists, but may be another temporary list +// as long at it is expected that the result will be later merged into draw_data->CmdLists[]. +void ImGui::AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector* out_list, ImDrawList* draw_list) +{ + if (draw_list->CmdBuffer.Size == 0) + return; + if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL) + return; + + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + // May trigger for you if you are using PrimXXX functions incorrectly. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) + // If this assert triggers because you are drawing lots of stuff manually: + // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. + // Be mindful that the lower-level ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents. + // - If you want large meshes with more than 64K vertices, you can either: + // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. + // Most example backends already support this from 1.71. Pre-1.71 backends won't. + // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. + // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. + // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time: + // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + // Your own engine or render API may use different parameters or function calls to specify index sizes. + // 2 and 4 bytes indices are generally supported by most graphics API. + // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching + // the 64K limit to split your draw commands in multiple draw lists. + if (sizeof(ImDrawIdx) == 2) + IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); + + // Resolve callback data pointers + if (draw_list->_CallbacksDataBuf.Size > 0) + for (ImDrawCmd& cmd : draw_list->CmdBuffer) + if (cmd.UserCallback != NULL && cmd.UserCallbackDataOffset != -1 && cmd.UserCallbackDataSize > 0) + cmd.UserCallbackData = draw_list->_CallbacksDataBuf.Data + cmd.UserCallbackDataOffset; + + // Add to output list + records state in ImDrawData + out_list->push_back(draw_list); + draw_data->CmdListsCount++; + draw_data->TotalVtxCount += draw_list->VtxBuffer.Size; + draw_data->TotalIdxCount += draw_list->IdxBuffer.Size; +} + +void ImDrawData::AddDrawList(ImDrawList* draw_list) +{ + IM_ASSERT(CmdLists.Size == CmdListsCount); + draw_list->_PopUnusedDrawCmd(); + ImGui::AddDrawListToDrawDataEx(this, &CmdLists, draw_list); +} + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (ImDrawList* draw_list : CmdLists) + { + if (draw_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(draw_list->IdxBuffer.Size); + for (int j = 0; j < draw_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = draw_list->VtxBuffer[draw_list->IdxBuffer[j]]; + draw_list->VtxBuffer.swap(new_vtx_buffer); + draw_list->IdxBuffer.resize(0); + TotalVtxCount += draw_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. +// Use if your final output buffer is at a different scale than draw_data->DisplaySize, +// or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) +{ + for (ImDrawList* draw_list : CmdLists) + for (ImDrawCmd& cmd : draw_list->CmdBuffer) + cmd.ClipRect = ImVec4(cmd.ClipRect.x * fb_scale.x, cmd.ClipRect.y * fb_scale.y, cmd.ClipRect.z * fb_scale.x, cmd.ClipRect.w * fb_scale.y); +} + +//----------------------------------------------------------------------------- +// [SECTION] Helpers ShadeVertsXXX functions +//----------------------------------------------------------------------------- + +// Generic linear color gradient, write to RGB fields, leave A untouched. +void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) +{ + ImVec2 gradient_extent = gradient_p1 - gradient_p0; + float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); + ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF; + const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF; + const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF; + const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r; + const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g; + const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b; + for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) + { + float d = ImDot(vert->pos - gradient_p0, gradient_extent); + float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); + int r = (int)(col0_r + col_delta_r * t); + int g = (int)(col0_g + col_delta_g * t); + int b = (int)(col0_b + col_delta_b * t); + vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); + } +} + +// Distribute UV over (a, b) rectangle +void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp) +{ + const ImVec2 size = b - a; + const ImVec2 uv_size = uv_b - uv_a; + const ImVec2 scale = ImVec2( + size.x != 0.0f ? (uv_size.x / size.x) : 0.0f, + size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); + + ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + if (clamp) + { + const ImVec2 min = ImMin(uv_a, uv_b); + const ImVec2 max = ImMax(uv_a, uv_b); + for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max); + } + else + { + for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale); + } +} + +void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& pivot_in, float cos_a, float sin_a, const ImVec2& pivot_out) +{ + ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) + vertex->pos = ImRotate(vertex->pos- pivot_in, cos_a, sin_a) + pivot_out; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontConfig +//----------------------------------------------------------------------------- + +// FIXME-NEWATLAS: Oversample specification could be more dynamic. For now, favoring automatic selection. +ImFontConfig::ImFontConfig() +{ + memset(this, 0, sizeof(*this)); + FontDataOwnedByAtlas = true; + OversampleH = 0; // Auto == 1 or 2 depending on size + OversampleV = 0; // Auto == 1 + ExtraSizeScale = 1.0f; + GlyphMaxAdvanceX = FLT_MAX; + RasterizerMultiply = 1.0f; + RasterizerDensity = 1.0f; + EllipsisChar = 0; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImTextureData +//----------------------------------------------------------------------------- +// - ImTextureData::Create() +// - ImTextureData::DestroyPixels() +//----------------------------------------------------------------------------- + +int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return 1; + case ImTextureFormat_RGBA32: return 4; + } + IM_ASSERT(0); + return 0; +} + +const char* ImTextureDataGetStatusName(ImTextureStatus status) +{ + switch (status) + { + case ImTextureStatus_OK: return "OK"; + case ImTextureStatus_Destroyed: return "Destroyed"; + case ImTextureStatus_WantCreate: return "WantCreate"; + case ImTextureStatus_WantUpdates: return "WantUpdates"; + case ImTextureStatus_WantDestroy: return "WantDestroy"; + } + return "N/A"; +} + +const char* ImTextureDataGetFormatName(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return "Alpha8"; + case ImTextureFormat_RGBA32: return "RGBA32"; + } + return "N/A"; +} + +void ImTextureData::Create(ImTextureFormat format, int w, int h) +{ + IM_ASSERT(Status == ImTextureStatus_Destroyed); + DestroyPixels(); + Format = format; + Status = ImTextureStatus_WantCreate; + Width = w; + Height = h; + BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format); + UseColors = false; + Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); + IM_ASSERT(Pixels != NULL); + memset(Pixels, 0, Width * Height * BytesPerPixel); + UsedRect.x = UsedRect.y = UsedRect.w = UsedRect.h = 0; + UpdateRect.x = UpdateRect.y = (unsigned short)~0; + UpdateRect.w = UpdateRect.h = 0; +} + +void ImTextureData::DestroyPixels() +{ + if (Pixels) + IM_FREE(Pixels); + Pixels = NULL; + UseColors = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas, ImFontAtlasBuilder +//----------------------------------------------------------------------------- +// - Default texture data encoded in ASCII +// - ImFontAtlas() +// - ImFontAtlas::Clear() +// - ImFontAtlas::CompactCache() +// - ImFontAtlas::ClearInputData() +// - ImFontAtlas::ClearTexData() +// - ImFontAtlas::ClearFonts() +//----------------------------------------------------------------------------- +// - ImFontAtlasUpdateNewFrame() +// - ImFontAtlasTextureBlockConvert() +// - ImFontAtlasTextureBlockPostProcess() +// - ImFontAtlasTextureBlockPostProcessMultiply() +// - ImFontAtlasTextureBlockFill() +// - ImFontAtlasTextureBlockCopy() +// - ImFontAtlasTextureBlockQueueUpload() +//----------------------------------------------------------------------------- +// - ImFontAtlas::GetTexDataAsAlpha8() [legacy] +// - ImFontAtlas::GetTexDataAsRGBA32() [legacy] +// - ImFontAtlas::Build() [legacy] +//----------------------------------------------------------------------------- +// - ImFontAtlas::AddFont() +// - ImFontAtlas::AddFontDefault() +// - ImFontAtlas::AddFontDefaultBitmap() +// - ImFontAtlas::AddFontDefaultVector() +// - ImFontAtlas::AddFontFromFileTTF() +// - ImFontAtlas::AddFontFromMemoryTTF() +// - ImFontAtlas::AddFontFromMemoryCompressedTTF() +// - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF() +// - ImFontAtlas::RemoveFont() +// - ImFontAtlasBuildNotifySetFont() +//----------------------------------------------------------------------------- +// - ImFontAtlas::AddCustomRect() +// - ImFontAtlas::RemoveCustomRect() +// - ImFontAtlas::GetCustomRect() +// - ImFontAtlas::AddCustomRectFontGlyph() [legacy] +// - ImFontAtlas::AddCustomRectFontGlyphForSize() [legacy] +// - ImFontAtlasGetMouseCursorTexData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildMain() +// - ImFontAtlasBuildSetupFontLoader() +// - ImFontAtlasBuildPreloadAllGlyphRanges() +// - ImFontAtlasBuildUpdatePointers() +// - ImFontAtlasBuildRenderBitmapFromString() +// - ImFontAtlasBuildUpdateBasicTexData() +// - ImFontAtlasBuildUpdateLinesTexData() +// - ImFontAtlasBuildAddFont() +// - ImFontAtlasBuildSetupFontBakedEllipsis() +// - ImFontAtlasBuildSetupFontBakedBlanks() +// - ImFontAtlasBuildSetupFontBakedFallback() +// - ImFontAtlasBuildSetupFontSpecialGlyphs() +// - ImFontAtlasBuildDiscardBakes() +// - ImFontAtlasBuildDiscardFontBakedGlyph() +// - ImFontAtlasBuildDiscardFontBaked() +// - ImFontAtlasBuildDiscardFontBakes() +//----------------------------------------------------------------------------- +// - ImFontAtlasAddDrawListSharedData() +// - ImFontAtlasRemoveDrawListSharedData() +// - ImFontAtlasUpdateDrawListsTextures() +// - ImFontAtlasUpdateDrawListsSharedData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildSetTexture() +// - ImFontAtlasBuildAddTexture() +// - ImFontAtlasBuildMakeSpace() +// - ImFontAtlasBuildRepackTexture() +// - ImFontAtlasBuildGrowTexture() +// - ImFontAtlasBuildRepackOrGrowTexture() +// - ImFontAtlasBuildGetTextureSizeEstimate() +// - ImFontAtlasBuildCompactTexture() +// - ImFontAtlasBuildInit() +// - ImFontAtlasBuildDestroy() +//----------------------------------------------------------------------------- +// - ImFontAtlasPackInit() +// - ImFontAtlasPackAllocRectEntry() +// - ImFontAtlasPackReuseRectEntry() +// - ImFontAtlasPackDiscardRect() +// - ImFontAtlasPackAddRect() +// - ImFontAtlasPackGetRect() +//----------------------------------------------------------------------------- +// - ImFontBaked_BuildGrowIndex() +// - ImFontBaked_BuildLoadGlyph() +// - ImFontBaked_BuildLoadGlyphAdvanceX() +// - ImFontAtlasDebugLogTextureRequests() +//----------------------------------------------------------------------------- +// - ImFontAtlasGetFontLoaderForStbTruetype() +//----------------------------------------------------------------------------- + +// A work of art lies ahead! (. = white layer, X = black layer, others are blank) +// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +// (This is used when io.MouseDrawCursor = true) +const int FONT_ATLAS_DEFAULT_TEX_DATA_W = 122; // Actual texture will be 2 times that + 1 spacing. +const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; +static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = +{ + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " + "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X -X...X X...X" + "X - X.X - X.....X - X.....X -X...X - X...X- X..X - X...X X...X " + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X - X...X...X " + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX - X.....X " + "X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX - X...X " + "X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X - X...X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X- X.....X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X- X...X...X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X- X...X X...X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X-X...X X...X" + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X-X..X X..X" + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X- XX XX " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X--------------" + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X - " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X - " + "X.X X..X - -X.......X- X.......X - XX XX - - X..........X - " + "XX X..X - - X.....X - X.....X - X.X X.X - - X........X - " + " X..X - - X...X - X...X - X..X X..X - - X........X - " + " XX - - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX - " + "------------- - X - X -X.....................X- ------------------- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " +}; + +static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] = +{ + // Pos ........ Size ......... Offset ...... + { ImVec2( 0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2( 7,16), ImVec2( 1, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 4,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 4) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE + { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Wait // Arrow + custom code in ImGui::RenderMouseCursor() + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Progress // Arrow + custom code in ImGui::RenderMouseCursor() + { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed +}; + +#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF +#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE + +ImFontAtlas::ImFontAtlas() +{ + memset(this, 0, sizeof(*this)); + TexDesiredFormat = ImTextureFormat_RGBA32; + TexGlyphPadding = 1; + TexMinWidth = 512; + TexMinHeight = 128; + TexMaxWidth = 8192; + TexMaxHeight = 8192; + TexRef._TexID = ImTextureID_Invalid; + RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. + TexNextUniqueID = 1; + FontNextUniqueID = 1; + Builder = NULL; +} + +ImFontAtlas::~ImFontAtlas() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); + ClearTexData(); + TexList.clear_delete(); + TexData = NULL; +} + +// If you call this mid-frame, you would need to add new font and bind them! +void ImFontAtlas::Clear() +{ + bool backup_renderer_has_textures = RendererHasTextures; + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); + ClearTexData(); + RendererHasTextures = backup_renderer_has_textures; +} + +void ImFontAtlas::CompactCache() +{ + ImFontAtlasTextureCompact(this); +} + +void ImFontAtlas::SetFontLoader(const ImFontLoader* font_loader) +{ + ImFontAtlasBuildSetupFontLoader(this, font_loader); +} + +void ImFontAtlas::ClearInputData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + + for (ImFont* font : Fonts) + ImFontAtlasFontDestroyOutput(this, font); + for (ImFontConfig& font_cfg : Sources) + ImFontAtlasFontDestroySourceData(this, &font_cfg); + for (ImFont* font : Fonts) + { + // When clearing this we lose access to the font name and other information used to build the font. + font->Sources.clear(); + font->Flags |= ImFontFlags_NoLoadGlyphs; + } + Sources.clear(); +} + +// Clear CPU-side copy of the texture data. +void ImFontAtlas::ClearTexData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + IM_ASSERT(RendererHasTextures == false && "Not supported for dynamic atlases, but you may call Clear()."); + for (ImTextureData* tex : TexList) + tex->DestroyPixels(); + //Locked = true; // Hoped to be able to lock this down but some reload patterns may not be happy with it. +} + +void ImFontAtlas::ClearFonts() +{ + // FIXME-NEWATLAS: Illegal to remove currently bound font. + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + for (ImFont* font : Fonts) + ImFontAtlasBuildNotifySetFont(this, font, NULL); + ImFontAtlasBuildDestroy(this); + ClearInputData(); + Fonts.clear_delete(); + TexIsBuilt = false; + for (ImDrawListSharedData* shared_data : DrawListSharedDatas) + if (shared_data->FontAtlas == this) + { + shared_data->Font = NULL; + shared_data->FontScale = shared_data->FontSize = 0.0f; + } +} + +static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas) +{ + // [LEGACY] Copy back the ImGuiBackendFlags_RendererHasTextures flag from ImGui context. + // - This is the 1% exceptional case where that dependency if useful, to bypass an issue where otherwise at the + // time of an early call to Build(), it would be impossible for us to tell if the backend supports texture update. + // - Without this hack, we would have quite a pitfall as many legacy codebases have an early call to Build(). + // Whereas conversely, the portion of people using ImDrawList without ImGui is expected to be pathologically rare. + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + if (ImGuiContext* imgui_ctx = shared_data->Context) + { + atlas->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + break; + } +} + +// Called by NewFrame() for atlases owned by a context. +// If you manually manage font atlases, you'll need to call this yourself. +// - 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. +// - 'frame_count' may not match those of all imgui contexts using this atlas, as contexts may be updated as different frequencies. But generally you can use ImGui::GetFrameCount() on one of your context. +void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures) +{ + IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice. + atlas->RendererHasTextures = renderer_has_textures; + + // Check that font atlas was built or backend support texture reload in which case we can build now + if (atlas->RendererHasTextures) + { + atlas->TexIsBuilt = true; + if (atlas->Builder == NULL) // This will only happen if fonts were not already loaded. + ImFontAtlasBuildMain(atlas); + } + // Legacy backend + if (!atlas->RendererHasTextures) + IM_ASSERT_USER_ERROR(atlas->TexIsBuilt, "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); + if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) + IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); + + // Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + // We also rely on ImFontBaked* pointers never crossing frames. + ImFontAtlasBuilder* builder = atlas->Builder; + builder->FrameCount = frame_count; + for (ImFont* font : atlas->Fonts) + font->LastBaked = NULL; + + // Garbage collect BakedPool + if (builder->BakedDiscardedCount > 0) + { + int dst_n = 0, src_n = 0; + for (; src_n < builder->BakedPool.Size; src_n++) + { + ImFontBaked* p_src = &builder->BakedPool[src_n]; + if (p_src->WantDestroy) + continue; + ImFontBaked* p_dst = &builder->BakedPool[dst_n++]; + if (p_dst == p_src) + continue; + memcpy(p_dst, p_src, sizeof(ImFontBaked)); + builder->BakedMap.SetVoidPtr(p_dst->BakedId, p_dst); + } + IM_ASSERT(dst_n + builder->BakedDiscardedCount == src_n); + builder->BakedPool.Size -= builder->BakedDiscardedCount; + builder->BakedDiscardedCount = 0; + } + + // Update texture status + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + ImTextureData* tex = atlas->TexList[tex_n]; + bool remove_from_list = false; + if (tex->Status == ImTextureStatus_OK) + { + tex->Updates.resize(0); + tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; + tex->UpdateRect.w = tex->UpdateRect.h = 0; + } + if (tex->Status == ImTextureStatus_WantCreate && atlas->RendererHasTextures) + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture's TexID/BackendUserData but did not update Status to OK."); + + // Request destroy + // - Keep bool to true in order to differentiate a planned destroy vs a destroy decided by the backend. + // - We don't destroy pixels right away, as backend may have an in-flight copy from RAM. + if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_Destroyed && tex->Status != ImTextureStatus_WantDestroy) + { + IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); + tex->Status = ImTextureStatus_WantDestroy; + } + + // If a texture has never reached the backend, they don't need to know about it. + // (note: backends between 1.92.0 and 1.92.4 could set an already destroyed texture to ImTextureStatus_WantDestroy + // when invalidating graphics objects twice, which would previously remove it from the list and crash.) + if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) + tex->Status = ImTextureStatus_Destroyed; + + // Process texture being destroyed + if (tex->Status == ImTextureStatus_Destroyed) + { + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!"); + if (tex->WantDestroyNextFrame) + remove_from_list = true; // Destroy was scheduled by us + else + tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend: recreate it (e.g. freed resources mid-run) + } + + // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering. + // We allow the texture staying in _WantDestroy state and increment a counter which the backend can use to take its decision. + if (tex->Status == ImTextureStatus_WantDestroy) + tex->UnusedFrames++; + + // Destroy and remove + if (remove_from_list) + { + IM_ASSERT(atlas->TexData != tex); + tex->DestroyPixels(); + IM_DELETE(tex); + atlas->TexList.erase(atlas->TexList.begin() + tex_n); + tex_n--; + } + } +} + +void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h) +{ + IM_ASSERT(src_pixels != NULL && dst_pixels != NULL); + if (src_fmt == dst_fmt) + { + int line_sz = w * ImTextureDataGetFormatBytesPerPixel(src_fmt); + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + memcpy(dst_pixels, src_pixels, line_sz); + } + else if (src_fmt == ImTextureFormat_Alpha8 && dst_fmt == ImTextureFormat_RGBA32) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU8* src_p = (const ImU8*)src_pixels; + ImU32* dst_p = (ImU32*)(void*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = IM_COL32(255, 255, 255, (unsigned int)(*src_p++)); + } + } + else if (src_fmt == ImTextureFormat_RGBA32 && dst_fmt == ImTextureFormat_Alpha8) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU32* src_p = (const ImU32*)(void*)src_pixels; + ImU8* dst_p = (ImU8*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = ((*src_p++) >> IM_COL32_A_SHIFT) & 0xFF; + } + } + else + { + IM_ASSERT(0); + } +} + +// Source buffer may be written to (used for in-place mods). +// Post-process hooks may eventually be added here. +void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) +{ + // Multiply operator (legacy) + if (data->FontSrc->RasterizerMultiply != 1.0f) + ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply); +} + +void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor) +{ + unsigned char* pixels = (unsigned char*)data->Pixels; + int pitch = data->Pitch; + if (data->Format == ImTextureFormat_Alpha8) + { + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) + { + ImU8* p = (ImU8*)pixels; + for (int nx = data->Width; nx > 0; nx--, p++) + { + unsigned int v = ImMin((unsigned int)(*p * multiply_factor), (unsigned int)255); + *p = (unsigned char)v; + } + } + } + else if (data->Format == ImTextureFormat_RGBA32) //-V547 + { + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) + { + ImU32* p = (ImU32*)(void*)pixels; + for (int nx = data->Width; nx > 0; nx--, p++) + { + unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * multiply_factor), (unsigned int)255); + *p = IM_COL32((*p >> IM_COL32_R_SHIFT) & 0xFF, (*p >> IM_COL32_G_SHIFT) & 0xFF, (*p >> IM_COL32_B_SHIFT) & 0xFF, a); + } + } + } + else + { + IM_ASSERT(0); + } +} + +// Fill with single color. We don't use this directly but it is convenient for anyone working on uploading custom rects. +void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col) +{ + if (dst_tex->Format == ImTextureFormat_Alpha8) + { + ImU8 col_a = (col >> IM_COL32_A_SHIFT) & 0xFF; + for (int y = 0; y < h; y++) + memset((ImU8*)dst_tex->GetPixelsAt(dst_x, dst_y + y), col_a, w); + } + else + { + for (int y = 0; y < h; y++) + { + ImU32* p = (ImU32*)(void*)dst_tex->GetPixelsAt(dst_x, dst_y + y); + for (int x = w; x > 0; x--, p++) + *p = col; + } + } +} + +// Copy block from one texture to another +void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h) +{ + IM_ASSERT(src_tex->Pixels != NULL && dst_tex->Pixels != NULL); + IM_ASSERT(src_tex->Format == dst_tex->Format); + IM_ASSERT(src_x >= 0 && src_x + w <= src_tex->Width); + IM_ASSERT(src_y >= 0 && src_y + h <= src_tex->Height); + IM_ASSERT(dst_x >= 0 && dst_x + w <= dst_tex->Width); + IM_ASSERT(dst_y >= 0 && dst_y + h <= dst_tex->Height); + for (int y = 0; y < h; y++) + memcpy(dst_tex->GetPixelsAt(dst_x, dst_y + y), src_tex->GetPixelsAt(src_x, src_y + y), w * dst_tex->BytesPerPixel); +} + +// Queue texture block update for renderer backend +void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h) +{ + IM_ASSERT(tex->Status != ImTextureStatus_WantDestroy && tex->Status != ImTextureStatus_Destroyed); + IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000); + IM_UNUSED(atlas); + + ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h }; + int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w); + int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h); + tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x); + tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); + tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); + tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + tex->UsedRect.x = ImMin(tex->UsedRect.x, req.x); + tex->UsedRect.y = ImMin(tex->UsedRect.y, req.y); + tex->UsedRect.w = (unsigned short)(ImMax(tex->UsedRect.x + tex->UsedRect.w, req.x + req.w) - tex->UsedRect.x); + tex->UsedRect.h = (unsigned short)(ImMax(tex->UsedRect.y + tex->UsedRect.h, req.y + req.h) - tex->UsedRect.y); + atlas->TexIsBuilt = false; + + // No need to queue if status is == ImTextureStatus_WantCreate + if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) + { + tex->Status = ImTextureStatus_WantUpdates; + tex->Updates.push_back(req); + } +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +static void GetTexDataAsFormat(ImFontAtlas* atlas, ImTextureFormat format, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + ImTextureData* tex = atlas->TexData; + if (!atlas->TexIsBuilt || tex == NULL || tex->Pixels == NULL || atlas->TexDesiredFormat != format) + { + atlas->TexDesiredFormat = format; + atlas->Build(); + tex = atlas->TexData; + } + if (out_pixels) { *out_pixels = (unsigned char*)tex->Pixels; }; + if (out_width) { *out_width = tex->Width; }; + if (out_height) { *out_height = tex->Height; }; + if (out_bytes_per_pixel) { *out_bytes_per_pixel = tex->BytesPerPixel; } +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_Alpha8, out_pixels, out_width, out_height, out_bytes_per_pixel); +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_RGBA32, out_pixels, out_width, out_height, out_bytes_per_pixel); +} + +bool ImFontAtlas::Build() +{ + ImFontAtlasBuildMain(this); + return true; +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) +{ + // Sanity Checks + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + IM_ASSERT((font_cfg_in->FontData != NULL && font_cfg_in->FontDataSize > 0) || (font_cfg_in->FontLoader != NULL)); + //IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); + IM_ASSERT(font_cfg_in->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + if (font_cfg_in->GlyphOffset.x != 0.0f || font_cfg_in->GlyphOffset.y != 0.0f || font_cfg_in->GlyphMinAdvanceX != 0.0f || font_cfg_in->GlyphMaxAdvanceX != FLT_MAX) + IM_ASSERT(font_cfg_in->SizePixels != 0.0f && "Specifying glyph offset/advances requires a reference size to base it on."); + + // Lazily create builder on the first call to AddFont + if (Builder == NULL) + ImFontAtlasBuildInit(this); + + // Create new font + const bool is_first_font = (Fonts.Size == 0); + ImFont* font; + if (!font_cfg_in->MergeMode) + { + font = IM_NEW(ImFont)(); + font->FontId = FontNextUniqueID++; + font->Flags = font_cfg_in->Flags; + font->LegacySize = font_cfg_in->SizePixels; + font->CurrentRasterizerDensity = font_cfg_in->RasterizerDensity; + Fonts.push_back(font); + } + else + { + IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. + font = font_cfg_in->DstFont ? font_cfg_in->DstFont : Fonts.back(); + ImFontAtlasFontDiscardBakes(this, font, 0); // Need to discard bakes if the font was already used, because baked->FontLoaderDatas[] will change size. (#9162) + } + + // Add to list + Sources.push_back(*font_cfg_in); + ImFontConfig* font_cfg = &Sources.back(); + if (font_cfg->DstFont == NULL) + font_cfg->DstFont = font; + font->Sources.push_back(font_cfg); + ImFontAtlasBuildUpdatePointers(this); // Pointers to Sources are otherwise dangling after we called Sources.push_back(). + + // Sanity check + // We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. + if (font_cfg->GlyphExcludeRanges != NULL) + { + int size = 0; + for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {} + IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); + IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); + font_cfg->GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); + } + if (font_cfg->FontLoader != NULL) + { + IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet. + } + IM_ASSERT(font_cfg->FontLoaderData == NULL); + + if (!ImFontAtlasFontSourceInit(this, font_cfg)) + { + // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) + ImFontAtlasFontDestroySourceData(this, font_cfg); + Sources.pop_back(); + font->Sources.pop_back(); + if (!font_cfg->MergeMode) + { + IM_DELETE(font); + Fonts.pop_back(); + } + return NULL; + } + ImFontAtlasFontSourceAddToFont(this, font, font_cfg); + + if (is_first_font) + ImFontAtlasBuildNotifySetFont(this, NULL, font); + return font; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(const unsigned char* input); +static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. + src += 5; + dst += 4; + } +} +#ifndef IMGUI_DISABLE_DEFAULT_FONT +static const char* GetDefaultCompressedFontDataProggyClean(int* out_size); +static const char* GetDefaultCompressedFontDataProggyVector(int* out_size); +#endif + +// This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. +static float GetExpectedContextFontSize(ImGuiContext* ctx) +{ + return ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi; +} + +// Legacy function with heuristic to select Pixel or Vector font. +// The selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold at the time of adding the default font. +// Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) +{ + if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 16.0f) + return AddFontDefaultVector(font_cfg); + else + return AddFontDefaultBitmap(font_cfg); +} + +// Load embedded ProggyClean.ttf. Default size 13, disable oversampling. +// If you want a similar font which may be better scaled, consider using AddFontDefaultVector(). +ImFont* ImFontAtlas::AddFontDefaultBitmap(const ImFontConfig* font_cfg_template) +{ +#ifndef IMGUI_DISABLE_DEFAULT_FONT + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.SizePixels <= 0.0f) + font_cfg.SizePixels = 13.0f; // This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. + if (font_cfg.Name[0] == '\0') + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyClean.ttf"); + font_cfg.EllipsisChar = (ImWchar)0x0085; + font_cfg.GlyphOffset.y += 1.0f * (font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units + + int ttf_compressed_size = 0; + const char* ttf_compressed = GetDefaultCompressedFontDataProggyClean(&ttf_compressed_size); + return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); +#else + IM_ASSERT(0 && "Function is disabled in this build."); + IM_UNUSED(font_cfg_template); + return NULL; +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT +} + +// Load a minimal version of ProggyVector, designed to match our good old ProggyClean, but nicely scalable. +// (See misc/fonts/ProggyVector-ExtractScript.txt for details) +ImFont* ImFontAtlas::AddFontDefaultVector(const ImFontConfig* font_cfg_template) +{ +#ifndef IMGUI_DISABLE_DEFAULT_FONT + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.SizePixels <= 0.0f) + font_cfg.SizePixels = 16.0f; + if (font_cfg.Name[0] == '\0') + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyVector.ttf"); + font_cfg.ExtraSizeScale = 1.140f; // Match ProggyClean + font_cfg.GlyphOffset.y += -0.5f * (font_cfg.SizePixels / 13.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). + + int ttf_compressed_size = 0; + const char* ttf_compressed = GetDefaultCompressedFontDataProggyVector(&ttf_compressed_size); + return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); +#else + IM_ASSERT(0 && "Function is disabled in this build."); + IM_UNUSED(font_cfg_template); + return NULL; +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + size_t data_size = 0; + void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); + if (!data) + { + if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0) + { + IMGUI_DEBUG_LOG("While loading '%s'\n", filename); + IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + } + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + ImStrlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "%s", p); + } + return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + IM_ASSERT(font_data_size > 100 && "Incorrect value for font_data_size!"); // Heuristic to prevent accidentally passing a wrong value to font_data_size. + font_cfg.FontData = font_data; + font_cfg.FontDataSize = font_data_size; + font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char*)IM_ALLOC(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)ImStrlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + IM_FREE(compressed_ttf); + return font; +} + +// On font removal we need to remove references (otherwise we could queue removal?) +// We allow old_font == new_font which forces updating all values (e.g. sizes) +void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + { + if (shared_data->Font == old_font) + shared_data->Font = new_font; + if (ImGuiContext* ctx = shared_data->Context) + { + if (ctx->FrameCount == 0 && old_font == NULL) // While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. + continue; + + if (ctx->IO.FontDefault == old_font) + ctx->IO.FontDefault = new_font; + if (ctx->Font == old_font) + { + ImGuiContext* curr_ctx = ImGui::GetCurrentContext(); + bool need_bind_ctx = ctx != curr_ctx; + if (need_bind_ctx) + ImGui::SetCurrentContext(ctx); + ImGui::SetCurrentFont(new_font, ctx->FontSizeBase, ctx->FontSize); + if (need_bind_ctx) + ImGui::SetCurrentContext(curr_ctx); + } + for (ImFontStackData& font_stack_data : ctx->FontStack) + if (font_stack_data.Font == old_font) + font_stack_data.Font = new_font; + } + } +} + +void ImFontAtlas::RemoveFont(ImFont* font) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + + ImFontAtlasFontDestroyOutput(this, font); + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontDestroySourceData(this, src); + for (int src_n = 0; src_n < Sources.Size; src_n++) + if (Sources[src_n].DstFont == font) + Sources.erase(&Sources[src_n--]); + + bool removed = Fonts.find_erase(font); + IM_ASSERT(removed); + IM_UNUSED(removed); + + ImFontAtlasBuildUpdatePointers(this); + + font->OwnerAtlas = NULL; + IM_DELETE(font); + + // Notify external systems + ImFont* new_current_font = Fonts.empty() ? NULL : Fonts[0]; + ImFontAtlasBuildNotifySetFont(this, font, new_current_font); +} + +// At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'ImFontAtlasRect* out_r = NULL' argument to retrieve the info straight away. +ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height, ImFontAtlasRect* out_r) +{ + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + + if (Builder == NULL) + ImFontAtlasBuildInit(this); + + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; + if (out_r != NULL) + GetCustomRect(r_id, out_r); + + if (RendererHasTextures) + { + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + } + return r_id; +} + +void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) +{ + if (ImFontAtlasPackGetRectSafe(this, id) == NULL) + return; + ImFontAtlasPackDiscardRect(this, id); +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// This API does not make sense anymore with scalable fonts. +// - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. +// - You may use ImFontFlags_LockBakedSizes to limit an existing font to known baked sizes: +// ImFont* myfont = io.Fonts->AddFontFromFileTTF(....); +// myfont->GetFontBaked(16.0f); +// myfont->Flags |= ImFontFlags_LockBakedSizes; +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +{ + float font_size = font->LegacySize; + return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); +} +// FIXME: we automatically set glyph.Colored=true by default. +// If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph(). +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +{ +#ifdef IMGUI_USE_WCHAR32 + IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX); +#endif + IM_ASSERT(font != NULL); + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + + ImFontBaked* baked = font->GetFontBaked(font_size); + + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); + if (RendererHasTextures) + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + + if (baked->IsGlyphLoaded(codepoint)) + ImFontAtlasBakedDiscardFontGlyph(this, font, baked, baked->FindGlyph(codepoint)); + + ImFontGlyph glyph; + glyph.Codepoint = codepoint; + glyph.AdvanceX = advance_x; + glyph.X0 = offset.x; + glyph.Y0 = offset.y; + glyph.X1 = offset.x + r->w; + glyph.Y1 = offset.y + r->h; + glyph.Visible = true; + glyph.Colored = true; // FIXME: Arbitrary + glyph.PackId = r_id; + ImFontAtlasBakedAddFontGlyph(this, baked, font->Sources[0], &glyph); + return r_id; +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +bool ImFontAtlas::GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const +{ + ImTextureRect* r = ImFontAtlasPackGetRectSafe((ImFontAtlas*)this, id); + if (r == NULL) + return false; + IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates + if (out_r == NULL) + return true; + out_r->x = r->x; + out_r->y = r->y; + out_r->w = r->w; + out_r->h = r->h; + out_r->uv0 = ImVec2((float)(r->x), (float)(r->y)) * TexUvScale; + out_r->uv1 = ImVec2((float)(r->x + r->w), (float)(r->y + r->h)) * TexUvScale; + return true; +} + +bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) +{ + if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT) + return false; + if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) + return false; + + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->PackIdMouseCursors); + ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->x, (float)r->y); + ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; + *out_size = size; + *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; + out_uv_border[0] = (pos) * atlas->TexUvScale; + out_uv_border[1] = (pos + size) * atlas->TexUvScale; + pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + out_uv_fill[0] = (pos) * atlas->TexUvScale; + out_uv_fill[1] = (pos + size) * atlas->TexUvScale; + return true; +} + +// When atlas->RendererHasTextures = true, this is only called if no font were loaded. +void ImFontAtlasBuildMain(ImFontAtlas* atlas) +{ + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); + if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) + ImFontAtlasBuildClear(atlas); + + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); + + // Default font is none are specified + if (atlas->Sources.Size == 0) + atlas->AddFontDefault(); + + // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas); + atlas->TexIsBuilt = true; +} + +void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v) +{ + // (Only used by stb_truetype builder) + // Automatically disable horizontal oversampling over size 36 + const float raster_size = baked->Size * baked->RasterizerDensity * src->RasterizerDensity; + *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (raster_size > 36.0f || src->PixelSnapH) ? 1 : 2; + *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; +} + +// Setup main font loader for the atlas +// Every font source (ImFontConfig) will use this unless ImFontConfig::FontLoader specify a custom loader. +void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader) +{ + if (atlas->FontLoader == font_loader) + return; + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); + + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + atlas->FontLoader->LoaderShutdown(atlas); + + atlas->FontLoader = font_loader; + atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; + IM_ASSERT(atlas->FontLoaderData == NULL); + + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontInitOutput(atlas, font); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); +} + +// Preload all glyph ranges for legacy backends. +// This may lead to multiple texture creation which might be a little slower than before. +void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas) +{ + atlas->Builder->PreloadedAllGlyphsRanges = true; + for (ImFont* font : atlas->Fonts) + { + ImFontBaked* baked = font->GetFontBaked(font->LegacySize); + if (font->FallbackChar != 0) + baked->FindGlyph(font->FallbackChar); + if (font->EllipsisChar != 0) + baked->FindGlyph(font->EllipsisChar); + for (ImFontConfig* src : font->Sources) + { + const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + baked->FindGlyph((ImWchar)c); + } + } +} + +// FIXME: May make ImFont::Sources a ImSpan<> and move ownership to ImFontAtlas +void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) +{ + for (ImFont* font : atlas->Fonts) + font->Sources.resize(0); + for (ImFontConfig& src : atlas->Sources) + src.DstFont->Sources.push_back(&src); +} + +// Render a white-colored bitmap encoded in a string +void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char) +{ + ImTextureData* tex = atlas->TexData; + IM_ASSERT(x >= 0 && x + w <= tex->Width); + IM_ASSERT(y >= 0 && y + h <= tex->Height); + + switch (tex->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? 0xFF : 0x00; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? IM_COL32_WHITE : IM_COL32_BLACK_TRANS; + break; + } + } +} + +static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas) +{ + // Pack and store identifier so we can refresh UV coordinates on texture resize. + // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing. + ImFontAtlasBuilder* builder = atlas->Builder; + ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + + ImFontAtlasRect r; + bool add_and_draw = (atlas->GetCustomRect(builder->PackIdMouseCursors, &r) == false); + if (add_and_draw) + { + builder->PackIdMouseCursors = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdMouseCursors != ImFontAtlasRectId_Invalid); + + // Draw to texture + if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) + { + // 2x2 white pixels + ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, "XX" "XX", 'X'); + } + else + { + // 2x2 white pixels + mouse cursors + const int x_for_white = r.x; + const int x_for_black = r.x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); + } + } + + // Refresh UV coordinates + atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); +} + +static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) +{ + if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) + return; + + // Pack and store identifier so we can refresh UV coordinates on texture resize. + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + ImFontAtlasRect r; + bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; + if (add_and_draw) + { + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); + } + + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row + { + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + const int y = n; + const int line_width = n; + const int pad_left = (r.w - line_width) / 2; + const int pad_right = r.w - (pad_left + line_width); + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels + + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; + + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; + + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; + + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + } +} + +//----------------------------------------------------------------------------------------------------------------------------- + +// Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() +bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) +{ + bool ret = true; + for (ImFontConfig* src : font->Sources) + if (!ImFontAtlasFontSourceInit(atlas, src)) + ret = false; + IM_ASSERT(ret); // Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. + return ret; +} + +// Keep source/input FontData +void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) +{ + font->ClearOutputData(); + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(atlas, src); + } +} + +void ImFontAtlasFontRebuildOutput(ImFontAtlas* atlas, ImFont* font) +{ + ImFontAtlasFontDestroyOutput(atlas, font); + ImFontAtlasFontInitOutput(atlas, font); +} + +//----------------------------------------------------------------------------------------------------------------------------- + +bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + return false; + return true; +} + +void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) +{ + if (src->MergeMode == false) + { + font->ClearOutputData(); + //font->FontSize = src->SizePixels; + font->OwnerAtlas = atlas; + IM_ASSERT(font->Sources[0] == src); + } + atlas->TexIsBuilt = false; // For legacy backends + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); +} + +void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + // IF YOU GET A CRASH IN THE IM_FREE() CALL HERE AND USED AddFontFromMemoryTTF(): + // - DUE TO LEGACY REASON AddFontFromMemoryTTF() TRANSFERS MEMORY OWNERSHIP BY DEFAULT. + // - IT WILL THEREFORE CRASH WHEN PASSED DATA WHICH MAY NOT BE FREEED BY IMGUI. + // - USE `ImFontConfig font_cfg; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(....., &cfg);` to disable passing ownership/ + // WE WILL ADDRESS THIS IN A FUTURE REWORK OF THE API. + if (src->FontDataOwnedByAtlas) + IM_FREE(src->FontData); + src->FontData = NULL; + if (src->GlyphExcludeRanges) + IM_FREE((void*)src->GlyphExcludeRanges); + src->GlyphExcludeRanges = NULL; +} + +// Create a compact, baked "..." if it doesn't exist, by using the ".". +// This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. +// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers. +static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked) +{ + ImFont* font = baked->OwnerFont; + IM_ASSERT(font->EllipsisChar != 0); + + const ImFontGlyph* dot_glyph = baked->FindGlyphNoFallback((ImWchar)'.'); + if (dot_glyph == NULL) + dot_glyph = baked->FindGlyphNoFallback((ImWchar)0xFF0E); + if (dot_glyph == NULL) + return NULL; + ImFontAtlasRectId dot_r_id = dot_glyph->PackId; // Deep copy to avoid invalidation of glyphs and rect pointers + ImTextureRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); + const int dot_spacing = 1; + const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; + + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + + ImFontGlyph glyph_in = {}; + ImFontGlyph* glyph = &glyph_in; + glyph->Codepoint = font->EllipsisChar; + glyph->AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. + glyph->X0 = dot_glyph->X0; + glyph->Y0 = dot_glyph->Y0; + glyph->X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; + glyph->Y1 = dot_glyph->Y1; + glyph->Visible = true; + glyph->PackId = pack_id; + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, glyph); + dot_glyph = NULL; // Invalidated + + // Copy to texture, post-process and queue update for backend + // FIXME-NEWATLAS-V2: Dot glyph is already post-processed as this point, so this would damage it. + dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); + ImTextureData* tex = atlas->TexData; + for (int n = 0; n < 3; n++) + ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + + return glyph; +} + +// Load fallback in order to obtain its index +// (this is called from in hot-path so we avoid extraneous parameters to minimize impact on code size) +static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked) +{ + IM_ASSERT(baked->FallbackGlyphIndex == -1); + IM_ASSERT(baked->FallbackAdvanceX == 0.0f); + ImFont* font = baked->OwnerFont; + ImFontGlyph* fallback_glyph = NULL; + if (font->FallbackChar != 0) + fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar); + if (fallback_glyph == NULL) + { + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); + ImFontGlyph glyph; + glyph.Codepoint = 0; + glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f); + fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->OwnerAtlas, baked, NULL, &glyph); + } + baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code + baked->FallbackAdvanceX = fallback_glyph->AdvanceX; +} + +static void ImFontAtlasBuildSetupFontBakedBlanks(ImFontAtlas* atlas, ImFontBaked* baked) +{ + // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); + if (space_glyph != NULL) + space_glyph->Visible = false; + + // Setup Tab character. + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (baked->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) + { + ImFontGlyph tab_glyph; + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; + ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &tab_glyph); + } +} + +// Load/identify special glyphs +// (note that this is called again for fonts with MergeMode) +void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) +{ + IM_UNUSED(atlas); + IM_ASSERT(font->Sources.contains(src)); + + // Find Fallback character. Actual glyph loaded in GetFontBaked(). + const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; + if (font->FallbackChar == 0) + for (ImWchar candidate_char : fallback_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) + { + font->FallbackChar = (ImWchar)candidate_char; + break; + } + + // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). + // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. + // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. + const ImWchar ellipsis_chars[] = { src->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; + if (font->EllipsisChar == 0) + for (ImWchar candidate_char : ellipsis_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) + { + font->EllipsisChar = candidate_char; + break; + } + if (font->EllipsisChar == 0) + { + font->EllipsisChar = 0x0085; + font->EllipsisAutoBake = true; + } +} + +void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) +{ + if (glyph->PackId != ImFontAtlasRectId_Invalid) + { + ImFontAtlasPackDiscardRect(atlas, glyph->PackId); + glyph->PackId = ImFontAtlasRectId_Invalid; + } + ImWchar c = (ImWchar)glyph->Codepoint; + IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity + IM_ASSERT(glyph >= baked->Glyphs.Data && glyph < baked->Glyphs.Data + baked->Glyphs.Size); + IM_UNUSED(font); + baked->IndexLookup[c] = IM_FONTGLYPH_INDEX_UNUSED; + baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; +} + +ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id) +{ + IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size); + ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); + baked->Size = font_size; + baked->RasterizerDensity = font_rasterizer_density; + baked->BakedId = baked_id; + baked->OwnerFont = font; + baked->LastUsedFrame = atlas->Builder->FrameCount; + + // Initialize backend data + size_t loader_data_size = 0; + for (ImFontConfig* src : font->Sources) // Cannot easily be cached as we allow changing backend + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + loader_data_size += loader->FontBakedSrcLoaderDataSize; + } + baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL; + char* loader_data_p = (char*)baked->FontLoaderDatas; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedInit) + loader->FontBakedInit(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; + } + + ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked); + return baked; +} + +// FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case. +ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + for (int step_n = 0; step_n < 2; step_n++) + { + ImFontBaked* closest_larger_match = NULL; + ImFontBaked* closest_smaller_match = NULL; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->OwnerFont != font || baked->WantDestroy) + continue; + if (step_n == 0 && baked->RasterizerDensity != font_rasterizer_density) // First try with same density + continue; + if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) + closest_larger_match = baked; + if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) + closest_smaller_match = baked; + } + if (closest_larger_match) + if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f)) + return closest_larger_match; + if (closest_smaller_match) + return closest_smaller_match; + } + return NULL; +} + +void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); + + for (ImFontGlyph& glyph : baked->Glyphs) + if (glyph.PackId != ImFontAtlasRectId_Invalid) + ImFontAtlasPackDiscardRect(atlas, glyph.PackId); + + char* loader_data_p = (char*)baked->FontLoaderDatas; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedDestroy) + loader->FontBakedDestroy(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; + } + if (baked->FontLoaderDatas) + { + IM_FREE(baked->FontLoaderDatas); + baked->FontLoaderDatas = NULL; + } + builder->BakedMap.SetVoidPtr(baked->BakedId, NULL); + builder->BakedDiscardedCount++; + baked->ClearOutputData(); + baked->WantDestroy = true; + font->LastBaked = NULL; +} + +// use unused_frames==0 to discard everything. +void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames) +{ + if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->OwnerFont != font || baked->WantDestroy) + continue; + ImFontAtlasBakedDiscard(atlas, font, baked); + } +} + +// use unused_frames==0 to discard everything. +void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->WantDestroy || (baked->OwnerFont->Flags & ImFontFlags_LockBakedSizes)) + continue; + ImFontAtlasBakedDiscard(atlas, baked->OwnerFont, baked); + } +} + +// Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* +void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(!atlas->DrawListSharedDatas.contains(data)); + atlas->DrawListSharedDatas.push_back(data); +} + +void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(atlas->DrawListSharedDatas.contains(data)); + atlas->DrawListSharedDatas.find_erase(data); +} + +// Update texture identifier in all active draw lists +void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + { + // If Context 2 uses font owned by Context 1 which already called EndFrame()/Render(), we don't want to mess with draw commands for Context 1 + if (shared_data->Context && !shared_data->Context->WithinFrameScope) + continue; + + for (ImDrawList* draw_list : shared_data->DrawLists) + { + // Replace in command-buffer + // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[], + // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow) + if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex) + draw_list->_SetTexture(new_tex); + + // Replace in stack + for (ImTextureRef& stacked_tex : draw_list->_TextureStack) + if (stacked_tex == old_tex) + stacked_tex = new_tex; + } + } +} + +// Update texture coordinates in all draw list shared context +// FIXME-NEWATLAS FIXME-OPT: Doesn't seem necessary to update for all, only one bound to current context? +void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + if (shared_data->FontAtlas == atlas) + { + shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; + shared_data->TexUvLines = atlas->TexUvLines; + } +} + +// Set current texture. This is mostly called from AddTexture() + to handle a failed resize. +static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex) +{ + ImTextureRef old_tex_ref = atlas->TexRef; + atlas->TexData = tex; + atlas->TexUvScale = ImVec2(1.0f / tex->Width, 1.0f / tex->Height); + atlas->TexRef._TexData = tex; + //atlas->TexRef._TexID = tex->TexID; // <-- We intentionally don't do that. It would be misleading and betray promise that both fields aren't set. + ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, atlas->TexRef); +} + +// Create a new texture, discard previous one +ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h) +{ + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex; + + // FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + /*if (old_tex != NULL && old_tex->Status == ImTextureStatus_WantCreate) + { + // Reuse texture not yet used by backend. + IM_ASSERT(old_tex->TexID == ImTextureID_Invalid && old_tex->BackendUserData == NULL); + old_tex->DestroyPixels(); + old_tex->Updates.clear(); + new_tex = old_tex; + old_tex = NULL; + } + else*/ + { + // Add new + new_tex = IM_NEW(ImTextureData)(); + new_tex->UniqueID = atlas->TexNextUniqueID++; + atlas->TexList.push_back(new_tex); + } + if (old_tex != NULL) + { + // Queue old as to destroy next frame + old_tex->WantDestroyNextFrame = true; + IM_ASSERT(old_tex->Status == ImTextureStatus_OK || old_tex->Status == ImTextureStatus_WantCreate || old_tex->Status == ImTextureStatus_WantUpdates); + } + + new_tex->Create(atlas->TexDesiredFormat, w, h); + atlas->TexIsBuilt = false; + + ImFontAtlasBuildSetTexture(atlas, new_tex); + + return new_tex; +} + +#if 0 +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "../stb/stb_image_write.h" +static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* description) +{ + ImGuiContext& g = *GImGui; + char buf[128]; + ImFormatString(buf, IM_COUNTOF(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description); + stbi_write_png(buf, tex->Width, tex->Height, tex->BytesPerPixel, tex->Pixels, tex->GetPitch()); // tex->BytesPerPixel is technically not component, but ok for the formats we support. +} +#endif + +void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + builder->LockDisableResize = true; + + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex = ImFontAtlasTextureAdd(atlas, w, h); + new_tex->UseColors = old_tex->UseColors; + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); + //for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + // IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d\n", builder->BakedPool[baked_n].FontSize, builder->BakedPool[baked_n].Glyphs.Size, builder->BakedPool[baked_n].WantDestroy); + //IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px\n", builder->RectsPackedCount, builder->RectsPackedSurface); + //ImFontAtlasDebugWriteTexToDisk(old_tex, "Before Pack"); + + // Repack, lose discarded rectangle, copy pixels + // FIXME-NEWATLAS: This is unstable because packing order is based on RectsIndex + // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic, and fix stability. + // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. + ImFontAtlasPackInit(atlas); + ImVector old_rects; + ImVector old_index = builder->RectsIndex; + old_rects.swap(builder->Rects); + + for (ImFontAtlasRectEntry& index_entry : builder->RectsIndex) + { + if (index_entry.IsUsed == false) + continue; + ImTextureRect& old_r = old_rects[index_entry.TargetIndex]; + if (old_r.w == 0 && old_r.h == 0) + continue; + ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry); + if (new_r_id == ImFontAtlasRectId_Invalid) + { + // Undo, grow texture and try repacking again. + // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.\n", new_tex->UniqueID); + new_tex->WantDestroyNextFrame = true; + builder->Rects.swap(old_rects); + builder->RectsIndex = old_index; + ImFontAtlasBuildSetTexture(atlas, old_tex); + ImFontAtlasTextureGrow(atlas, w, h); // Recurse + return; + } + IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder->RectsIndex.index_from_ptr(&index_entry)); + ImTextureRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); + ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); + } + IM_ASSERT(old_rects.Size == builder->Rects.Size + builder->RectsDiscardedCount); + builder->RectsDiscardedCount = 0; + builder->RectsDiscardedSurface = 0; + + // Patch glyphs UV + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs) + if (glyph.PackId != ImFontAtlasRectId_Invalid) + { + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + } + + // Update other cached UV + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); + + builder->LockDisableResize = false; + ImFontAtlasUpdateDrawListsSharedData(atlas); + //ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); +} + +void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) +{ + //ImFontAtlasDebugWriteTexToDisk(atlas->TexData, "Before Grow"); + ImFontAtlasBuilder* builder = atlas->Builder; + if (old_tex_w == -1) + old_tex_w = atlas->TexData->Width; + if (old_tex_h == -1) + old_tex_h = atlas->TexData->Height; + + // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? + // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? + IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); + IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); + + // Grow texture so it follows roughly a square. + // - Grow height before width, as width imply more packing nodes. + // - Caller should be taking account of RectsDiscardedSurface and may not need to grow. + int new_tex_w = (old_tex_h <= old_tex_w) ? old_tex_w : old_tex_w * 2; + int new_tex_h = (old_tex_h <= old_tex_w) ? old_tex_h * 2 : old_tex_h; + + // Handle minimum size first (for pathologically large packed rects) + const int pack_padding = atlas->TexGlyphPadding; + new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + pack_padding)); + new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + pack_padding)); + new_tex_w = ImClamp(new_tex_w, atlas->TexMinWidth, atlas->TexMaxWidth); + new_tex_h = ImClamp(new_tex_h, atlas->TexMinHeight, atlas->TexMaxHeight); + if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) + return; + + ImFontAtlasTextureRepack(atlas, new_tex_w, new_tex_h); +} + +void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas) +{ + // Can some baked contents be ditched? + //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardBakes(atlas, 2); + + // Currently using a heuristic for repack without growing. + if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) + ImFontAtlasTextureGrow(atlas); + else + ImFontAtlasTextureRepack(atlas, atlas->TexData->Width, atlas->TexData->Height); +} + +ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas) +{ + int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth); + int min_h = ImUpperPowerOfTwo(atlas->TexMinHeight); + if (atlas->Builder == NULL || atlas->TexData == NULL || atlas->TexData->Status == ImTextureStatus_WantDestroy) + return ImVec2i(min_w, min_h); + + ImFontAtlasBuilder* builder = atlas->Builder; + min_w = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.x), min_w); + min_h = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.y), min_h); + const int surface_approx = builder->RectsPackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack + const int surface_sqrt = (int)sqrtf((float)surface_approx); + + int new_tex_w; + int new_tex_h; + if (min_w >= min_h) + { + new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt)); + new_tex_h = ImMax(min_h, (int)((surface_approx + new_tex_w - 1) / new_tex_w)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + } + else + { + new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h)); + } + + IM_ASSERT(ImIsPowerOfTwo(new_tex_w) && ImIsPowerOfTwo(new_tex_h)); + return ImVec2i(new_tex_w, new_tex_h); +} + +// Clear all output. Invalidates all AddCustomRect() return values! +void ImFontAtlasBuildClear(ImFontAtlas* atlas) +{ + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); + ImFontAtlasBuildDestroy(atlas); + ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasBuildInit(atlas); + for (ImFontConfig& src : atlas->Sources) + ImFontAtlasFontSourceInit(atlas, &src); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); +} + +// You should not need to call this manually! +// If you think you do, let us know and we can advise about policies auto-compact. +void ImFontAtlasTextureCompact(ImFontAtlas* atlas) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardBakes(atlas, 1); + + ImTextureData* old_tex = atlas->TexData; + ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); + if (builder->RectsDiscardedCount == 0 && new_tex_size.x == old_tex_size.x && new_tex_size.y == old_tex_size.y) + return; + + ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y); +} + +// Start packing over current empty texture +void ImFontAtlasBuildInit(ImFontAtlas* atlas) +{ + // Select Backend + // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which + // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are + // using a hot-reloading scheme that messes up static data, store your own instance of FontLoader somewhere + // and point to it instead of pointing directly to return value of the GetFontLoaderXXX functions. + if (atlas->FontLoader == NULL) + { +#ifdef IMGUI_ENABLE_FREETYPE + atlas->SetFontLoader(ImGuiFreeType::GetFontLoader()); +#elif defined(IMGUI_ENABLE_STB_TRUETYPE) + atlas->SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()); +#else + IM_ASSERT(0); // Invalid Build function +#endif + } + + // Create initial texture size + if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) + ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); + + atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + if (atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + + ImFontAtlasPackInit(atlas); + + // Add required texture data + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); + + // Register fonts + ImFontAtlasBuildUpdatePointers(atlas); + + // Update UV coordinates etc. stored in bound ImDrawListSharedData instance + ImFontAtlasUpdateDrawListsSharedData(atlas); + + //atlas->TexIsBuilt = true; + + // Lazily initialize char/text classifier + // FIXME: This could be practically anywhere, and should eventually be parameters to CalcTextSize/word-wrapping code, but there's no obvious spot now. + ImTextInitClassifiers(); +} + +// Destroy builder and all cached glyphs. Do not destroy actual fonts. +void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) +{ + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + { + atlas->FontLoader->LoaderShutdown(atlas); + IM_ASSERT(atlas->FontLoaderData == NULL); + } + IM_DELETE(atlas->Builder); + atlas->Builder = NULL; +} + +void ImFontAtlasPackInit(ImFontAtlas * atlas) +{ + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it. + const int pack_node_count = tex->Width / 2; + builder->PackNodes.resize(pack_node_count); + IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); + stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); + builder->RectsPackedSurface = builder->RectsPackedCount = 0; + builder->MaxRectSize = ImVec2i(0, 0); + builder->MaxRectBounds = ImVec2i(0, 0); +} + +// This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. +static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int rect_idx) +{ + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + int index_idx; + ImFontAtlasRectEntry* index_entry; + if (builder->RectsIndexFreeListStart < 0) + { + builder->RectsIndex.resize(builder->RectsIndex.Size + 1); + index_idx = builder->RectsIndex.Size - 1; + index_entry = &builder->RectsIndex[index_idx]; + memset(index_entry, 0, sizeof(*index_entry)); + } + else + { + index_idx = builder->RectsIndexFreeListStart; + index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->IsUsed == false && index_entry->Generation > 0); // Generation is incremented during DiscardRect + builder->RectsIndexFreeListStart = index_entry->TargetIndex; + } + index_entry->TargetIndex = rect_idx; + index_entry->IsUsed = 1; + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); +} + +// Overwrite existing entry +static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* index_entry) +{ + IM_ASSERT(index_entry->IsUsed); + index_entry->TargetIndex = atlas->Builder->Rects.Size - 1; + int index_idx = atlas->Builder->RectsIndex.index_from_ptr(index_entry); + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); +} + +// This is expected to be called in batches and followed by a repack +void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + IM_ASSERT(id != ImFontAtlasRectId_Invalid); + + ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id); + if (rect == NULL) + return; + + ImFontAtlasBuilder* builder = atlas->Builder; + int index_idx = ImFontAtlasRectId_GetIndex(id); + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0); + index_entry->IsUsed = false; + index_entry->TargetIndex = builder->RectsIndexFreeListStart; + index_entry->Generation++; + if (index_entry->Generation == 0) + index_entry->Generation++; // Keep non-zero on overflow + + const int pack_padding = atlas->TexGlyphPadding; + builder->RectsIndexFreeListStart = index_idx; + builder->RectsDiscardedCount++; + builder->RectsDiscardedSurface += (rect->w + pack_padding) * (rect->h + pack_padding); + rect->w = rect->h = 0; // Clear rectangle so it won't be packed again +} + +// Important: Calling this may recreate a new texture and therefore change atlas->TexData +// FIXME-NEWFONTS: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 +ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry) +{ + IM_ASSERT(w > 0 && w <= 0xFFFF); + IM_ASSERT(h > 0 && h <= 0xFFFF); + + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + const int pack_padding = atlas->TexGlyphPadding; + builder->MaxRectSize.x = ImMax(builder->MaxRectSize.x, w); + builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h); + + // Pack + ImTextureRect r = { 0, 0, (unsigned short)w, (unsigned short)h }; + for (int attempts_remaining = 3; attempts_remaining >= 0; attempts_remaining--) + { + // Try packing + stbrp_rect pack_r = {}; + pack_r.w = w + pack_padding; + pack_r.h = h + pack_padding; + stbrp_pack_rects((stbrp_context*)(void*)&builder->PackContext, &pack_r, 1); + r.x = (unsigned short)pack_r.x; + r.y = (unsigned short)pack_r.y; + if (pack_r.was_packed) + break; + + // If we ran out of attempts, return fallback + if (attempts_remaining == 0 || builder->LockDisableResize) + { + IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h); + return ImFontAtlasRectId_Invalid; + } + + // Resize or repack atlas! (this should be a rare event) + ImFontAtlasTextureMakeSpace(atlas); + } + + builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding); + builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h + pack_padding); + builder->RectsPackedCount++; + builder->RectsPackedSurface += (w + pack_padding) * (h + pack_padding); + + builder->Rects.push_back(r); + if (overwrite_entry != NULL) + return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry); // Write into an existing entry instead of adding one (used during repack) + else + return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); +} + +// Generally for non-user facing functions: assert on invalid ID. +ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + IM_ASSERT(id != ImFontAtlasRectId_Invalid); + int index_idx = ImFontAtlasRectId_GetIndex(id); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->Generation == ImFontAtlasRectId_GetGeneration(id)); + IM_ASSERT(index_entry->IsUsed); + return &builder->Rects[index_entry->TargetIndex]; +} + +// For user-facing functions: return NULL on invalid ID. +// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. +ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + if (id == ImFontAtlasRectId_Invalid) + return NULL; + int index_idx = ImFontAtlasRectId_GetIndex(id); + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + IM_MSVC_WARNING_SUPPRESS(28182); // Static Analysis false positive "warning C28182: Dereferencing NULL pointer 'builder'" + if (index_idx >= builder->RectsIndex.Size) + return NULL; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + if (index_entry->Generation != ImFontAtlasRectId_GetGeneration(id) || !index_entry->IsUsed) + return NULL; + return &builder->Rects[index_entry->TargetIndex]; +} + +// Important! This assume by ImFontConfig::GlyphExcludeRanges[] is a SMALL ARRAY (e.g. <10 entries) +// Use "Input Glyphs Overlap Detection Tool" to display a list of glyphs provided by multiple sources in order to set this array up. +static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) +{ + if (const ImWchar* exclude_list = src->GlyphExcludeRanges) + for (; exclude_list[0] != 0; exclude_list += 2) + if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1]) + return false; + return true; +} + +static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) +{ + IM_ASSERT(baked->IndexAdvanceX.Size == baked->IndexLookup.Size); + if (new_size <= baked->IndexLookup.Size) + return; + baked->IndexAdvanceX.resize(new_size, -1.0f); + baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); +} + +static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) +{ + IM_UNUSED(atlas); + if (font->RemapPairs.Data.Size != 0) + *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); +} + +static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) +{ + ImFont* font = baked->OwnerFont; + ImFontAtlas* atlas = font->OwnerAtlas; + if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) + { + // Lazily load fallback glyph + if (baked->FallbackGlyphIndex == -1 && baked->LoadNoFallback == 0) + ImFontAtlasBuildSetupFontBakedFallback(baked); + return NULL; + } + + // User remapping hooks + ImWchar src_codepoint = codepoint; + ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint); + + //char utf8_buf[5]; + //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); + + // Special hook + // FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking + if (codepoint == font->EllipsisChar && font->EllipsisAutoBake) + if (ImFontGlyph* glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)) + return glyph; + + // Call backend + char* loader_user_data_p = (char*)baked->FontLoaderDatas; + int src_n = 0; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + { + if (only_load_advance_x == NULL) + { + ImFontGlyph glyph_buf; + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + { + // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + } + } + else + { + // Special mode but only loading glyphs metrics. Will rasterize and pack later. + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + { + ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); + return NULL; + } + } + } + loader_user_data_p += loader->FontBakedSrcLoaderDataSize; + src_n++; + } + + // Lazily load fallback glyph + if (baked->LoadNoFallback) + return NULL; + if (baked->FallbackGlyphIndex == -1) + ImFontAtlasBuildSetupFontBakedFallback(baked); + + // Mark index as not found, so we don't attempt the search twice + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; + baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; + return NULL; +} + +static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) +{ + if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE || baked->LoadNoRenderOnLayout) + { + // First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. + float only_advance_x = 0.0f; + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, &only_advance_x); + return glyph ? glyph->AdvanceX : only_advance_x; + } + else + { + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, NULL); + return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX; + } +} + +// The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b +IM_MSVC_RUNTIME_CHECKS_OFF +static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* baked, unsigned int codepoint) +{ + return ImFontBaked_BuildLoadGlyphAdvanceX(baked, (ImWchar)codepoint); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) +{ + // [DEBUG] Log texture update requests + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + for (ImTextureData* tex : atlas->TexList) + { + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + IM_ASSERT(tex->Updates.Size == 0); + if (tex->Status == ImTextureStatus_WantCreate) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + else if (tex->Status == ImTextureStatus_WantDestroy) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, ImGui::DebugTextureIDToU64(tex->TexID), tex->BackendUserData); + else if (tex->Status == ImTextureStatus_WantUpdates) + { + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, ImGui::DebugTextureIDToU64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); + for (const ImTextureRect& r : tex->Updates) + { + IM_UNUSED(r); + IM_ASSERT(r.x >= 0 && r.y >= 0); + IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. + //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, ImGui::DebugTextureIDToU64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); + } + } + } +} +#endif + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas: backend for stb_truetype +//------------------------------------------------------------------------- +// (imstb_truetype.h in included near the top of this file, when IMGUI_ENABLE_STB_TRUETYPE is set) +//------------------------------------------------------------------------- + +#ifdef IMGUI_ENABLE_STB_TRUETYPE + +// One for each ConfigData +struct ImGui_ImplStbTrueType_FontSrcData +{ + stbtt_fontinfo FontInfo; + float ScaleFactor; +}; + +static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData); + IM_ASSERT(src->FontLoaderData == NULL); + + // Initialize helper structure for font loading and verify that the TTF/OTF data is correct + const int font_offset = stbtt_GetFontOffsetForIndex((const unsigned char*)src->FontData, src->FontNo); + if (font_offset < 0) + { + IM_DELETE(bd_font_data); + IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found."); + return false; + } + if (!stbtt_InitFont(&bd_font_data->FontInfo, (const unsigned char*)src->FontData, font_offset)) + { + IM_DELETE(bd_font_data); + IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); + return false; + } + src->FontLoaderData = bd_font_data; + + const float ref_size = src->DstFont->Sources[0]->SizePixels; + if (src->MergeMode && src->SizePixels == 0.0f) + src->SizePixels = ref_size; + + bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); + if (src->MergeMode && src->SizePixels != 0.0f && ref_size != 0.0f) + bd_font_data->ScaleFactor *= src->SizePixels / ref_size; // FIXME-NEWATLAS: Should tidy up that a bit + bd_font_data->ScaleFactor *= src->ExtraSizeScale; + + return true; +} + +static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_DELETE(bd_font_data); + src->FontLoaderData = NULL; +} + +static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data != NULL); + + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + return glyph_index != 0; +} + +static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + if (src->MergeMode == false) + { + // FIXME-NEWFONTS: reevaluate how to use sizing metrics + // FIXME-NEWFONTS: make use of line gap value + float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); + baked->Descent = ImFloor(unscaled_descent * scale_for_layout); + } + return true; +} + +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +{ + // Search for first font which has the glyph + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data); + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + if (glyph_index == 0) + return false; + + // Fonts unit to pixels + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); + const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_h; + const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_v; + + // Obtain size and advance + int x0, y0, x1, y1; + int advance, lsb; + stbtt_GetGlyphBitmapBoxSubpixel(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0, &x0, &y0, &x1, &y1); + stbtt_GetGlyphHMetrics(&bd_font_data->FontInfo, glyph_index, &advance, &lsb); + + // Load metrics only mode + if (out_advance_x != NULL) + { + IM_ASSERT(out_glyph == NULL); + *out_advance_x = advance * scale_for_layout; + return true; + } + + // Prepare glyph + out_glyph->Codepoint = codepoint; + out_glyph->AdvanceX = advance * scale_for_layout; + + // Pack and retrieve position inside texture atlas + // (generally based on stbtt_PackFontRangesRenderIntoRects) + const bool is_visible = (x0 != x1 && y0 != y1); + if (is_visible) + { + const int w = (x1 - x0 + oversample_h - 1); + const int h = (y1 - y0 + oversample_v - 1); + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + if (pack_id == ImFontAtlasRectId_Invalid) + { + // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) + IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); + return false; + } + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + + // Render + stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1); + ImFontAtlasBuilder* builder = atlas->Builder; + builder->TempBuffer.resize(w * h * 1); + unsigned char* bitmap_pixels = builder->TempBuffer.Data; + memset(bitmap_pixels, 0, w * h * 1); + + // Render with oversampling + // (those functions conveniently assert if pixels are not cleared, which is another safety layer) + float sub_x, sub_y; + stbtt_MakeGlyphBitmapSubpixelPrefilter(&bd_font_data->FontInfo, bitmap_pixels, w, h, w, + scale_for_raster_x, scale_for_raster_y, 0, 0, oversample_h, oversample_v, &sub_x, &sub_y, glyph_index); + + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + float font_off_x = ImFloor(src->GlyphOffset.x * offsets_scale + 0.5f); // Snap scaled offset. + float font_off_y = ImFloor(src->GlyphOffset.y * offsets_scale + 0.5f); + font_off_x += sub_x; + font_off_y += sub_y + IM_ROUND(baked->Ascent); + float recip_h = 1.0f / (oversample_h * rasterizer_density); + float recip_v = 1.0f / (oversample_v * rasterizer_density); + + // Register glyph + // r->x r->y are coordinates inside texture (in pixels) + // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling. + out_glyph->X0 = x0 * recip_h + font_off_x; + out_glyph->Y0 = y0 * recip_v + font_off_y; + out_glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x; + out_glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y; + out_glyph->Visible = true; + out_glyph->PackId = pack_id; + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w); + } + + return true; +} + +const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() +{ + static ImFontLoader loader; + loader.Name = "stb_truetype"; + loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; + loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; + loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; + loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; + loader.FontBakedDestroy = NULL; + loader.FontBakedLoadGlyph = ImGui_ImplStbTrueType_FontBakedLoadGlyph; + return &loader; +} + +#endif // IMGUI_ENABLE_STB_TRUETYPE + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas: glyph ranges helpers +//------------------------------------------------------------------------- +// - GetGlyphRangesDefault() +// Obsolete functions since 1.92: +// - GetGlyphRangesGreek() +// - GetGlyphRangesKorean() +// - GetGlyphRangesChineseFull() +// - GetGlyphRangesChineseSimplifiedCommon() +// - GetGlyphRangesJapanese() +// - GetGlyphRangesCyrillic() +// - GetGlyphRangesThai() +// - GetGlyphRangesVietnamese() +//----------------------------------------------------------------------------- + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +const ImWchar* ImFontAtlas::GetGlyphRangesGreek() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0370, 0x03FF, // Greek and Coptic + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD7A3, // Korean characters + 0xFFFD, 0xFFFD, // Invalid + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChineseFull() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x2000, 0x206F, // General Punctuation + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0xFFFD, 0xFFFD, // Invalid + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short* accumulative_offsets, int accumulative_offsets_count, ImWchar* out_ranges) +{ + for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2) + { + out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]); + base_codepoint += accumulative_offsets[n]; + } + out_ranges[0] = 0; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() +{ + // Store 2500 regularly used characters for Simplified Chinese. + // Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8 + // This table covers 97.97% of all characters used during the month in July, 1987. + // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2, + 1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4, + 2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1, + 1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2, + 3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6, + 1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1, + 1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3, + 2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4, + 27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12, + 3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1, + 1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23, + 176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6, + 5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6, + 1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1, + 6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5, + 2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15, + 2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6, + 2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4, + 3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5, + 3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2, + 3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16, + 1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31, + 140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7, + 5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2, + 2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13, + 4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3, + 2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4, + 4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1, + 3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3, + 3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11, + 2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9, + 5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2, + 3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3, + 1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12, + 4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8, + 4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5, + 26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1, + 3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5, + 2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6, + 10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6 + }; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x2000, 0x206F, // General Punctuation + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0xFFFD, 0xFFFD // Invalid + }; + static ImWchar full_ranges[IM_COUNTOF(base_ranges) + IM_COUNTOF(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 }; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_COUNTOF(accumulative_offsets_from_0x4E00), full_ranges + IM_COUNTOF(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // 2999 ideograms code points for Japanese + // - 2136 Joyo (meaning "for regular use" or "for common use") Kanji code points + // - 863 Jinmeiyo (meaning "for personal name") Kanji code points + // - Sourced from official information provided by the government agencies of Japan: + // - List of Joyo Kanji by the Agency for Cultural Affairs + // - https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kijun/naikaku/kanji/ + // - List of Jinmeiyo Kanji by the Ministry of Justice + // - http://www.moj.go.jp/MINJI/minji86.html + // - Available under the terms of the Creative Commons Attribution 4.0 International (CC BY 4.0). + // - https://creativecommons.org/licenses/by/4.0/legalcode + // - You can generate this code by the script at: + // - https://github.com/vaiorabbit/everyday_use_kanji + // - References: + // - List of Joyo Kanji + // - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji + // - List of Jinmeiyo Kanji + // - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji + // - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details. + // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1, + 1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3, + 2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8, + 2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5, + 2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1, + 1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30, + 2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3, + 13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4, + 5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14, + 2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1, + 1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1, + 7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1, + 1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1, + 6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2, + 10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7, + 2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5, + 3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1, + 6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7, + 4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2, + 4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5, + 1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6, + 12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2, + 1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16, + 22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11, + 2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18, + 18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9, + 14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3, + 1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6, + 40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1, + 12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8, + 2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1, + 1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10, + 1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5, + 3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2, + 14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5, + 12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1, + 2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5, + 1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4, + 3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7, + 2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5, + 13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13, + 18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21, + 37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1, + 5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38, + 32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4, + 1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4, + 4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1, + 3,2,1,1,1,1,2,1,1, + }; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0xFFFD, 0xFFFD // Invalid + }; + static ImWchar full_ranges[IM_COUNTOF(base_ranges) + IM_COUNTOF(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 }; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_COUNTOF(accumulative_offsets_from_0x4E00), full_ranges + IM_COUNTOF(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x2010, 0x205E, // Punctuations + 0x0E00, 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x0102, 0x0103, + 0x0110, 0x0111, + 0x0128, 0x0129, + 0x0168, 0x0169, + 0x01A0, 0x01A1, + 0x01AF, 0x01B0, + 0x1EA0, 0x1EF9, + 0, + }; + return &ranges[0]; +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//----------------------------------------------------------------------------- +// [SECTION] ImFontGlyphRangesBuilder +//----------------------------------------------------------------------------- + +void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end) +{ + if (text_end == NULL) + text_end = text + strlen(text); + while (text < text_end) + { + unsigned int c = 0; + int c_len = ImTextCharFromUtf8(&c, text, text_end); + text += c_len; + if (c_len == 0) + break; + AddChar((ImWchar)c); + } +} + +void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges) +{ + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + AddChar((ImWchar)c); +} + +void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) +{ + const int max_codepoint = IM_UNICODE_CODEPOINT_MAX; + for (int n = 0; n <= max_codepoint; n++) + if (GetBit(n)) + { + out_ranges->push_back((ImWchar)n); + while (n < max_codepoint && GetBit(n + 1)) + n++; + out_ranges->push_back((ImWchar)n); + } + out_ranges->push_back(0); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontBaked, ImFont +//----------------------------------------------------------------------------- + +ImFontBaked::ImFontBaked() +{ + memset(this, 0, sizeof(*this)); + FallbackGlyphIndex = -1; +} + +void ImFontBaked::ClearOutputData() +{ + FallbackAdvanceX = 0.0f; + Glyphs.clear(); + IndexAdvanceX.clear(); + IndexLookup.clear(); + FallbackGlyphIndex = -1; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + +ImFont::ImFont() +{ + memset(this, 0, sizeof(*this)); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + Scale = 1.0f; +#endif +} + +ImFont::~ImFont() +{ + ClearOutputData(); +} + +void ImFont::ClearOutputData() +{ + if (ImFontAtlas* atlas = OwnerAtlas) + ImFontAtlasFontDiscardBakes(atlas, this, 0); + //FallbackChar = EllipsisChar = 0; + memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); + LastBaked = NULL; +} + +// API is designed this way to avoid exposing the 8K page size +// e.g. use with IsGlyphRangeUnused(0, 255) +bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) +{ + unsigned int page_begin = (c_begin / 8192); + unsigned int page_last = (c_last / 8192); + for (unsigned int page_n = page_begin; page_n <= page_last; page_n++) + if ((page_n >> 3) < sizeof(Used8kPagesMap)) + if (Used8kPagesMap[page_n >> 3] & (1 << (page_n & 7))) + return false; + return true; +} + +// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. +// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). +// - 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. +ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph) +{ + int glyph_idx = baked->Glyphs.Size; + baked->Glyphs.push_back(*in_glyph); + ImFontGlyph* glyph = &baked->Glyphs[glyph_idx]; + IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + + // Set UV from packed rectangle + if (glyph->PackId != ImFontAtlasRectId_Invalid) + { + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph->PackId); + IM_ASSERT(glyph->U0 == 0.0f && glyph->V0 == 0.0f && glyph->U1 == 0.0f && glyph->V1 == 0.0f); + glyph->U0 = (r->x) * atlas->TexUvScale.x; + glyph->V0 = (r->y) * atlas->TexUvScale.y; + glyph->U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph->V1 = (r->y + r->h) * atlas->TexUvScale.y; + baked->MetricsTotalSurface += r->w * r->h; + } + + if (src != NULL) + { + // Clamp & recenter if needed + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + if (advance_x != glyph->AdvanceX) + { + float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph->AdvanceX) * 0.5f) : (advance_x - glyph->AdvanceX) * 0.5f; + glyph->X0 += char_off_x; + glyph->X1 += char_off_x; + } + + // Snap to pixel + if (src->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + glyph->AdvanceX = advance_x + src->GlyphExtraAdvanceX; + } + if (glyph->Colored) + atlas->TexPixelsUseColors = atlas->TexData->UseColors = true; + + // Update lookup tables + const int codepoint = glyph->Codepoint; + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = glyph->AdvanceX; + baked->IndexLookup[codepoint] = (ImU16)glyph_idx; + const int page_n = codepoint / 8192; + baked->OwnerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + + return glyph; +} + +// FIXME: Code is duplicated with code above. +void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x) +{ + IM_UNUSED(atlas); + if (src != NULL) + { + // Clamp & recenter if needed + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + + // Snap to pixel + if (src->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + advance_x += src->GlyphExtraAdvanceX; + } + + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = advance_x; +} + +// Copy to texture, post-process and queue update for backend +void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) +{ + ImTextureData* tex = atlas->TexData; + IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); + ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, (unsigned char*)tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); + ImFontAtlasPostProcessData pp_data = { atlas, baked->OwnerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; + ImFontAtlasTextureBlockPostProcess(&pp_data); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); +} + +void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) +{ + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); +} + +// Find glyph, load if necessary, return fallback if missing +ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return &Glyphs.Data[FallbackGlyphIndex]; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); + return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex]; +} + +// Attempt to load but when missing, return NULL instead of FallbackGlyph +ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return NULL; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + LoadNoFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); + LoadNoFallback = false; + return glyph; +} + +bool ImFontBaked::IsGlyphLoaded(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return false; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return true; + } + return false; +} + +// This is not fast query +bool ImFont::IsGlyphInFont(ImWchar c) +{ + ImFontAtlas* atlas = OwnerAtlas; + ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); + for (ImFontConfig* src : Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) + return true; + } + return false; +} + +// This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). +IM_MSVC_RUNTIME_CHECKS_OFF +float ImFontBaked::GetCharAdvance(ImWchar c) +{ + if ((int)c < IndexAdvanceX.Size) + { + // Missing glyphs fitting inside index will have stored FallbackAdvanceX already. + const float x = IndexAdvanceX.Data[c]; + if (x >= 0.0f) + return x; + } + return ImFontBaked_BuildLoadGlyphAdvanceX(this, c); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density) +{ + struct { ImGuiID FontId; float BakedSize; float RasterizerDensity; } hashed_data; + hashed_data.FontId = font_id; + hashed_data.BakedSize = baked_size; + hashed_data.RasterizerDensity = rasterizer_density; + return ImHashData(&hashed_data, sizeof(hashed_data)); +} + +// ImFontBaked pointers are valid for the entire frame but shall never be kept between frames. +ImFontBaked* ImFont::GetFontBaked(float size, float density) +{ + ImFontBaked* baked = LastBaked; + + // Round font size + // - ImGui::PushFont() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) + size = ImGui::GetRoundedFontSize(size); + + if (density < 0.0f) + density = CurrentRasterizerDensity; + if (baked && baked->Size == size && baked->RasterizerDensity == density) + return baked; + + ImFontAtlas* atlas = OwnerAtlas; + ImFontAtlasBuilder* builder = atlas->Builder; + baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, density); + if (baked == NULL) + return NULL; + baked->LastUsedFrame = builder->FrameCount; + LastBaked = baked; + return baked; +} + +ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) +{ + // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? + // FIXME-NEWATLAS: Altering font density won't work right away. + IM_ASSERT(font_size > 0.0f && font_rasterizer_density > 0.0f); + ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size, font_rasterizer_density); + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); + ImFontBaked* baked = *p_baked_in_map; + if (baked != NULL) + { + IM_ASSERT(baked->Size == font_size && baked->OwnerFont == font && baked->BakedId == baked_id); + return baked; + } + + // If atlas is locked, find closest match + // FIXME-OPT: This is not an optimal query. + if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) + { + baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density); + if (baked != NULL) + return baked; + if (atlas->Locked) + { + IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! + return NULL; + } + } + + // Create new + baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id); + *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. + return baked; +} + +// Trim trailing space and find beginning of next line +const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags) +{ + if ((flags & ImDrawTextFlags_WrapKeepBlanks) == 0) + while (text < text_end && ImCharIsBlankA(*text)) + text++; + if (text < text_end && *text == '\n') + text++; + return text; +} + +void ImTextClassifierClear(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class) +{ + for (unsigned int c = codepoint_min; c < codepoint_end; c++) + ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c); +} + +void ImTextClassifierSetCharClass(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, unsigned int c) +{ + IM_ASSERT(c >= codepoint_min && c < codepoint_end); + IM_UNUSED(codepoint_end); + c -= codepoint_min; + const ImU32 shift = (c & 15) << 1; + bits[c >> 4] = (bits[c >> 4] & ~(0x03 << shift)) | (char_class << shift); +} + +void ImTextClassifierSetCharClassFromStr(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, const char* s) +{ + const char* s_end = s + strlen(s); + while (*s) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, s_end); + ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c); + } +} + +#define ImTextClassifierGet(_BITS, _CHAR_OFFSET) ((_BITS[(_CHAR_OFFSET) >> 4] >> (((_CHAR_OFFSET) & 15) << 1)) & 0x03) + +// 2-bit per character +static ImU32 g_CharClassifierIsSeparator_0000_007f[128 / 16] = {}; +static ImU32 g_CharClassifierIsSeparator_3000_300f[ 16 / 16] = {}; + +void ImTextInitClassifiers() +{ + if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, ',') != 0) + return; + + // List of hardcoded separators: .,;!?'" + // Making this dynamic given known ranges is trivial BUT requires us to standardize where you pass them as parameters. (#3002, #8503) + ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Other); + ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Blank, " \t"); + ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Punct, ".,;!?\""); + + ImTextClassifierClear(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Other); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Blank, 0x3000); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Punct, 0x3001); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Punct, 0x3002); +} + +// Simple word-wrapping for English, not full-featured. Please submit failing cases! +// This will return the next location to wrap from. If no wrapping if necessary, this will fast-forward to e.g. text_end. +// Refer to imgui_test_suite's "drawlist_text_wordwrap_1" for tests. +const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags) +{ + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + ImFontBaked* baked = font->GetFontBaked(size); + const float scale = size / baked->Size; + + float line_width = 0.0f; + float blank_width = 0.0f; + wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters + + const char* s = text; + IM_ASSERT(text_end != NULL); + + int prev_type = ImWcharClass_Other; + const bool keep_blanks = (flags & ImDrawTextFlags_WrapKeepBlanks) != 0; + + // Find next wrapping point + //const char* span_begin = s; + const char* span_end = s; + float span_width = 0.0f; + + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + + if (c < 32) + { + if (c == '\n') + return s; // Direct return, skip "Wrap_width is too small to fit anything" path. + if (c == '\r') + { + s = next_s; // Fast-skip + continue; + } + } + + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); + + // Classify current character + int curr_type; + if (c < 128) + curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c); + else if (c >= 0x3000 && c < 0x3010) + curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_3000_300f, c & 15); //-V578 + else + curr_type = ImWcharClass_Other; + + if (curr_type == ImWcharClass_Blank) + { + // End span: 'A ' or '. ' + if (prev_type != ImWcharClass_Blank && !keep_blanks) + { + span_end = s; + line_width += span_width; + span_width = 0.0f; + } + blank_width += char_width; + } + else + { + // End span: '.X' unless X is a digit + if (prev_type == ImWcharClass_Punct && curr_type != ImWcharClass_Punct && !(c >= '0' && c <= '9')) // FIXME: Digit checks might be removed if allow custom separators (#8503) + { + span_end = s; + line_width += span_width + blank_width; + span_width = blank_width = 0.0f; + } + // End span: 'A ' or '. ' + else if (prev_type == ImWcharClass_Blank && keep_blanks) + { + span_end = s; + line_width += span_width + blank_width; + span_width = blank_width = 0.0f; + } + span_width += char_width; + } + + if (span_width + blank_width + line_width > wrap_width) + { + if (span_width + blank_width > wrap_width) + break; + // FIXME: Narrow wrapping e.g. "A quick brown" -> "Quic|k br|own", would require knowing if span is going to be longer than wrap_width. + //if (span_width > wrap_width && !is_blank && !was_blank) + // return s; + return span_end; + } + + prev_type = curr_type; + s = next_s; + } + + // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + // +1 may not be a character start point in UTF-8 but it's ok because caller loops use (text >= word_wrap_eol). + if (s == text && text < text_end) + return s + ImTextCountUtf8BytesFromChar(s, text_end); + return s; +} + +const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) +{ + return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width, ImDrawTextFlags_None); +} + +ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) +{ + if (!text_end) + text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. + if (!text_end_display) + text_end_display = text_end; + + ImFontBaked* baked = font->GetFontBaked(size); + const float line_height = size; + const float scale = line_height / baked->Size; + + ImVec2 text_size = ImVec2(0, 0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end_display) + { + // Word-wrapping + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, s, text_end, wrap_width - line_width, flags); + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks + if (flags & ImDrawTextFlags_StopOnNewLine) + break; + word_wrap_eol = NULL; + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + s += 1; + else + s += ImTextCharFromUtf8(&c, s, text_end); + + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (flags & ImDrawTextFlags_StopOnNewLine) + break; + continue; + } + if (c == '\r') + continue; + + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); + char_width *= scale; + + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset != NULL) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (out_remaining != NULL) + *out_remaining = s; + + return text_size; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) +{ + return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, text_end, text_end, out_remaining, NULL, ImDrawTextFlags_None); +} + +// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip) +{ + ImFontBaked* baked = GetFontBaked(size); + const ImFontGlyph* glyph = baked->FindGlyph(c); + if (!glyph || !glyph->Visible) + return; + if (glyph->Colored) + col |= ~IM_COL32_A_MASK; + float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f; + float x = IM_TRUNC(pos.x); + float y = IM_TRUNC(pos.y); + + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + if (cpu_fine_clip && (x1 > cpu_fine_clip->z || x2 < cpu_fine_clip->x)) + return; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // Always CPU fine clip. Code extracted from RenderText(). + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip != NULL) + { + if (x1 < cpu_fine_clip->x) { u1 = u1 + (1.0f - (x2 - cpu_fine_clip->x) / (x2 - x1)) * (u2 - u1); x1 = cpu_fine_clip->x; } + if (y1 < cpu_fine_clip->y) { v1 = v1 + (1.0f - (y2 - cpu_fine_clip->y) / (y2 - y1)) * (v2 - v1); y1 = cpu_fine_clip->y; } + if (x2 > cpu_fine_clip->z) { u2 = u1 + ((cpu_fine_clip->z - x1) / (x2 - x1)) * (u2 - u1); x2 = cpu_fine_clip->z; } + if (y2 > cpu_fine_clip->w) { v2 = v1 + ((cpu_fine_clip->w - y1) / (y2 - y1)) * (v2 - v1); y2 = cpu_fine_clip->w; } + if (y1 >= y2) + return; + } + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(ImVec2(x1, y1), ImVec2(x2, y2), ImVec2(u1, v1), ImVec2(u2, v2), col); +} + +// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +// DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2026. Use ImDrawList::AddText(). +void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, ImDrawTextFlags flags) +{ + // Align to be pixel perfect +begin: + float x = IM_TRUNC(pos.x); + float y = IM_TRUNC(pos.y); + if (y > clip_rect.w) + return; + + if (!text_end) + text_end = text_begin + ImStrlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. + + const float line_height = size; + ImFontBaked* baked = GetFontBaked(size); + + const float scale = size / baked->Size; + const float origin_x = x; + const bool word_wrap_enabled = (wrap_width > 0.0f); + + // Fast-forward to first visible line + const char* s = text_begin; + if (y + line_height < clip_rect.y) + while (y + line_height < clip_rect.y && s < text_end) + { + const char* line_end = (const char*)ImMemchr(s, '\n', text_end - s); + if (word_wrap_enabled) + { + // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition(). + // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. + // However it is still better than nothing performing the fast-forward! + s = ImFontCalcWordWrapPositionEx(this, size, s, line_end ? line_end : text_end, wrap_width, flags); + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); + } + else + { + s = line_end ? line_end + 1 : text_end; + } + y += line_height; + } + + // For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + // Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) + if (text_end - s > 10000 && !word_wrap_enabled) + { + const char* s_end = s; + float y_end = y; + while (y_end < clip_rect.w && s_end < text_end) + { + s_end = (const char*)ImMemchr(s_end, '\n', text_end - s_end); + s_end = s_end ? s_end + 1 : text_end; + y_end += line_height; + } + text_end = s_end; + } + if (s == text_end) + return; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_index = draw_list->_VtxCurrentIdx; + const int cmd_count = draw_list->CmdBuffer.Size; + const bool cpu_fine_clip = (flags & ImDrawTextFlags_CpuFineClip) != 0; + + const ImU32 col_untinted = col | ~IM_COL32_A_MASK; + const char* word_wrap_eol = NULL; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - (x - origin_x), flags); + + if (s >= word_wrap_eol) + { + x = origin_x; + y += line_height; + if (y > clip_rect.w) + break; // break out of main loop + word_wrap_eol = NULL; + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + s += 1; + else + s += ImTextCharFromUtf8(&c, s, text_end); + + if (c < 32) + { + if (c == '\n') + { + x = origin_x; + y += line_height; + if (y > clip_rect.w) + break; // break out of main loop + continue; + } + if (c == '\r') + continue; + } + + const ImFontGlyph* glyph = baked->FindGlyph((ImWchar)c); + //if (glyph == NULL) + // continue; + + float char_width = glyph->AdvanceX * scale; + if (glyph->Visible) + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // Support for untinted glyphs + ImU32 glyph_col = glyph->Colored ? col_untinted : col; + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: + { + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = glyph_col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = glyph_col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = glyph_col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = glyph_col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + idx_write[0] = (ImDrawIdx)(vtx_index); idx_write[1] = (ImDrawIdx)(vtx_index + 1); idx_write[2] = (ImDrawIdx)(vtx_index + 2); + idx_write[3] = (ImDrawIdx)(vtx_index); idx_write[4] = (ImDrawIdx)(vtx_index + 2); idx_write[5] = (ImDrawIdx)(vtx_index + 3); + vtx_write += 4; + vtx_index += 4; + idx_write += 6; + } + } + } + x += char_width; + } + + // Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui:: calls because CalcTextSize() is always used. + if (cmd_count != draw_list->CmdBuffer.Size) //-V547 + { + IM_ASSERT(draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount == 0); + draw_list->CmdBuffer.pop_back(); + draw_list->PrimUnreserve(idx_count_max, vtx_count_max); + draw_list->AddDrawCmd(); + //IMGUI_DEBUG_LOG("RenderText: cancel and retry to missing glyphs.\n"); // [DEBUG] + //draw_list->AddRectFilled(pos, pos + ImVec2(10, 10), IM_COL32(255, 0, 0, 255)); // [DEBUG] + goto begin; + //RenderText(draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); // FIXME-OPT: Would a 'goto begin' be better for code-gen? + //return; + } + + // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. + draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink() + draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = vtx_index; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGui Internal Render Helpers +//----------------------------------------------------------------------------- +// Vaguely redesigned to stop accessing ImGui global state: +// - RenderArrow() +// - RenderBullet() +// - RenderCheckMark() +// - RenderArrowDockMenu() +// - RenderArrowPointingAt() +// - RenderRectFilledInRangeH() +// - RenderRectFilledWithHole() +//----------------------------------------------------------------------------- +// Function in need of a redesign (legacy mess) +// - RenderColorRectWithAlphaCheckerboard() +//----------------------------------------------------------------------------- + +// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state +void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) +{ + const float h = draw_list->_Data->FontSize * 1.00f; + float r = h * 0.40f * scale; + ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + + ImVec2 a, b, c; + switch (dir) + { + case ImGuiDir_Up: + case ImGuiDir_Down: + if (dir == ImGuiDir_Up) r = -r; + a = ImVec2(+0.000f, +0.750f) * r; + b = ImVec2(-0.866f, -0.750f) * r; + c = ImVec2(+0.866f, -0.750f) * r; + break; + case ImGuiDir_Left: + case ImGuiDir_Right: + if (dir == ImGuiDir_Left) r = -r; + a = ImVec2(+0.750f, +0.000f) * r; + b = ImVec2(-0.750f, +0.866f) * r; + c = ImVec2(-0.750f, -0.866f) * r; + break; + case ImGuiDir_None: + case ImGuiDir_COUNT: + IM_ASSERT(0); + break; + } + draw_list->AddTriangleFilled(center + a, center + b, center + c, col); +} + +void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) +{ + // FIXME-OPT: This should be baked in font now that it's easier. + float font_size = draw_list->_Data->FontSize; + draw_list->AddCircleFilled(pos, font_size * 0.20f, col, (font_size < 22) ? 8 : (font_size < 40) ? 12 : 0); // Hardcode optimal/nice tessellation threshold +} + +void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz) +{ + float thickness = ImMax(sz / 5.0f, 1.0f); + sz -= thickness * 0.5f; + pos += ImVec2(thickness * 0.25f, thickness * 0.25f); + + float third = sz / 3.0f; + float bx = pos.x + third; + float by = pos.y + sz - third * 0.5f; + draw_list->PathLineTo(ImVec2(bx - third, by - third)); + draw_list->PathLineTo(ImVec2(bx, by)); + draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f)); + draw_list->PathStroke(col, 0, thickness); +} + +// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + switch (direction) + { + case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings + } +} + +// This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, +// and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. +void ImGui::RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col) +{ + draw_list->AddRectFilled(p_min + ImVec2(sz * 0.20f, sz * 0.15f), p_min + ImVec2(sz * 0.80f, sz * 0.30f), col); + RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50f, sz * 0.85f), ImVec2(sz * 0.30f, sz * 0.40f), ImGuiDir_Down, col); +} + +static inline float ImAcos01(float x) +{ + if (x <= 0.0f) return IM_PI * 0.5f; + if (x >= 1.0f) return 0.0f; + return ImAcos(x); + //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do. +} + +// FIXME: Cleanup and move code to ImDrawList. +// - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized +// - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! +void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding) +{ + if (fill_x0 > fill_x1) + return; + + ImVec2 p0 = ImVec2(fill_x0, rect.Min.y); + ImVec2 p1 = ImVec2(fill_x1, rect.Max.y); + if (rounding == 0.0f) + { + draw_list->AddRectFilled(p0, p1, col, 0.0f); + return; + } + + rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding); + const float inv_rounding = 1.0f / rounding; + const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding); + const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding); + const float half_pi = IM_PI * 0.5f; // We will == compare to this because we know this is the exact value ImAcos01 can return. + const float x0 = ImMax(p0.x, rect.Min.x + rounding); + if (arc0_b == arc0_e) + { + draw_list->PathLineTo(ImVec2(x0, p1.y)); + draw_list->PathLineTo(ImVec2(x0, p0.y)); + } + else if (arc0_b == 0.0f && arc0_e == half_pi) + { + draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL + draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR + } + else + { + draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b); // BL + draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e); // TR + } + if (p1.x > rect.Min.x + rounding) + { + const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding); + const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding); + const float x1 = ImMin(p1.x, rect.Max.x - rounding); + if (arc1_b == arc1_e) + { + draw_list->PathLineTo(ImVec2(x1, p0.y)); + draw_list->PathLineTo(ImVec2(x1, p1.y)); + } + else if (arc1_b == 0.0f && arc1_e == half_pi) + { + draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR + draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR + } + else + { + draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b); // TR + draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e); // BR + } + } + draw_list->PathFillConvex(col); +} + +void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding) +{ + const bool fill_L = (inner.Min.x > outer.Min.x); + const bool fill_R = (inner.Max.x < outer.Max.x); + const bool fill_U = (inner.Min.y > outer.Min.y); + const bool fill_D = (inner.Max.y < outer.Max.y); + if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft)); + if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight)); + if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft); + if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight); + if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft); + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); +} + +ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold) +{ + bool round_l = r_in.Min.x <= r_outer.Min.x + threshold; + bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; + bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; + bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; + return ImDrawFlags_RoundCornersNone + | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) + | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); +} + +// Helper for ColorPicker4() +// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. +// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. +// FIXME: uses ImGui::GetColorU32 +void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags) +{ + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags = ImDrawFlags_RoundCornersDefault_; + if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) + { + ImU32 col_bg1 = GetColorU32(ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col)); + ImU32 col_bg2 = GetColorU32(ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col)); + draw_list->AddRectFilled(p_min, p_max, col_bg1, rounding, flags); + + int yi = 0; + for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++) + { + float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y); + if (y2 <= y1) + continue; + for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f) + { + float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x); + if (x2 <= x1) + continue; + ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone; + if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersTopRight; } + if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersBottomRight; } + + // Combine flags + cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags); + draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding, cell_flags); + } + } + } + else + { + draw_list->AddRectFilled(p_min, p_max, col, rounding, flags); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Decompression code +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array and encoded as base85. +// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(const unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier_out_e, *stb__barrier_out_b; +static const unsigned char *stb__barrier_in_b; +static unsigned char *stb__dout; +static void stb__match(const unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } + if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(const unsigned char *data, unsigned int length) +{ + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } + if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static const unsigned char *stb_decompress_token(const unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen = buflen % 5552; + + unsigned long i; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/) +{ + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + const unsigned int olen = stb_decompress_length(i); + stb__barrier_in_b = i; + stb__barrier_out_e = output + olen; + stb__barrier_out_b = output; + i += 16; + + stb__dout = output; + for (;;) { + const unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Default font data (ProggyClean.ttf) +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download) +// Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php +// If you want a similar font which may be better scaled, consider using ProggyVector from the same author! +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_DEFAULT_FONT + +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using binary_to_compressed_c.exe -u8 "ProggyClean.ttf" proggy_clean_ttf +static const unsigned int proggy_clean_ttf_compressed_size = 9583; +static const unsigned char proggy_clean_ttf_compressed_data[9583] = +{ + 87,188,0,0,0,0,0,0,0,0,160,248,0,4,0,0,55,0,1,0,0,0,12,0,128,0,3,0,64,79,83,47,50,136,235,116,144,0,0,1,72,130,21,44,78,99,109,97,112,2,18,35,117,0,0,3,160,130,19,36,82,99,118,116, + 32,130,23,130,2,33,4,252,130,4,56,2,103,108,121,102,18,175,137,86,0,0,7,4,0,0,146,128,104,101,97,100,215,145,102,211,130,27,32,204,130,3,33,54,104,130,16,39,8,66,1,195,0,0,1,4,130, + 15,59,36,104,109,116,120,138,0,126,128,0,0,1,152,0,0,2,6,108,111,99,97,140,115,176,216,0,0,5,130,30,41,2,4,109,97,120,112,1,174,0,218,130,31,32,40,130,16,44,32,110,97,109,101,37,89, + 187,150,0,0,153,132,130,19,44,158,112,111,115,116,166,172,131,239,0,0,155,36,130,51,44,210,112,114,101,112,105,2,1,18,0,0,4,244,130,47,32,8,132,203,46,1,0,0,60,85,233,213,95,15,60, + 245,0,3,8,0,131,0,34,183,103,119,130,63,43,0,0,189,146,166,215,0,0,254,128,3,128,131,111,130,241,33,2,0,133,0,32,1,130,65,38,192,254,64,0,0,3,128,131,16,130,5,32,1,131,7,138,3,33,2, + 0,130,17,36,1,1,0,144,0,130,121,130,23,38,2,0,8,0,64,0,10,130,9,32,118,130,9,130,6,32,0,130,59,33,1,144,131,200,35,2,188,2,138,130,16,32,143,133,7,37,1,197,0,50,2,0,131,0,33,4,9,131, + 5,145,3,43,65,108,116,115,0,64,0,0,32,172,8,0,131,0,35,5,0,1,128,131,77,131,3,33,3,128,191,1,33,1,128,130,184,35,0,0,128,0,130,3,131,11,32,1,130,7,33,0,128,131,1,32,1,136,9,32,0,132, + 15,135,5,32,1,131,13,135,27,144,35,32,1,149,25,131,21,32,0,130,0,32,128,132,103,130,35,132,39,32,0,136,45,136,97,133,17,130,5,33,0,0,136,19,34,0,128,1,133,13,133,5,32,128,130,15,132, + 131,32,3,130,5,32,3,132,27,144,71,32,0,133,27,130,29,130,31,136,29,131,63,131,3,65,63,5,132,5,132,205,130,9,33,0,0,131,9,137,119,32,3,132,19,138,243,130,55,32,1,132,35,135,19,131,201, + 136,11,132,143,137,13,130,41,32,0,131,3,144,35,33,128,0,135,1,131,223,131,3,141,17,134,13,136,63,134,15,136,53,143,15,130,96,33,0,3,131,4,130,3,34,28,0,1,130,5,34,0,0,76,130,17,131, + 9,36,28,0,4,0,48,130,17,46,8,0,8,0,2,0,0,0,127,0,255,32,172,255,255,130,9,34,0,0,129,132,9,130,102,33,223,213,134,53,132,22,33,1,6,132,6,64,4,215,32,129,165,216,39,177,0,1,141,184, + 1,255,133,134,45,33,198,0,193,1,8,190,244,1,28,1,158,2,20,2,136,2,252,3,20,3,88,3,156,3,222,4,20,4,50,4,80,4,98,4,162,5,22,5,102,5,188,6,18,6,116,6,214,7,56,7,126,7,236,8,78,8,108, + 8,150,8,208,9,16,9,74,9,136,10,22,10,128,11,4,11,86,11,200,12,46,12,130,12,234,13,94,13,164,13,234,14,80,14,150,15,40,15,176,16,18,16,116,16,224,17,82,17,182,18,4,18,110,18,196,19, + 76,19,172,19,246,20,88,20,174,20,234,21,64,21,128,21,166,21,184,22,18,22,126,22,198,23,52,23,142,23,224,24,86,24,186,24,238,25,54,25,150,25,212,26,72,26,156,26,240,27,92,27,200,28, + 4,28,76,28,150,28,234,29,42,29,146,29,210,30,64,30,142,30,224,31,36,31,118,31,166,31,166,32,16,130,1,52,46,32,138,32,178,32,200,33,20,33,116,33,152,33,238,34,98,34,134,35,12,130,1, + 33,128,35,131,1,60,152,35,176,35,216,36,0,36,74,36,104,36,144,36,174,37,6,37,96,37,130,37,248,37,248,38,88,38,170,130,1,8,190,216,39,64,39,154,40,10,40,104,40,168,41,14,41,32,41,184, + 41,248,42,54,42,96,42,96,43,2,43,42,43,94,43,172,43,230,44,32,44,52,44,154,45,40,45,92,45,120,45,170,45,232,46,38,46,166,47,38,47,182,47,244,48,94,48,200,49,62,49,180,50,30,50,158, + 51,30,51,130,51,238,52,92,52,206,53,58,53,134,53,212,54,38,54,114,54,230,55,118,55,216,56,58,56,166,57,18,57,116,57,174,58,46,58,154,59,6,59,124,59,232,60,58,60,150,61,34,61,134,61, + 236,62,86,62,198,63,42,63,154,64,18,64,106,64,208,65,54,65,162,66,8,66,64,66,122,66,184,66,240,67,98,67,204,68,42,68,138,68,238,69,88,69,182,69,226,70,84,70,180,71,20,71,122,71,218, + 72,84,72,198,73,64,0,36,70,21,8,8,77,3,0,7,0,11,0,15,0,19,0,23,0,27,0,31,0,35,0,39,0,43,0,47,0,51,0,55,0,59,0,63,0,67,0,71,0,75,0,79,0,83,0,87,0,91,0,95,0,99,0,103,0,107,0,111,0,115, + 0,119,0,123,0,127,0,131,0,135,0,139,0,143,0,0,17,53,51,21,49,150,3,32,5,130,23,32,33,130,3,211,7,151,115,32,128,133,0,37,252,128,128,2,128,128,190,5,133,74,32,4,133,6,206,5,42,0,7, + 1,128,0,0,2,0,4,0,0,65,139,13,37,0,1,53,51,21,7,146,3,32,3,130,19,32,1,141,133,32,3,141,14,131,13,38,255,0,128,128,0,6,1,130,84,35,2,128,4,128,140,91,132,89,32,51,65,143,6,139,7,33, + 1,0,130,57,32,254,130,3,32,128,132,4,32,4,131,14,138,89,35,0,0,24,0,130,0,33,3,128,144,171,66,55,33,148,115,65,187,19,32,5,130,151,143,155,163,39,32,1,136,182,32,253,134,178,132,7, + 132,200,145,17,32,3,65,48,17,165,17,39,0,0,21,0,128,255,128,3,65,175,17,65,3,27,132,253,131,217,139,201,155,233,155,27,131,67,131,31,130,241,33,255,0,131,181,137,232,132,15,132,4,138, + 247,34,255,0,128,179,238,32,0,130,0,32,20,65,239,48,33,0,19,67,235,10,32,51,65,203,14,65,215,11,32,7,154,27,135,39,32,33,130,35,33,128,128,130,231,32,253,132,231,32,128,132,232,34, + 128,128,254,133,13,136,8,32,253,65,186,5,130,36,130,42,176,234,133,231,34,128,0,0,66,215,44,33,0,1,68,235,6,68,211,19,32,49,68,239,14,139,207,139,47,66,13,7,32,51,130,47,33,1,0,130, + 207,35,128,128,1,0,131,222,131,5,130,212,130,6,131,212,32,0,130,10,133,220,130,233,130,226,32,254,133,255,178,233,39,3,1,128,3,0,2,0,4,68,15,7,68,99,12,130,89,130,104,33,128,4,133, + 93,130,10,38,0,0,11,1,0,255,0,68,63,16,70,39,9,66,215,8,32,7,68,77,6,68,175,14,32,29,68,195,6,132,7,35,2,0,128,255,131,91,132,4,65,178,5,141,111,67,129,23,165,135,140,107,142,135,33, + 21,5,69,71,6,131,7,33,1,0,140,104,132,142,130,4,137,247,140,30,68,255,12,39,11,0,128,0,128,3,0,3,69,171,15,67,251,7,65,15,8,66,249,11,65,229,7,67,211,7,66,13,7,35,1,128,128,254,133, + 93,32,254,131,145,132,4,132,18,32,2,151,128,130,23,34,0,0,9,154,131,65,207,8,68,107,15,68,51,7,32,7,70,59,7,135,121,130,82,32,128,151,111,41,0,0,4,0,128,255,0,1,128,1,137,239,33,0, + 37,70,145,10,65,77,10,65,212,14,37,0,0,0,5,0,128,66,109,5,70,123,10,33,0,19,72,33,18,133,237,70,209,11,33,0,2,130,113,137,119,136,115,33,1,0,133,43,130,5,34,0,0,10,69,135,6,70,219, + 13,66,155,7,65,9,12,66,157,11,66,9,11,32,7,130,141,132,252,66,151,9,137,9,66,15,30,36,0,20,0,128,0,130,218,71,11,42,68,51,8,65,141,7,73,19,15,69,47,23,143,39,66,81,7,32,1,66,55,6,34, + 1,128,128,68,25,5,69,32,6,137,6,136,25,32,254,131,42,32,3,66,88,26,148,26,32,0,130,0,32,14,164,231,70,225,12,66,233,7,67,133,19,71,203,15,130,161,32,255,130,155,32,254,139,127,134, + 12,164,174,33,0,15,164,159,33,59,0,65,125,20,66,25,7,32,5,68,191,6,66,29,7,144,165,65,105,9,35,128,128,255,0,137,2,133,182,164,169,33,128,128,197,171,130,155,68,235,7,32,21,70,77,19, + 66,21,10,68,97,8,66,30,5,66,4,43,34,0,17,0,71,19,41,65,253,20,71,25,23,65,91,15,65,115,7,34,2,128,128,66,9,8,130,169,33,1,0,66,212,13,132,28,72,201,43,35,0,0,0,18,66,27,38,76,231,5, + 68,157,20,135,157,32,7,68,185,13,65,129,28,66,20,5,32,253,66,210,11,65,128,49,133,61,32,0,65,135,6,74,111,37,72,149,12,66,203,19,65,147,19,68,93,7,68,85,8,76,4,5,33,255,0,133,129,34, + 254,0,128,68,69,8,181,197,34,0,0,12,65,135,32,65,123,20,69,183,27,133,156,66,50,5,72,87,10,67,137,32,33,0,19,160,139,78,251,13,68,55,20,67,119,19,65,91,36,69,177,15,32,254,143,16,65, + 98,53,32,128,130,0,32,0,66,43,54,70,141,23,66,23,15,131,39,69,47,11,131,15,70,129,19,74,161,9,36,128,255,0,128,254,130,153,65,148,32,67,41,9,34,0,0,4,79,15,5,73,99,10,71,203,8,32,3, + 72,123,6,72,43,8,32,2,133,56,131,99,130,9,34,0,0,6,72,175,5,73,159,14,144,63,135,197,132,189,133,66,33,255,0,73,6,7,70,137,12,35,0,0,0,10,130,3,73,243,25,67,113,12,65,73,7,69,161,7, + 138,7,37,21,2,0,128,128,254,134,3,73,116,27,33,128,128,130,111,39,12,0,128,1,0,3,128,2,72,219,21,35,43,0,47,0,67,47,20,130,111,33,21,1,68,167,13,81,147,8,133,230,32,128,77,73,6,32, + 128,131,142,134,18,130,6,32,255,75,18,12,131,243,37,128,0,128,3,128,3,74,231,21,135,123,32,29,134,107,135,7,32,21,74,117,7,135,7,134,96,135,246,74,103,23,132,242,33,0,10,67,151,28, + 67,133,20,66,141,11,131,11,32,3,77,71,6,32,128,130,113,32,1,81,4,6,134,218,66,130,24,131,31,34,0,26,0,130,0,77,255,44,83,15,11,148,155,68,13,7,32,49,78,231,18,79,7,11,73,243,11,32, + 33,65,187,10,130,63,65,87,8,73,239,19,35,0,128,1,0,131,226,32,252,65,100,6,32,128,139,8,33,1,0,130,21,32,253,72,155,44,73,255,20,32,128,71,67,8,81,243,39,67,15,20,74,191,23,68,121, + 27,32,1,66,150,6,32,254,79,19,11,131,214,32,128,130,215,37,2,0,128,253,0,128,136,5,65,220,24,147,212,130,210,33,0,24,72,219,42,84,255,13,67,119,16,69,245,19,72,225,19,65,3,15,69,93, + 19,131,55,132,178,71,115,14,81,228,6,142,245,33,253,0,132,43,172,252,65,16,11,75,219,8,65,219,31,66,223,24,75,223,10,33,29,1,80,243,10,66,175,8,131,110,134,203,133,172,130,16,70,30, + 7,164,183,130,163,32,20,65,171,48,65,163,36,65,143,23,65,151,19,65,147,13,65,134,17,133,17,130,216,67,114,5,164,217,65,137,12,72,147,48,79,71,19,74,169,22,80,251,8,65,173,7,66,157, + 15,74,173,15,32,254,65,170,8,71,186,45,72,131,6,77,143,40,187,195,152,179,65,123,38,68,215,57,68,179,15,65,85,7,69,187,14,32,21,66,95,15,67,19,25,32,1,83,223,6,32,2,76,240,7,77,166, + 43,65,8,5,130,206,32,0,67,39,54,143,167,66,255,19,82,193,11,151,47,85,171,5,67,27,17,132,160,69,172,11,69,184,56,66,95,6,33,12,1,130,237,32,2,68,179,27,68,175,16,80,135,15,72,55,7, + 71,87,12,73,3,12,132,12,66,75,32,76,215,5,169,139,147,135,148,139,81,12,12,81,185,36,75,251,7,65,23,27,76,215,9,87,165,12,65,209,15,72,157,7,65,245,31,32,128,71,128,6,32,1,82,125,5, + 34,0,128,254,131,169,32,254,131,187,71,180,9,132,27,32,2,88,129,44,32,0,78,47,40,65,79,23,79,171,14,32,21,71,87,8,72,15,14,65,224,33,130,139,74,27,62,93,23,7,68,31,7,75,27,7,139,15, + 74,3,7,74,23,27,65,165,11,65,177,15,67,123,5,32,1,130,221,32,252,71,96,5,74,12,12,133,244,130,25,34,1,0,128,130,2,139,8,93,26,8,65,9,32,65,57,14,140,14,32,0,73,79,67,68,119,11,135, + 11,32,51,90,75,14,139,247,65,43,7,131,19,139,11,69,159,11,65,247,6,36,1,128,128,253,0,90,71,9,33,1,0,132,14,32,128,89,93,14,69,133,6,130,44,131,30,131,6,65,20,56,33,0,16,72,179,40, + 75,47,12,65,215,19,74,95,19,65,43,11,131,168,67,110,5,75,23,17,69,106,6,75,65,5,71,204,43,32,0,80,75,47,71,203,15,159,181,68,91,11,67,197,7,73,101,13,68,85,6,33,128,128,130,214,130, + 25,32,254,74,236,48,130,194,37,0,18,0,128,255,128,77,215,40,65,139,64,32,51,80,159,10,65,147,39,130,219,84,212,43,130,46,75,19,97,74,33,11,65,201,23,65,173,31,33,1,0,79,133,6,66,150, + 5,67,75,48,85,187,6,70,207,37,32,71,87,221,13,73,163,14,80,167,15,132,15,83,193,19,82,209,8,78,99,9,72,190,11,77,110,49,89,63,5,80,91,35,99,63,32,70,235,23,81,99,10,69,148,10,65,110, + 36,32,0,65,99,47,95,219,11,68,171,51,66,87,7,72,57,7,74,45,17,143,17,65,114,50,33,14,0,65,111,40,159,195,98,135,15,35,7,53,51,21,100,78,9,95,146,16,32,254,82,114,6,32,128,67,208,37, + 130,166,99,79,58,32,17,96,99,14,72,31,19,72,87,31,82,155,7,67,47,14,32,21,131,75,134,231,72,51,17,72,78,8,133,8,80,133,6,33,253,128,88,37,9,66,124,36,72,65,12,134,12,71,55,43,66,139, + 27,85,135,10,91,33,12,65,35,11,66,131,11,71,32,8,90,127,6,130,244,71,76,11,168,207,33,0,12,66,123,32,32,0,65,183,15,68,135,11,66,111,7,67,235,11,66,111,15,32,254,97,66,12,160,154,67, + 227,52,80,33,15,87,249,15,93,45,31,75,111,12,93,45,11,77,99,9,160,184,81,31,12,32,15,98,135,30,104,175,7,77,249,36,69,73,15,78,5,12,32,254,66,151,19,34,128,128,4,87,32,12,149,35,133, + 21,96,151,31,32,19,72,35,5,98,173,15,143,15,32,21,143,99,158,129,33,0,0,65,35,52,65,11,15,147,15,98,75,11,33,1,0,143,151,132,15,32,254,99,200,37,132,43,130,4,39,0,10,0,128,1,128,3, + 0,104,151,14,97,187,20,69,131,15,67,195,11,87,227,7,33,128,128,132,128,33,254,0,68,131,9,65,46,26,42,0,0,0,7,0,0,255,128,3,128,0,88,223,15,33,0,21,89,61,22,66,209,12,65,2,12,37,0,2, + 1,0,3,128,101,83,8,36,0,1,53,51,29,130,3,34,21,1,0,66,53,8,32,0,68,215,6,100,55,25,107,111,9,66,193,11,72,167,8,73,143,31,139,31,33,1,0,131,158,32,254,132,5,33,253,128,65,16,9,133, + 17,89,130,25,141,212,33,0,0,93,39,8,90,131,25,93,39,14,66,217,6,106,179,8,159,181,71,125,15,139,47,138,141,87,11,14,76,23,14,65,231,26,140,209,66,122,8,81,179,5,101,195,26,32,47,74, + 75,13,69,159,11,83,235,11,67,21,16,136,167,131,106,130,165,130,15,32,128,101,90,24,134,142,32,0,65,103,51,108,23,11,101,231,15,75,173,23,74,237,23,66,15,6,66,46,17,66,58,17,65,105, + 49,66,247,55,71,179,12,70,139,15,86,229,7,84,167,15,32,1,95,72,12,89,49,6,33,128,128,65,136,38,66,30,9,32,0,100,239,7,66,247,29,70,105,20,65,141,19,69,81,15,130,144,32,128,83,41,5, + 32,255,131,177,68,185,5,133,126,65,97,37,32,0,130,0,33,21,0,130,55,66,195,28,67,155,13,34,79,0,83,66,213,13,73,241,19,66,59,19,65,125,11,135,201,66,249,16,32,128,66,44,11,66,56,17, + 68,143,8,68,124,38,67,183,12,96,211,9,65,143,29,112,171,5,32,0,68,131,63,34,33,53,51,71,121,11,32,254,98,251,16,32,253,74,231,10,65,175,37,133,206,37,0,0,8,1,0,0,107,123,11,113,115, + 9,33,0,1,130,117,131,3,73,103,7,66,51,18,66,44,5,133,75,70,88,5,32,254,65,39,12,68,80,9,34,12,0,128,107,179,28,68,223,6,155,111,86,147,15,32,2,131,82,141,110,33,254,0,130,15,32,4,103, + 184,15,141,35,87,176,5,83,11,5,71,235,23,114,107,11,65,189,16,70,33,15,86,153,31,135,126,86,145,30,65,183,41,32,0,130,0,32,10,65,183,24,34,35,0,39,67,85,9,65,179,15,143,15,33,1,0,65, + 28,17,157,136,130,123,32,20,130,3,32,0,97,135,24,115,167,19,80,71,12,32,51,110,163,14,78,35,19,131,19,155,23,77,229,8,78,9,17,151,17,67,231,46,94,135,8,73,31,31,93,215,56,82,171,25, + 72,77,8,162,179,169,167,99,131,11,69,85,19,66,215,15,76,129,13,68,115,22,72,79,35,67,113,5,34,0,0,19,70,31,46,65,89,52,73,223,15,85,199,33,95,33,8,132,203,73,29,32,67,48,16,177,215, + 101,13,15,65,141,43,69,141,15,75,89,5,70,0,11,70,235,21,178,215,36,10,0,128,0,0,71,207,24,33,0,19,100,67,6,80,215,11,66,67,7,80,43,12,71,106,7,80,192,5,65,63,5,66,217,26,33,0,13,156, + 119,68,95,5,72,233,12,134,129,85,81,11,76,165,20,65,43,8,73,136,8,75,10,31,38,128,128,0,0,0,13,1,130,4,32,3,106,235,29,114,179,12,66,131,23,32,7,77,133,6,67,89,12,131,139,116,60,9, + 89,15,37,32,0,74,15,7,103,11,22,65,35,5,33,55,0,93,81,28,67,239,23,78,85,5,107,93,14,66,84,17,65,193,26,74,183,10,66,67,34,143,135,79,91,15,32,7,117,111,8,75,56,9,84,212,9,154,134, + 32,0,130,0,32,18,130,3,70,171,41,83,7,16,70,131,19,84,191,15,84,175,19,84,167,30,84,158,12,154,193,68,107,15,33,0,0,65,79,42,65,71,7,73,55,7,118,191,16,83,180,9,32,255,76,166,9,154, + 141,32,0,130,0,69,195,52,65,225,15,151,15,75,215,31,80,56,10,68,240,17,100,32,9,70,147,39,65,93,12,71,71,41,92,85,15,84,135,23,78,35,15,110,27,10,84,125,8,107,115,29,136,160,38,0,0, + 14,0,128,255,0,82,155,24,67,239,8,119,255,11,69,131,11,77,29,6,112,31,8,134,27,105,203,8,32,2,75,51,11,75,195,12,74,13,29,136,161,37,128,0,0,0,11,1,130,163,82,115,8,125,191,17,69,35, + 12,74,137,15,143,15,32,1,65,157,12,136,12,161,142,65,43,40,65,199,6,65,19,24,102,185,11,76,123,11,99,6,12,135,12,32,254,130,8,161,155,101,23,9,39,8,0,0,1,128,3,128,2,78,63,17,72,245, + 12,67,41,11,90,167,9,32,128,97,49,9,32,128,109,51,14,132,97,81,191,8,130,97,125,99,12,121,35,9,127,75,15,71,79,12,81,151,23,87,97,7,70,223,15,80,245,16,105,97,15,32,254,113,17,6,32, + 128,130,8,105,105,8,76,122,18,65,243,21,74,63,7,38,4,1,0,255,0,2,0,119,247,28,133,65,32,255,141,91,35,0,0,0,16,67,63,36,34,59,0,63,77,59,9,119,147,11,143,241,66,173,15,66,31,11,67, + 75,8,81,74,16,32,128,131,255,87,181,42,127,43,5,34,255,128,2,120,235,11,37,19,0,23,0,0,37,109,191,14,118,219,7,127,43,14,65,79,14,35,0,0,0,3,73,91,5,130,5,38,3,0,7,0,11,0,0,70,205, + 11,88,221,12,32,0,73,135,7,87,15,22,73,135,10,79,153,15,97,71,19,65,49,11,32,1,131,104,121,235,11,80,65,11,142,179,144,14,81,123,46,32,1,88,217,5,112,5,8,65,201,15,83,29,15,122,147, + 11,135,179,142,175,143,185,67,247,39,66,199,7,35,5,0,128,3,69,203,15,123,163,12,67,127,7,130,119,71,153,10,141,102,70,175,8,32,128,121,235,30,136,89,100,191,11,116,195,11,111,235,15, + 72,39,7,32,2,97,43,5,132,5,94,67,8,131,8,125,253,10,32,3,65,158,16,146,16,130,170,40,0,21,0,128,0,0,3,128,5,88,219,15,24,64,159,32,135,141,65,167,15,68,163,10,97,73,49,32,255,82,58, + 7,93,80,8,97,81,16,24,67,87,52,34,0,0,5,130,231,33,128,2,80,51,13,65,129,8,113,61,6,132,175,65,219,5,130,136,77,152,17,32,0,95,131,61,70,215,6,33,21,51,90,53,10,78,97,23,105,77,31, + 65,117,7,139,75,24,68,195,9,24,64,22,9,33,0,128,130,11,33,128,128,66,25,5,121,38,5,134,5,134,45,66,40,36,66,59,18,34,128,0,0,66,59,81,135,245,123,103,19,120,159,19,77,175,12,33,255, + 0,87,29,10,94,70,21,66,59,54,39,3,1,128,3,0,2,128,4,24,65,7,15,66,47,7,72,98,12,37,0,0,0,3,1,0,24,65,55,21,131,195,32,1,67,178,6,33,4,0,77,141,8,32,6,131,47,74,67,16,24,69,3,20,24, + 65,251,7,133,234,130,229,94,108,17,35,0,0,6,0,141,175,86,59,5,162,79,85,166,8,70,112,13,32,13,24,64,67,26,24,71,255,7,123,211,12,80,121,11,69,215,15,66,217,11,69,71,10,131,113,132, + 126,119,90,9,66,117,19,132,19,32,0,130,0,24,64,47,59,33,7,0,73,227,5,68,243,15,85,13,12,76,37,22,74,254,15,130,138,33,0,4,65,111,6,137,79,65,107,16,32,1,77,200,6,34,128,128,3,75,154, + 12,37,0,16,0,0,2,0,104,115,36,140,157,68,67,19,68,51,15,106,243,15,134,120,70,37,10,68,27,10,140,152,65,121,24,32,128,94,155,7,67,11,8,24,74,11,25,65,3,12,83,89,18,82,21,37,67,200, + 5,130,144,24,64,172,12,33,4,0,134,162,74,80,14,145,184,32,0,130,0,69,251,20,32,19,81,243,5,82,143,8,33,5,53,89,203,5,133,112,79,109,15,33,0,21,130,71,80,175,41,36,75,0,79,0,83,121, + 117,9,87,89,27,66,103,11,70,13,15,75,191,11,135,67,87,97,20,109,203,5,69,246,8,108,171,5,78,195,38,65,51,13,107,203,11,77,3,17,24,75,239,17,65,229,28,79,129,39,130,175,32,128,123,253, + 7,132,142,24,65,51,15,65,239,41,36,128,128,0,0,13,65,171,5,66,163,28,136,183,118,137,11,80,255,15,67,65,7,74,111,8,32,0,130,157,32,253,24,76,35,10,103,212,5,81,175,9,69,141,7,66,150, + 29,131,158,24,75,199,28,124,185,7,76,205,15,68,124,14,32,3,123,139,16,130,16,33,128,128,108,199,6,33,0,3,65,191,35,107,11,6,73,197,11,24,70,121,15,83,247,15,24,70,173,23,69,205,14, + 32,253,131,140,32,254,136,4,94,198,9,32,3,78,4,13,66,127,13,143,13,32,0,130,0,33,16,0,24,69,59,39,109,147,12,76,253,19,24,69,207,15,69,229,15,130,195,71,90,10,139,10,130,152,73,43, + 40,91,139,10,65,131,37,35,75,0,79,0,84,227,12,143,151,68,25,15,80,9,23,95,169,11,34,128,2,128,112,186,5,130,6,83,161,19,76,50,6,130,37,65,145,44,110,83,5,32,16,67,99,6,71,67,15,76, + 55,17,140,215,67,97,23,76,69,15,77,237,11,104,211,23,77,238,11,65,154,43,33,0,10,83,15,28,83,13,20,67,145,19,67,141,14,97,149,21,68,9,15,86,251,5,66,207,5,66,27,37,82,1,23,127,71,12, + 94,235,10,110,175,24,98,243,15,132,154,132,4,24,66,69,10,32,4,67,156,43,130,198,35,2,1,0,4,75,27,9,69,85,9,95,240,7,32,128,130,35,32,28,66,43,40,24,82,63,23,83,123,12,72,231,15,127, + 59,23,116,23,19,117,71,7,24,77,99,15,67,111,15,71,101,8,36,2,128,128,252,128,127,60,11,32,1,132,16,130,18,141,24,67,107,9,32,3,68,194,15,175,15,38,0,11,0,128,1,128,2,80,63,25,32,0, + 24,65,73,11,69,185,15,83,243,16,32,0,24,81,165,8,130,86,77,35,6,155,163,88,203,5,24,66,195,30,70,19,19,24,80,133,15,32,1,75,211,8,32,254,108,133,8,79,87,20,65,32,9,41,0,0,7,0,128,0, + 0,2,128,2,68,87,15,66,1,16,92,201,16,24,76,24,17,133,17,34,128,0,30,66,127,64,34,115,0,119,73,205,9,66,43,11,109,143,15,24,79,203,11,90,143,15,131,15,155,31,65,185,15,86,87,11,35,128, + 128,253,0,69,7,6,130,213,33,1,0,119,178,15,142,17,66,141,74,83,28,6,36,7,0,0,4,128,82,39,18,76,149,12,67,69,21,32,128,79,118,15,32,0,130,0,32,8,131,206,32,2,79,83,9,100,223,14,102, + 113,23,115,115,7,24,65,231,12,130,162,32,4,68,182,19,130,102,93,143,8,69,107,29,24,77,255,12,143,197,72,51,7,76,195,15,132,139,85,49,15,130,152,131,18,71,81,23,70,14,11,36,0,10,0,128, + 2,69,59,9,89,151,15,66,241,11,76,165,12,71,43,15,75,49,13,65,12,23,132,37,32,0,179,115,130,231,95,181,16,132,77,32,254,67,224,8,65,126,20,79,171,8,32,2,89,81,5,75,143,6,80,41,8,34, + 2,0,128,24,81,72,9,32,0,130,0,35,17,0,0,255,77,99,39,95,65,36,67,109,15,24,69,93,11,77,239,5,95,77,23,35,128,1,0,128,24,86,7,8,132,167,32,2,69,198,41,130,202,33,0,26,120,75,44,24,89, + 51,15,71,243,12,70,239,11,24,84,3,11,66,7,11,71,255,10,32,21,69,155,35,88,151,12,32,128,74,38,10,65,210,8,74,251,5,65,226,5,75,201,13,32,3,65,9,41,146,41,40,0,0,0,9,1,0,1,0,2,91,99, + 19,32,35,106,119,13,70,219,15,83,239,12,137,154,32,2,67,252,19,36,128,0,0,4,1,130,196,32,2,130,8,91,107,8,32,0,135,81,24,73,211,8,132,161,73,164,13,36,0,8,0,128,2,105,123,26,139,67, + 76,99,15,34,1,0,128,135,76,83,156,20,92,104,8,67,251,30,24,86,47,27,123,207,12,24,86,7,15,71,227,8,32,4,65,20,20,131,127,32,0,130,123,32,0,71,223,26,32,19,90,195,22,71,223,15,84,200, + 6,32,128,133,241,24,84,149,9,67,41,25,36,0,0,0,22,0,88,111,49,32,87,66,21,5,77,3,27,123,75,7,71,143,19,135,183,71,183,19,130,171,74,252,5,131,5,89,87,17,32,1,132,18,130,232,68,11,10, + 33,1,128,70,208,16,66,230,18,147,18,130,254,223,255,75,27,23,65,59,15,135,39,155,255,34,128,128,254,104,92,8,33,0,128,65,32,11,65,1,58,33,26,0,130,0,72,71,18,78,55,17,76,11,19,86,101, + 12,75,223,11,89,15,11,24,76,87,15,75,235,15,131,15,72,95,7,85,71,11,72,115,11,73,64,6,34,1,128,128,66,215,9,34,128,254,128,134,14,33,128,255,67,102,5,32,0,130,16,70,38,11,66,26,57, + 88,11,8,24,76,215,34,78,139,7,95,245,7,32,7,24,73,75,23,32,128,131,167,130,170,101,158,9,82,49,22,118,139,6,32,18,67,155,44,116,187,9,108,55,14,80,155,23,66,131,15,93,77,10,131,168, + 32,128,73,211,12,24,75,187,22,32,4,96,71,20,67,108,19,132,19,120,207,8,32,5,76,79,15,66,111,21,66,95,8,32,3,190,211,111,3,8,211,212,32,20,65,167,44,34,75,0,79,97,59,13,32,33,112,63, + 10,65,147,19,69,39,19,143,39,24,66,71,9,130,224,65,185,43,94,176,12,65,183,24,71,38,8,24,72,167,7,65,191,38,136,235,24,96,167,12,65,203,62,115,131,13,65,208,42,175,235,67,127,6,32, + 4,76,171,29,114,187,5,32,71,65,211,5,65,203,68,72,51,8,164,219,32,0,172,214,71,239,58,78,3,27,66,143,15,77,19,15,147,31,35,33,53,51,21,66,183,10,173,245,66,170,30,150,30,34,0,0,23, + 80,123,54,76,1,16,73,125,15,82,245,11,167,253,24,76,85,12,70,184,5,32,254,131,185,37,254,0,128,1,0,128,133,16,117,158,18,92,27,38,65,3,17,130,251,35,17,0,128,254,24,69,83,39,140,243, + 121,73,19,109,167,7,81,41,15,24,95,175,12,102,227,15,121,96,11,24,95,189,7,32,3,145,171,154,17,24,77,47,9,33,0,5,70,71,37,68,135,7,32,29,117,171,11,69,87,15,24,79,97,19,24,79,149,23, + 131,59,32,1,75,235,5,72,115,11,72,143,7,132,188,71,27,46,131,51,32,0,69,95,6,175,215,32,21,131,167,81,15,19,151,191,151,23,131,215,71,43,5,32,254,24,79,164,24,74,109,8,77,166,13,65, + 176,26,88,162,5,98,159,6,171,219,120,247,6,79,29,8,99,169,10,103,59,19,65,209,35,131,35,91,25,19,112,94,15,83,36,8,173,229,33,20,0,88,75,43,71,31,12,65,191,71,33,1,0,130,203,32,254, + 131,4,68,66,7,67,130,6,104,61,13,173,215,38,13,1,0,0,0,2,128,67,111,28,74,129,16,104,35,19,79,161,16,87,14,7,138,143,132,10,67,62,36,114,115,5,162,151,67,33,16,108,181,15,143,151,67, + 5,5,24,100,242,15,170,153,34,0,0,14,65,51,34,32,55,79,75,9,32,51,74,7,10,65,57,38,132,142,32,254,72,0,14,139,163,32,128,80,254,8,67,158,21,65,63,7,32,4,72,227,27,95,155,12,67,119,19, + 124,91,24,149,154,72,177,34,97,223,8,155,151,24,108,227,15,88,147,16,72,117,19,68,35,11,92,253,15,70,199,15,24,87,209,17,32,2,87,233,7,32,1,24,88,195,10,119,24,8,32,3,81,227,24,65, + 125,21,35,128,128,0,25,76,59,48,24,90,187,9,97,235,12,66,61,11,91,105,19,24,79,141,11,24,79,117,15,24,79,129,27,90,53,13,130,13,32,253,131,228,24,79,133,40,69,70,8,66,137,31,65,33, + 19,96,107,8,68,119,29,66,7,5,68,125,16,65,253,19,65,241,27,24,90,179,13,24,79,143,18,33,128,128,130,246,32,254,130,168,68,154,36,77,51,9,97,47,5,167,195,32,21,131,183,78,239,27,155, + 195,78,231,14,201,196,77,11,6,32,5,73,111,37,97,247,12,77,19,31,155,207,78,215,19,162,212,69,17,14,66,91,19,80,143,57,78,203,39,159,215,32,128,93,134,8,24,80,109,24,66,113,15,169,215, + 66,115,6,32,4,69,63,33,32,0,101,113,7,86,227,35,143,211,36,49,53,51,21,1,77,185,14,65,159,28,69,251,34,67,56,8,33,9,0,24,107,175,25,90,111,12,110,251,11,119,189,24,119,187,34,87,15, + 9,32,4,66,231,37,90,39,7,66,239,8,84,219,15,69,105,23,24,85,27,27,87,31,11,33,1,128,76,94,6,32,1,85,241,7,33,128,128,106,48,10,33,128,128,69,136,11,133,13,24,79,116,49,84,236,8,24, + 91,87,9,32,5,165,255,69,115,12,66,27,15,159,15,24,72,247,12,74,178,5,24,80,64,15,33,0,128,143,17,77,89,51,130,214,24,81,43,7,170,215,74,49,8,159,199,143,31,139,215,69,143,5,32,254, + 24,81,50,35,181,217,84,123,70,143,195,159,15,65,187,16,66,123,7,65,175,15,65,193,29,68,207,39,79,27,5,70,131,6,32,4,68,211,33,33,67,0,83,143,14,159,207,143,31,140,223,33,0,128,24,80, + 82,14,24,93,16,23,32,253,65,195,5,68,227,40,133,214,107,31,7,32,5,67,115,27,87,9,8,107,31,43,66,125,6,32,0,103,177,23,131,127,72,203,36,32,0,110,103,8,155,163,73,135,6,32,19,24,112, + 99,10,65,71,11,73,143,19,143,31,126,195,5,24,85,21,9,24,76,47,14,32,254,24,93,77,36,68,207,11,39,25,0,0,255,128,3,128,4,66,51,37,95,247,13,82,255,24,76,39,19,147,221,66,85,27,24,118, + 7,8,24,74,249,12,76,74,8,91,234,8,67,80,17,131,222,33,253,0,121,30,44,73,0,16,69,15,6,32,0,65,23,38,69,231,12,65,179,6,98,131,16,86,31,27,24,108,157,14,80,160,8,24,65,46,17,33,4,0, + 96,2,18,144,191,65,226,8,68,19,5,171,199,80,9,15,180,199,67,89,5,32,255,24,79,173,28,174,201,24,79,179,50,32,1,24,122,5,10,82,61,10,180,209,83,19,8,32,128,24,80,129,27,111,248,43,131, + 71,24,115,103,8,67,127,41,78,213,24,100,247,19,66,115,39,75,107,5,32,254,165,219,78,170,40,24,112,163,49,32,1,97,203,6,65,173,64,32,0,83,54,7,133,217,88,37,12,32,254,131,28,33,128, + 3,67,71,44,84,183,6,32,5,69,223,33,96,7,7,123,137,16,192,211,24,112,14,9,32,255,67,88,29,68,14,10,84,197,38,33,0,22,116,47,50,32,87,106,99,9,116,49,15,89,225,15,97,231,23,70,41,19, + 82,85,8,93,167,6,32,253,132,236,108,190,7,89,251,5,116,49,58,33,128,128,131,234,32,15,24,74,67,38,70,227,24,24,83,45,23,89,219,12,70,187,12,89,216,19,32,2,69,185,24,141,24,70,143,66, + 24,82,119,56,78,24,10,32,253,133,149,132,6,24,106,233,7,69,198,48,178,203,81,243,12,68,211,15,106,255,23,66,91,15,69,193,7,100,39,10,24,83,72,16,176,204,33,19,0,88,207,45,68,21,12, + 68,17,10,65,157,53,68,17,6,32,254,92,67,10,65,161,25,69,182,43,24,118,91,47,69,183,18,181,209,111,253,12,89,159,8,66,112,12,69,184,45,35,0,0,0,9,24,80,227,26,73,185,16,118,195,15,131, + 15,33,1,0,65,59,15,66,39,27,160,111,66,205,12,148,111,143,110,33,128,128,156,112,24,81,199,8,75,199,23,66,117,20,155,121,32,254,68,126,12,72,213,29,134,239,149,123,89,27,16,148,117, + 65,245,8,24,71,159,14,141,134,134,28,73,51,55,109,77,15,105,131,11,68,67,11,76,169,27,107,209,12,102,174,8,32,128,72,100,18,116,163,56,79,203,11,75,183,44,85,119,19,71,119,23,151,227, + 32,1,93,27,8,65,122,5,77,102,8,110,120,20,66,23,8,66,175,17,66,63,12,133,12,79,35,8,74,235,33,67,149,16,69,243,15,78,57,15,69,235,16,67,177,7,151,192,130,23,67,84,29,141,192,174,187, + 77,67,15,69,11,12,159,187,77,59,10,199,189,24,70,235,50,96,83,19,66,53,23,105,65,19,77,47,12,163,199,66,67,37,78,207,50,67,23,23,174,205,67,228,6,71,107,13,67,22,14,66,85,11,83,187, + 38,124,47,49,95,7,19,66,83,23,67,23,19,24,96,78,17,80,101,16,71,98,40,33,0,7,88,131,22,24,89,245,12,84,45,12,102,213,5,123,12,9,32,2,126,21,14,43,255,0,128,128,0,0,20,0,128,255,128, + 3,126,19,39,32,75,106,51,7,113,129,15,24,110,135,19,126,47,15,115,117,11,69,47,11,32,2,109,76,9,102,109,9,32,128,75,2,10,130,21,32,254,69,47,6,32,3,94,217,47,32,0,65,247,10,69,15,46, + 65,235,31,65,243,15,101,139,10,66,174,14,65,247,16,72,102,28,69,17,14,84,243,9,165,191,88,47,48,66,53,12,32,128,71,108,6,203,193,32,17,75,187,42,73,65,16,65,133,52,114,123,9,167,199, + 69,21,37,86,127,44,75,171,11,180,197,78,213,12,148,200,81,97,46,24,95,243,9,32,4,66,75,33,113,103,9,87,243,36,143,225,24,84,27,31,90,145,8,148,216,67,49,5,24,84,34,14,75,155,27,67, + 52,13,140,13,36,0,20,0,128,255,24,135,99,46,88,59,43,155,249,80,165,7,136,144,71,161,23,32,253,132,33,32,254,88,87,44,136,84,35,128,0,0,21,81,103,5,94,47,44,76,51,12,143,197,151,15, + 65,215,31,24,64,77,13,65,220,20,65,214,14,71,4,40,65,213,13,32,0,130,0,35,21,1,2,0,135,0,34,36,0,72,134,10,36,1,0,26,0,130,134,11,36,2,0,14,0,108,134,11,32,3,138,23,32,4,138,11,34, + 5,0,20,134,33,34,0,0,6,132,23,32,1,134,15,32,18,130,25,133,11,37,1,0,13,0,49,0,133,11,36,2,0,7,0,38,134,11,36,3,0,17,0,45,134,11,32,4,138,35,36,5,0,10,0,62,134,23,32,6,132,23,36,3, + 0,1,4,9,130,87,131,167,133,11,133,167,133,11,133,167,133,11,37,3,0,34,0,122,0,133,11,133,167,133,11,133,167,133,11,133,167,34,50,0,48,130,1,34,52,0,47,134,5,8,49,49,0,53,98,121,32, + 84,114,105,115,116,97,110,32,71,114,105,109,109,101,114,82,101,103,117,108,97,114,84,84,88,32,80,114,111,103,103,121,67,108,101,97,110,84,84,50,48,48,52,47,130,2,53,49,53,0,98,0,121, + 0,32,0,84,0,114,0,105,0,115,0,116,0,97,0,110,130,15,32,71,132,15,36,109,0,109,0,101,130,9,32,82,130,5,36,103,0,117,0,108,130,29,32,114,130,43,34,84,0,88,130,35,32,80,130,25,34,111, + 0,103,130,1,34,121,0,67,130,27,32,101,132,59,32,84,130,31,33,0,0,65,155,9,34,20,0,0,65,11,6,130,8,135,2,33,1,1,130,9,8,120,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1,11,1,12,1,13,1,14, + 1,15,1,16,1,17,1,18,1,19,1,20,1,21,1,22,1,23,1,24,1,25,1,26,1,27,1,28,1,29,1,30,1,31,1,32,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0, + 22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,130,187,8,66,33,0,34,0,35,0,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44,0,45,0,46,0,47,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0, + 57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,130,243,9,75,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0,78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0, + 92,0,93,0,94,0,95,0,96,0,97,1,33,1,34,1,35,1,36,1,37,1,38,1,39,1,40,1,41,1,42,1,43,1,44,1,45,1,46,1,47,1,48,1,49,1,50,1,51,1,52,1,53,1,54,1,55,1,56,1,57,1,58,1,59,1,60,1,61,1,62,1, + 63,1,64,1,65,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,0,239,0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170, + 0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0,207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0, + 212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0,114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0, + 161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,14,117,110,105,99,111,100,101,35,48,120,48,48,48,49,141,14,32,50,141,14,32,51,141,14,32,52,141,14,32,53,141,14,32,54,141,14,32,55,141, + 14,32,56,141,14,32,57,141,14,32,97,141,14,32,98,141,14,32,99,141,14,32,100,141,14,32,101,141,14,32,102,140,14,33,49,48,141,14,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49, + 141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,45,49,102,6,100,101,108,101,116,101,4,69,117,114, + 111,140,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236, + 32,56,141,236,32,56,141,236,32,56,65,220,13,32,57,65,220,13,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141, + 239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,35,57,102,0,0,5,250,72,249,98,247, +}; + +static const char* GetDefaultCompressedFontDataProggyClean(int* out_size) +{ + *out_size = proggy_clean_ttf_compressed_size; + return (const char*)proggy_clean_ttf_compressed_data; +} + +//----------------------------------------------------------------------------- +// [SECTION] Default font data (ProggyVector-minimal.ttf) +//----------------------------------------------------------------------------- +// Based on ProggyVector.ttf, Copyright (c) 2019,2023 Tristan Grimmer / Copyright (c) 2018 Source Foundry Authors / Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. +// MIT license + public domain, see licenses at https://github.com/bluescan/proggyfonts/tree/master/ProggyVector +//----------------------------------------------------------------------------- +// See misc/fonts/ProggyVector-ExtractScript.txt for FontForge script to create this from ProggyVector.ttf +//----------------------------------------------------------------------------- + +// File: 'ProggyVector-minimal.ttf' (23952 bytes) +// Exported using binary_to_compressed_c.exe -u8 "ProggyVector-minimal.ttf" proggy_vector_minimal_ttf +static const unsigned int proggy_vector_minimal_ttf_compressed_size = 18519; +static const unsigned char proggy_vector_minimal_ttf_compressed_data[18519] = +{ + 87,188,0,0,0,0,0,0,0,0,93,144,0,4,0,0,55,0,1,0,0,0,14,0,128,0,3,0,96,70,70,84,77,165,245,48,76,0,0,93,116,130,21,38,28,71,68,69,70,0,37,130,9,34,0,93,92,130,5,44,24,79,83,47,50,135, + 98,111,82,0,0,1,104,130,15,44,96,99,109,97,112,10,236,8,177,0,0,3,88,130,19,44,82,99,118,116,32,0,34,2,136,0,0,4,172,130,31,38,4,103,97,115,112,255,255,130,89,34,0,93,84,130,15,56, + 8,103,108,121,102,169,208,238,39,0,0,6,56,0,0,84,32,104,101,97,100,39,214,168,186,130,27,32,236,130,3,33,54,104,130,16,35,6,225,0,231,130,75,32,36,130,15,40,36,104,109,116,120,37,72, + 32,85,130,15,32,200,130,3,40,142,108,111,99,97,26,185,47,212,130,95,32,176,130,15,40,136,109,97,120,112,0,201,0,151,130,11,32,72,130,47,43,32,110,97,109,101,10,160,159,163,0,0,90,131, + 143,44,68,112,111,115,116,153,185,200,234,0,0,91,156,130,35,32,184,132,235,45,1,0,0,96,193,239,192,95,15,60,245,0,11,4,130,54,37,0,0,225,81,71,241,131,8,43,228,205,29,41,255,247,255, + 2,2,162,3,161,130,15,34,8,0,2,130,5,131,2,32,1,130,225,38,182,254,184,0,143,2,102,130,31,34,196,2,162,132,73,131,25,135,3,32,4,132,17,37,195,0,104,0,5,0,134,49,131,6,132,3,32,46,132, + 5,36,2,2,102,1,144,131,29,39,2,138,2,188,0,47,0,140,131,7,40,255,92,1,224,0,49,1,2,0,131,0,32,9,132,57,143,61,43,0,66,105,114,100,0,64,0,32,32,172,3,132,131,47,3,182,1,72,32,63,0,255, + 223,253,0,0,2,14,3,182,130,48,38,32,0,1,2,102,0,34,130,9,32,0,130,7,132,3,35,0,237,0,169,130,147,46,91,0,19,0,29,1,10,0,168,0,205,0,46,0,41,130,5,32,83,130,25,44,65,0,67,0,132,0,76, + 0,75,0,40,0,72,130,11,40,70,0,66,0,63,0,239,0,209,130,33,52,45,0,44,0,81,255,251,0,18,0,79,0,70,0,69,0,94,0,117,0,51,130,7,34,100,0,61,130,5,34,108,0,38,130,21,36,58,0,86,0,58,130, + 57,42,70,0,24,0,60,0,29,0,2,0,9,130,47,50,55,0,148,0,62,0,154,0,61,255,247,0,167,0,68,0,96,0,82,130,51,34,62,0,66,130,105,40,97,0,166,0,118,0,113,0,141,130,97,32,97,130,71,32,95,130, + 3,40,129,0,106,0,128,0,84,0,50,130,183,32,38,130,85,38,101,0,92,1,6,0,102,130,147,36,0,0,232,0,105,130,17,34,102,0,18,130,187,34,99,0,160,130,33,38,135,0,40,0,44,0,178,130,9,34,159, + 0,150,130,9,52,161,0,163,0,238,0,83,0,53,0,227,0,198,0,172,0,122,0,116,0,13,132,1,32,96,130,139,32,18,136,3,32,0,130,71,33,98,0,133,1,33,100,0,133,1,32,4,132,195,32,58,130,195,131, + 3,36,75,0,4,0,74,134,1,32,18,130,33,32,94,130,187,32,68,136,3,32,20,130,197,32,62,130,215,131,3,34,109,0,134,132,1,33,69,0,131,195,32,69,130,195,131,3,34,44,0,24,130,15,32,97,132,3, + 36,52,0,95,0,52,130,123,130,166,33,0,3,130,4,131,3,34,28,0,1,130,9,36,0,0,76,0,3,132,9,32,28,130,111,32,48,130,17,46,8,0,8,0,2,0,0,0,126,0,255,32,172,255,255,130,9,34,32,0,160,131, + 9,37,255,227,255,194,224,22,132,43,130,20,131,2,34,1,6,0,136,14,35,1,2,0,0,132,55,130,6,136,2,8,152,1,0,0,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, + 30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89, + 90,91,92,93,94,95,96,97,0,134,135,137,139,147,152,158,163,162,164,166,165,167,169,171,170,172,173,175,174,176,177,179,181,180,182,184,183,188,187,189,190,0,114,100,101,105,0,120,161, + 112,107,0,118,106,0,136,154,0,115,0,0,103,119,132,161,39,108,124,0,168,186,129,99,110,131,12,38,109,125,0,98,130,133,151,131,10,131,3,37,185,0,193,0,0,194,131,9,33,0,121,130,5,47,132, + 140,131,141,138,143,144,145,142,149,150,0,148,156,157,155,130,18,32,113,130,3,32,122,130,3,130,2,34,34,2,136,130,5,33,42,0,133,1,8,186,80,0,100,0,170,1,22,1,132,2,2,2,16,2,36,2,56, + 2,104,2,124,2,166,2,182,2,208,2,226,3,26,3,52,3,132,3,214,3,246,4,46,4,126,4,150,4,238,5,66,5,120,5,194,5,224,5,244,6,14,6,84,6,224,7,12,7,80,7,122,7,162,7,184,7,208,8,0,8,24,8,46, + 8,76,8,116,8,132,8,170,8,202,8,254,9,42,9,98,9,160,9,248,10,10,10,66,10,98,10,152,10,208,10,246,11,20,11,38,11,68,11,86,11,116,11,128,11,152,11,234,12,52,12,100,12,180,12,238,13,16, + 13,108,13,148,13,194,13,236,14,18,14,38,14,96,14,128,14,176,14,222,15,18,15,60,15,122,15,152,15,190,15,224,16,18,16,76,16,146,16,178,16,240,16,254,17,68,17,122,130,1,8,225,158,17,228, + 18,12,18,88,18,142,18,162,19,32,19,66,19,176,19,246,20,40,20,56,20,68,20,192,20,206,21,8,21,34,21,80,21,160,21,184,21,232,22,4,22,32,22,62,22,88,22,146,22,198,23,4,23,80,23,196,24, + 40,24,96,24,146,24,208,25,46,25,116,25,188,25,228,26,48,26,84,26,114,26,156,26,212,26,244,27,16,27,52,27,100,27,154,27,244,28,46,28,98,28,162,29,10,29,82,29,144,30,0,30,68,30,134,30, + 210,31,38,31,84,31,122,31,212,32,68,32,176,33,36,33,182,34,50,34,188,35,44,35,128,35,206,36,24,36,104,36,192,36,238,37,20,37,64,37,118,37,216,38,38,38,104,38,160,38,222,39,60,39,134, + 39,174,39,250,40,50,40,100,40,158,40,226,41,42,41,92,41,178,42,16,0,2,0,34,0,0,1,50,2,170,0,3,0,7,0,46,177,1,0,47,60,178,7,4,0,237,50,177,6,5,220,60,178,3,2,130,10,34,0,177,3,131,22, + 32,5,131,22,39,178,7,6,1,252,60,178,1,131,23,53,51,17,33,17,39,51,17,35,34,1,16,238,204,204,2,170,253,86,34,2,102,0,130,83,8,71,237,255,255,1,126,2,228,0,14,0,20,0,0,37,50,23,22,20, + 14,1,35,34,39,38,53,52,55,54,19,3,35,3,53,51,1,53,50,17,6,33,25,15,32,19,21,21,19,85,15,80,18,113,140,42,13,47,30,9,19,19,24,41,19,19,1,221,254,160,1,96,123,0,131,75,38,169,1,185,1, + 191,2,189,132,159,34,0,1,17,131,115,39,51,17,1,104,87,254,234,87,130,25,35,4,254,252,1,130,3,61,0,2,0,1,0,5,2,102,2,183,0,5,0,46,0,0,19,51,54,55,35,6,15,1,35,62,1,55,35,53,130,12,130, + 14,38,53,51,55,51,14,1,7,134,5,33,21,35,131,11,34,21,35,7,131,34,51,229,123,31,11,123,11,50,52,80,10,32,10,129,149,7,13,14,7,133,152,132,12,32,123,132,5,40,121,140,8,26,8,125,144,53, + 79,130,30,51,1,10,112,46,46,178,195,37,121,37,71,30,49,49,29,73,194,37,120,37,131,3,36,73,29,98,30,71,131,22,32,0,130,169,8,40,91,255,237,2,41,2,210,0,8,0,18,0,72,0,0,1,21,54,55,54, + 53,52,39,38,39,53,6,7,6,29,1,6,23,22,19,46,1,39,38,35,38,131,18,39,22,23,30,1,23,22,23,53,130,12,8,166,52,55,54,55,53,51,21,20,30,4,23,21,39,38,47,2,34,39,21,22,23,22,21,20,7,6,7,21, + 1,102,56,26,31,31,32,132,62,25,8,2,26,30,44,1,1,1,3,7,12,25,79,59,21,30,13,23,16,36,46,82,53,50,53,61,71,82,56,19,21,20,20,11,22,35,25,33,16,8,8,98,43,54,58,63,74,1,54,205,10,20,37, + 49,39,29,21,91,194,5,62,20,6,10,25,34,24,254,84,10,37,11,1,1,5,13,23,85,12,15,5,9,6,13,2,217,11,45,42,144,45,50,6,57,57,3,10,3,5,4,6,3,81,10,14,7,8,2,1,202,16,43,46,71,72,50,49,4,58, + 0,5,0,19,0,17,2,84,2,172,130,9,38,22,0,38,0,55,0,71,130,219,37,0,7,35,18,19,3,130,166,33,51,50,133,228,38,35,34,7,6,20,23,6,65,239,7,33,51,50,131,193,33,1,22,131,30,32,52,130,239,40, + 38,34,14,2,21,20,55,20,7,140,33,8,124,2,40,254,177,58,96,234,160,60,13,34,7,11,24,20,20,20,19,21,52,17,5,165,43,54,52,46,38,39,36,61,55,41,40,254,24,13,34,27,20,20,5,10,27,12,27,23, + 20,10,204,68,33,25,67,41,39,67,30,26,68,42,40,2,172,253,200,98,1,140,1,14,253,205,28,10,1,18,20,19,32,18,19,38,11,27,77,38,37,38,53,57,36,36,37,40,51,54,1,162,18,18,20,38,11,23,11, + 4,8,18,22,14,27,28,75,37,17,37,35,56,73,40,16,38,36,0,130,0,63,3,0,29,255,243,2,98,2,209,0,11,0,37,0,85,0,0,19,62,1,53,52,35,34,6,7,6,23,22,3,20,23,132,223,45,63,1,54,55,62,2,55,38, + 39,38,47,1,38,39,130,26,43,55,38,53,54,55,54,51,50,30,1,29,1,130,208,41,7,30,3,23,54,61,1,54,38,59,132,13,34,22,23,34,131,227,37,6,43,1,34,39,38,130,22,8,147,237,30,57,71,34,40,3,14, + 38,19,102,53,29,57,18,15,53,41,12,5,6,7,4,3,2,26,20,34,19,67,17,27,47,26,22,50,86,2,75,42,52,35,78,35,34,24,59,33,53,40,46,26,38,1,2,1,81,20,19,36,36,49,43,47,5,10,40,81,104,8,100, + 73,70,13,1,221,18,49,44,61,35,14,53,35,17,254,239,71,49,27,13,4,23,6,3,3,4,5,1,1,34,26,41,26,86,21,36,36,33,38,163,66,66,99,37,23,23,60,24,38,41,45,31,41,42,69,53,57,33,46,91,26,6, + 24,108,52,51,38,45,63,1,52,64,63,64,85,20,127,130,250,52,0,1,1,10,1,186,1,102,2,191,0,3,0,0,1,17,51,17,1,10,92,130,16,34,5,254,251,130,14,41,0,168,255,174,1,141,3,7,0,7,130,12,55,6, + 16,23,35,38,16,55,1,141,132,132,80,149,149,3,7,217,254,88,216,224,1,157,220,130,26,39,0,205,255,179,1,178,3,12,132,39,8,48,22,16,7,35,54,16,39,1,29,149,149,80,132,132,3,12,220,254, + 96,221,216,1,175,210,0,0,1,0,46,0,90,2,57,2,100,0,27,0,0,19,39,54,55,22,23,53,51,21,55,131,7,8,64,7,23,22,23,7,46,1,39,21,35,53,7,39,54,219,173,19,25,129,43,87,88,55,33,14,30,176,88, + 54,33,44,33,109,33,87,174,42,99,1,100,96,28,40,70,24,186,186,48,30,17,20,49,96,48,30,19,68,18,59,18,196,196,92,67,56,132,203,48,0,41,0,100,2,61,2,85,0,11,0,0,37,53,35,53,51,130,94, + 49,51,21,35,21,1,8,223,223,84,225,225,100,208,80,209,209,80,208,130,135,44,205,255,85,1,125,0,141,0,25,0,0,23,38,130,136,45,54,55,34,38,39,38,53,52,55,54,51,50,23,22,65,207,5,8,44, + 6,241,6,30,59,17,7,7,20,29,5,4,43,13,15,32,19,22,3,13,91,17,171,8,42,51,37,15,18,29,13,13,15,49,18,4,19,20,31,6,15,17,92,86,16,130,83,40,83,1,52,2,23,1,133,0,5,130,219,46,53,33,21, + 22,21,83,1,195,1,1,52,81,40,25,16,130,156,38,1,0,237,255,255,1,126,130,115,35,13,0,0,4,139,109,8,34,20,1,85,47,25,11,21,44,13,16,30,20,22,1,9,10,19,33,48,18,5,20,20,63,0,0,1,0,65,255, + 208,2,41,2,230,131,83,8,37,23,0,55,51,0,7,65,1,38,99,95,254,217,98,48,2,81,197,253,176,198,0,0,3,0,67,255,243,2,38,2,203,0,7,0,18,0,32,130,247,51,50,17,52,39,6,7,22,19,38,35,34,7,6, + 21,20,23,54,55,5,16,67,111,6,32,16,131,221,8,57,1,56,148,8,104,149,35,185,33,78,93,35,21,8,63,63,1,1,137,45,60,120,60,61,241,121,60,61,72,1,34,48,46,130,182,72,1,232,72,111,77,102, + 49,46,79,78,54,254,240,68,23,92,91,180,1,109,92,88,130,198,130,147,39,132,0,0,1,254,2,189,0,130,199,8,34,51,53,51,17,6,7,38,53,54,55,51,17,51,21,132,144,32,111,1,107,35,94,142,82,2, + 0,25,89,82,33,80,26,253,149,82,133,51,44,76,0,0,2,30,2,202,0,54,0,0,1,34,130,48,33,62,1,131,137,36,21,20,14,1,7,130,2,49,6,15,1,14,5,7,33,21,33,53,52,62,4,63,1,62,3,55,69,50,5,8,102, + 46,1,35,1,27,70,132,1,96,93,23,100,67,65,30,12,8,20,49,10,30,34,18,9,14,20,19,20,28,17,1,100,254,46,27,33,39,42,40,12,22,17,14,9,18,11,47,9,5,37,16,53,15,2,123,73,58,29,51,14,55,52, + 89,49,62,15,12,30,49,11,33,34,16,7,18,16,18,22,27,17,82,63,17,26,34,38,43,40,13,22,19,12,12,20,13,61,40,19,24,52,33,15,19,130,211,44,75,255,243,2,34,2,203,0,56,0,0,19,54,131,154,69, + 120,6,69,128,6,37,43,1,38,39,46,1,69,175,5,33,22,51,68,234,6,34,43,1,53,68,245,11,8,161,7,97,120,73,74,64,58,26,16,6,31,97,93,37,22,69,67,127,25,12,14,54,35,14,23,31,65,23,62,45,131, + 34,10,44,44,67,86,77,107,30,10,36,33,72,51,88,25,26,2,172,31,29,26,56,34,29,46,17,78,24,23,68,36,51,101,55,55,1,1,4,10,3,5,11,95,30,5,15,77,25,32,65,34,36,78,63,20,27,54,28,29,21,7, + 10,0,2,0,40,0,0,2,64,2,189,0,6,0,17,0,0,55,51,17,14,3,39,1,51,17,51,21,35,21,35,53,33,136,242,61,108,39,24,106,1,26,135,119,119,90,254,185,245,1,114,87,170,61,38,6,1,180,254,56,78, + 167,167,0,0,0,1,0,72,130,227,32,23,130,63,32,36,135,227,36,21,20,7,14,1,132,218,34,2,39,53,136,214,8,69,39,38,34,7,17,33,21,33,196,47,35,120,69,68,109,50,80,22,36,12,14,69,41,20,10, + 88,96,129,37,11,9,15,17,53,170,66,1,135,254,214,1,194,14,65,64,109,141,62,25,11,1,1,5,12,7,3,97,46,90,30,29,48,22,36,15,47,35,1,96,79,130,175,38,67,255,246,2,38,2,191,130,173,32,54, + 130,175,136,95,66,149,6,38,22,39,54,51,50,23,22,70,9,6,67,123,7,39,54,59,1,30,2,23,21,38,130,149,8,91,35,6,7,6,214,34,68,101,25,9,53,30,51,69,34,37,21,8,46,51,117,105,57,60,61,56,117, + 130,58,49,9,3,89,89,104,9,19,7,25,32,30,17,8,60,44,19,9,9,73,69,51,108,43,92,30,39,99,42,22,43,46,75,59,36,12,249,97,63,62,226,63,60,85,71,113,38,43,192,83,87,1,4,9,4,3,88,32,1,2,71, + 71,0,130,0,8,62,1,0,70,0,0,2,28,2,189,0,9,0,0,9,1,35,18,55,54,55,33,53,33,2,28,254,244,105,120,101,22,17,254,155,1,214,2,150,253,106,1,39,232,54,41,79,0,0,3,0,66,255,243,2,39,2,203, + 0,14,0,28,0,58,130,209,33,20,23,132,211,34,52,39,38,131,210,34,55,50,53,134,9,32,21,130,24,34,37,20,7,66,58,6,36,35,34,38,53,52,130,91,33,38,39,68,96,6,130,244,8,95,167,82,26,33,65, + 40,37,37,37,68,69,35,37,141,125,32,30,63,93,24,8,72,23,1,0,121,78,29,31,16,58,170,113,128,39,24,75,43,23,32,9,14,60,61,208,61,61,198,100,28,10,36,37,128,37,35,35,35,145,115,60,28,30, + 67,22,28,85,24,7,126,135,26,17,46,46,75,49,38,115,104,97,73,49,47,16,11,26,32,25,38,35,76,50,49,49,51,130,222,39,0,2,0,63,255,249,2,35,130,175,38,13,0,53,0,0,19,20,66,171,11,40,18, + 38,39,53,22,23,30,1,54,130,152,36,6,7,14,1,34,133,156,130,14,66,251,10,8,97,6,7,38,163,134,68,34,37,79,29,23,78,30,34,59,32,72,36,31,19,36,61,35,100,18,18,19,39,63,81,40,86,30,15,23, + 11,61,139,130,59,34,12,15,23,42,93,47,63,36,1,219,164,43,43,78,118,36,11,41,42,253,206,1,17,78,15,6,1,2,1,18,50,198,36,15,30,16,15,33,90,44,42,71,67,19,97,89,49,65,73,62,114,65,133, + 46,22,4,2,133,167,45,239,0,111,1,129,2,66,0,15,0,32,0,0,1,72,26,14,34,3,22,21,130,17,132,159,32,52,130,172,40,54,50,1,129,22,20,23,39,20,130,0,57,23,55,21,5,45,44,22,19,48,13,26,11, + 6,5,10,29,13,31,1,251,33,18,20,20,16,35,130,5,49,42,13,254,236,17,56,24,20,19,5,9,28,13,31,13,25,12,5,130,108,36,2,0,209,255,197,132,107,38,31,0,47,0,0,23,54,130,81,35,34,38,39,38, + 132,89,69,248,10,37,7,6,7,46,3,19,142,137,60,209,42,14,18,15,19,29,5,4,5,9,29,13,15,31,20,22,3,3,4,21,29,51,29,6,9,8,8,171,139,147,62,9,36,19,24,42,29,13,13,31,12,26,12,5,20,20,31, + 6,12,18,29,12,54,34,58,18,7,13,11,12,2,11,138,162,130,146,8,57,0,1,0,41,0,116,2,57,2,75,0,14,0,0,45,1,53,36,55,21,14,2,7,30,2,31,1,2,57,253,240,1,140,132,91,126,156,52,28,74,115,78, + 130,116,196,78,148,49,86,33,44,55,19,9,26,41,27,45,132,207,38,45,0,205,2,61,1,245,75,31,5,36,55,53,33,21,37,130,3,44,45,2,16,253,240,2,16,205,81,81,216,80,80,133,99,58,44,0,114,2,60, + 2,73,0,11,0,0,1,37,53,4,23,21,5,53,62,1,55,54,1,213,254,87,130,98,60,253,240,28,73,58,195,1,93,151,85,148,49,78,196,86,9,26,21,68,0,2,0,81,255,255,2,33,2,223,130,151,130,107,75,199, + 14,61,3,39,62,1,51,50,22,29,1,6,15,1,14,1,29,1,35,53,54,55,62,2,53,54,39,38,43,1,34,6,75,223,12,56,124,72,33,130,78,106,117,2,85,32,29,44,96,2,87,17,48,45,1,25,38,73,9,37,94,75,243, + 12,56,156,46,52,85,86,73,4,77,60,22,21,44,30,55,54,72,61,13,34,45,25,41,20,29,57,131,191,44,2,255,251,255,225,2,162,2,224,0,16,0,95,130,193,36,35,38,7,6,7,74,116,10,46,19,22,23,14, + 1,7,6,35,34,39,38,39,46,1,53,65,206,8,33,21,20,130,39,42,6,35,17,38,35,53,6,7,6,46,1,68,101,6,8,203,54,30,1,31,1,22,23,51,22,55,54,61,1,54,39,46,2,34,6,7,14,2,29,1,20,23,22,23,62,1, + 1,111,10,10,17,53,6,6,22,32,37,38,29,29,62,17,236,3,50,12,49,40,78,96,83,79,104,75,45,18,27,56,132,64,54,196,88,31,8,14,39,14,19,56,18,20,38,30,69,46,33,53,83,43,60,26,43,17,7,14,9, + 12,34,12,11,5,2,38,18,71,53,42,37,32,84,77,27,82,82,122,81,117,1,229,1,8,27,94,64,32,32,35,33,60,91,29,8,254,167,3,59,10,43,19,37,25,32,109,63,104,50,98,64,142,54,26,98,37,60,18,26, + 47,15,7,254,242,1,45,34,16,14,6,27,29,62,86,119,66,37,2,22,10,4,14,9,13,2,23,10,6,7,25,36,16,33,7,2,11,31,113,93,47,12,115,100,87,3,1,41,0,0,2,0,18,130,4,45,86,2,189,0,10,0,23,0,0, + 19,51,46,3,39,130,202,8,61,1,15,1,35,54,19,51,22,18,30,1,23,35,39,202,213,13,39,30,18,7,13,19,37,30,32,54,105,41,188,123,28,83,63,39,15,104,56,1,3,44,132,98,62,23,43,67,125,100,100, + 183,124,2,65,85,254,254,192,120,46,183,0,130,0,38,3,0,79,255,255,2,58,132,87,45,21,0,44,0,0,55,51,50,55,54,52,38,39,38,70,243,10,42,43,1,3,17,51,50,23,22,23,20,7,71,197,5,68,240,7, + 8,88,175,149,124,26,10,20,20,40,80,149,127,104,23,8,33,32,82,115,96,207,112,64,60,2,6,13,21,6,12,30,17,84,26,41,66,69,129,78,67,24,67,51,16,32,78,60,21,28,57,21,24,253,144,2,189,46, + 46,86,39,15,30,26,7,13,10,7,22,38,47,76,94,50,49,0,1,0,70,255,243,2,25,2,203,0,25,0,0,37,6,76,84,10,39,21,38,35,34,7,6,21,16,131,151,8,41,55,2,25,76,90,147,76,78,139,71,91,88,78,79, + 87,98,49,49,197,58,68,20,19,25,38,95,96,171,232,90,44,39,97,58,71,74,142,254,225,34,10,15,130,218,39,0,2,0,69,0,0,2,44,130,219,34,12,0,23,134,217,34,53,52,39,132,219,133,208,8,32,21, + 16,7,6,35,170,86,153,32,13,50,25,23,41,62,83,101,189,172,63,63,172,55,71,78,142,54,78,157,56,30,11,18,131,173,39,85,87,179,254,250,66,22,0,130,163,32,94,130,79,32,35,130,79,38,11,0, + 0,51,17,33,21,135,1,49,94,1,196,254,161,1,53,254,203,1,96,2,189,79,208,80,254,80,130,43,32,117,130,43,36,41,2,190,0,12,131,43,34,50,54,51,131,44,53,51,21,35,17,117,28,75,60,1,17,254, + 174,246,246,2,189,1,76,222,76,254,184,131,171,34,1,0,51,130,255,32,40,130,255,32,31,135,255,74,164,8,32,21,130,177,65,3,8,8,53,53,35,53,51,2,40,86,116,71,56,61,36,75,80,81,139,96,79, + 25,38,43,58,109,47,49,194,60,45,134,230,57,70,24,29,45,94,170,175,94,97,50,98,25,19,26,71,71,146,254,226,30,189,78,0,130,143,32,69,130,143,32,36,135,187,79,93,5,55,35,17,33,17,69,101, + 1,20,102,102,254,236,2,189,254,225,1,31,253,67,1,78,254,178,130,144,34,1,0,100,130,47,32,3,134,47,37,53,51,17,35,53,33,130,188,47,51,21,100,157,157,1,159,157,157,80,2,30,79,79,253, + 226,68,115,6,36,61,255,247,1,222,130,43,32,17,131,187,33,7,6,66,58,7,131,52,61,17,20,1,169,38,51,29,63,183,185,80,23,28,191,1,36,41,38,7,5,77,30,36,95,1,137,79,254,40,132,134,151,32, + 100,130,59,53,24,0,0,51,17,51,17,62,3,55,51,6,7,30,2,23,35,46,3,39,6,7,130,159,51,38,116,86,55,20,119,194,97,126,102,52,19,122,29,90,66,42,16,58,19,130,173,52,200,38,115,85,54,20,191, + 95,173,143,72,27,43,129,96,60,23,57,20,254,238,130,79,32,108,130,183,32,57,130,79,32,5,133,79,41,33,21,108,101,1,104,2,189,253,147,134,171,32,38,130,31,32,68,130,31,50,20,0,0,1,3,35, + 39,46,2,39,17,35,17,51,22,23,62,2,55,130,229,8,40,1,236,145,77,21,13,39,54,17,88,135,90,45,18,86,24,8,136,88,2,102,254,142,56,32,101,137,44,253,154,2,189,229,115,45,218,59,22,253,67, + 0,72,87,8,32,35,133,247,37,51,17,51,30,3,23,130,192,8,38,35,46,1,39,38,39,17,70,128,31,92,69,43,17,97,128,31,93,34,72,22,2,189,69,210,156,98,38,2,59,253,67,70,210,78,164,49,253,197, + 130,63,48,2,0,58,255,247,2,46,2,198,0,13,0,29,0,0,18,16,72,101,5,46,16,39,38,35,34,7,19,34,17,16,55,54,50,22,23,130,1,8,58,21,16,7,6,164,34,33,77,78,33,34,34,35,76,75,35,110,250,141, + 47,93,54,24,48,32,61,141,50,1,242,254,216,68,65,65,64,1,48,64,67,67,253,193,1,103,1,15,66,23,11,11,22,46,94,176,254,239,65,21,130,102,39,0,2,0,86,0,0,2,46,130,167,41,12,0,26,0,0,19, + 51,50,55,54,79,194,5,67,216,8,8,51,22,20,7,6,43,1,17,187,117,56,33,11,10,39,39,40,78,109,101,218,125,65,35,10,19,16,49,189,117,1,104,21,7,7,37,61,60,37,34,253,144,2,189,53,30,28,49, + 101,39,119,254,230,130,87,36,58,255,159,2,104,130,191,42,23,0,32,0,0,37,30,1,23,21,35,130,251,35,6,34,39,38,137,188,54,16,1,6,16,22,50,54,16,38,34,1,248,26,56,30,64,62,23,24,53,145, + 47,140,135,193,52,254,152,34,68,153,68,69,151,92,29,66,35,59,70,27,27,35,22,66,1,14,136,195,43,254,171,1,125,68,254,217,134,130,1,47,131,130,111,32,72,130,199,32,50,130,199,34,9,0, + 40,134,199,34,52,39,38,135,196,44,21,20,6,7,6,7,30,4,31,1,35,46,2,130,134,32,35,130,25,8,43,17,173,111,82,33,36,38,36,79,109,101,219,123,54,66,23,24,34,56,16,19,6,13,35,28,48,107,54, + 45,16,6,16,13,59,12,24,37,1,119,31,30,124,32,32,131,220,55,52,60,88,45,60,26,32,28,29,34,13,24,66,54,90,105,91,31,11,31,26,1,254,216,68,159,6,36,37,2,203,0,58,74,225,11,130,102,73, + 237,8,43,51,50,23,30,2,23,21,38,47,1,38,34,130,136,36,6,21,20,23,22,130,1,33,30,1,76,96,5,8,108,34,39,46,1,39,79,110,102,118,33,11,29,27,75,14,7,62,40,58,24,47,103,63,79,37,54,16,45, + 26,13,39,21,32,43,87,28,58,21,11,6,8,14,32,69,13,13,39,189,146,48,90,27,57,75,27,130,67,72,23,28,52,27,27,17,3,1,9,16,25,24,43,77,118,57,33,9,4,11,9,4,96,23,7,12,13,7,17,45,21,20,32, + 12,19,13,28,13,3,3,8,38,165,153,40,13,3,5,24,10,0,130,175,43,24,0,0,2,81,2,189,0,7,0,0,33,67,189,6,44,1,2,234,2,57,234,2,110,79,79,253,146,0,131,35,36,60,255,243,2,43,130,35,37,34, + 0,0,5,35,34,132,204,130,164,37,38,53,17,51,17,20,71,116,6,33,55,54,132,13,131,208,60,1,82,29,49,59,10,9,42,12,30,18,4,16,103,21,11,38,75,54,24,56,10,2,101,11,17,34,61,13,130,119,60, + 19,11,25,41,12,48,105,1,176,253,250,43,34,11,32,11,27,52,20,205,1,67,254,80,105,35,58,30,48,132,111,32,29,130,147,32,76,130,111,32,15,130,124,36,2,3,35,38,2,130,114,8,44,51,30,3,23, + 19,2,76,111,107,123,27,80,30,48,33,98,12,31,49,67,22,181,2,189,254,162,254,161,85,1,2,96,155,107,40,106,168,226,75,2,103,0,1,0,2,130,63,32,102,130,63,32,30,130,63,40,3,35,47,1,38,47, + 1,14,2,130,154,34,35,2,3,132,70,8,72,51,18,23,22,23,18,55,2,102,109,99,40,25,10,8,15,4,10,16,12,41,15,98,44,66,86,10,28,21,14,5,86,112,39,14,26,8,58,19,2,189,253,67,244,157,59,51,85, + 22,59,99,75,254,87,1,9,1,180,68,206,153,96,37,2,48,254,255,88,173,43,1,165,140,130,107,32,9,130,107,32,95,130,107,32,31,132,107,36,19,54,55,46,1,132,173,8,83,1,23,19,51,6,7,14,1,7, + 22,23,30,1,23,35,38,39,46,1,1,59,197,109,174,46,30,17,40,31,64,83,108,39,100,44,167,109,28,41,45,95,14,47,113,22,42,15,108,12,16,32,101,1,46,254,210,1,2,68,46,23,56,43,88,119,57,143, + 64,1,8,40,61,68,138,22,75,173,36,64,24,20,26,52,167,130,98,71,223,8,32,19,130,12,33,19,51,130,95,36,6,7,17,35,17,131,94,8,45,39,51,22,23,22,1,52,181,109,29,88,33,51,39,101,29,44,78, + 72,16,108,44,47,64,1,136,1,53,46,143,52,82,63,254,197,1,59,47,71,126,117,25,76,79,107,0,130,62,33,0,55,130,187,32,49,130,187,8,47,16,0,0,51,53,54,18,54,55,33,53,33,21,14,3,7,33,21, + 55,109,180,65,25,254,144,1,229,26,67,106,144,47,1,144,73,156,1,6,95,36,79,71,36,95,150,202,67,80,131,59,44,148,255,166,1,205,3,24,0,7,0,0,23,17,69,243,5,43,148,1,57,220,220,90,3,114, + 74,253,35,75,132,95,8,52,62,255,210,2,40,2,233,0,13,0,0,19,22,23,18,31,1,35,39,46,1,47,1,38,39,158,31,43,212,41,67,96,60,34,62,25,50,121,42,2,233,62,85,254,84,82,134,120,68,124,51, + 102,244,80,31,6,36,154,255,167,1,210,134,95,70,87,5,44,17,154,220,220,1,56,89,75,2,220,74,252,143,132,95,36,61,1,177,2,43,130,191,32,14,130,144,39,7,35,19,51,30,1,23,22,65,106,6,59, + 52,136,111,203,88,25,74,28,58,18,111,8,12,24,75,2,112,191,1,12,32,99,36,77,24,13,16,32,130,252,45,1,255,247,255,167,2,114,255,243,0,3,0,0,7,130,245,49,9,2,123,89,76,76,0,1,0,167,2, + 51,1,169,3,2,0,10,130,83,33,35,38,65,202,6,8,33,22,1,169,112,33,39,64,10,111,9,26,20,48,2,51,46,56,92,13,13,36,29,67,0,0,2,0,68,255,243,2,19,2,27,130,227,32,57,78,1,9,38,61,1,35,34, + 7,6,5,72,159,8,49,55,54,59,1,53,52,39,38,43,1,34,7,53,51,50,62,1,50,130,168,32,22,82,86,5,8,94,35,34,39,54,52,38,160,70,21,27,78,44,38,116,96,42,24,1,31,48,144,84,50,53,35,38,54,59, + 77,107,36,37,61,88,34,40,40,19,32,40,50,24,59,27,76,14,8,1,31,10,42,2,2,158,73,20,7,57,50,81,18,39,22,133,83,44,45,81,67,39,40,13,17,13,68,25,27,2,73,1,1,3,9,15,40,66,36,76,250,24, + 21,1,30,14,15,131,163,32,96,130,163,52,44,2,246,0,25,0,47,0,0,19,20,23,22,50,55,54,55,62,2,55,54,130,147,36,46,1,34,6,7,132,1,79,126,5,68,133,5,32,7,131,186,8,86,6,7,35,17,51,193,70, + 28,69,19,32,18,28,16,4,2,1,43,26,51,46,37,14,30,10,20,4,6,5,48,107,86,52,57,15,3,47,23,43,40,61,106,48,5,4,83,92,1,7,134,50,20,5,8,21,31,54,35,17,17,16,114,47,29,13,10,10,21,22,41, + 25,46,168,80,52,54,121,24,24,110,78,38,27,24,80,44,23,130,136,35,0,1,0,82,130,147,36,3,2,27,0,30,73,199,14,36,22,23,21,38,39,69,25,9,8,57,51,50,55,2,3,72,91,128,73,69,123,62,87,54, + 24,50,33,41,24,45,76,27,47,35,41,76,40,67,91,62,27,40,76,72,128,167,74,35,7,16,17,91,32,9,17,7,12,40,53,91,123,53,28,58,0,2,0,61,130,95,43,9,2,245,0,28,0,51,0,0,55,30,1,130,72,130, + 243,36,1,55,54,52,39,130,95,35,39,38,35,34,130,245,36,14,2,21,20,5,130,234,132,17,32,52,78,236,7,8,37,17,51,17,35,38,200,24,48,22,42,20,37,11,16,6,2,1,1,2,2,3,12,35,80,45,26,29,9,17, + 6,3,1,14,50,101,62,63,17,130,252,8,60,30,29,57,102,75,48,16,11,92,83,2,101,29,13,15,26,29,35,49,17,17,32,17,17,17,30,26,80,20,22,22,37,52,34,16,114,82,80,37,16,54,122,25,88,100,37, + 73,45,15,20,1,42,253,11,19,0,0,0,2,0,62,130,159,32,44,130,255,38,10,0,36,0,0,19,33,132,149,131,147,32,1,87,7,12,35,29,1,33,21,80,85,6,8,67,55,162,1,47,14,21,60,20,26,69,46,40,1,110, + 96,100,129,74,74,116,60,83,170,50,15,254,114,46,46,90,72,76,23,24,1,54,37,42,54,18,5,46,38,254,157,40,72,74,126,164,79,37,148,46,46,56,3,83,48,50,33,10,11,0,0,1,0,66,130,120,44,40, + 2,224,0,22,0,0,51,17,35,53,51,53,131,242,34,59,1,21,131,119,8,35,29,1,51,21,35,17,231,165,165,22,21,43,99,136,140,50,19,19,169,169,1,143,78,71,43,84,21,40,73,19,17,62,88,78,254,113, + 130,62,37,0,76,255,3,2,23,130,183,37,18,0,63,0,0,19,134,155,32,53,131,190,33,46,1,80,245,5,49,23,52,38,53,51,6,29,1,6,20,14,3,35,7,53,51,54,55,131,1,34,53,6,7,132,217,34,39,46,3,77, + 142,5,8,106,168,83,26,33,98,27,8,9,15,13,28,47,27,60,38,38,125,105,55,1,83,1,1,1,17,62,60,45,222,102,53,36,66,34,33,1,32,29,48,40,70,42,20,17,29,32,10,6,48,24,43,42,1,13,147,41,12, + 113,37,33,77,27,50,16,31,13,50,50,173,67,13,29,10,34,45,95,93,193,113,99,66,37,2,78,1,1,2,46,46,60,77,38,9,15,24,13,15,28,72,48,48,24,110,74,37,26,24,131,251,32,97,130,188,35,13,2, + 245,0,130,12,42,19,54,59,1,50,23,22,21,17,35,17,81,160,6,33,7,6,131,12,8,38,51,189,50,106,10,68,38,64,92,57,20,26,73,38,19,7,4,92,92,1,207,80,32,57,127,254,185,1,71,105,23,9,52,26, + 47,20,21,254,214,130,68,35,0,2,0,166,130,84,51,129,2,219,0,21,0,33,0,0,33,35,53,54,61,1,35,53,51,21,20,130,248,34,22,29,1,130,2,41,20,6,17,20,43,1,34,61,1,52,130,109,38,21,1,128,92, + 1,127,218,130,222,63,1,15,71,16,16,71,15,114,28,120,187,77,64,16,35,37,126,11,23,40,16,18,66,16,37,2,103,14,14,81,14,14,130,166,37,0,118,255,4,1,187,130,91,43,15,0,27,0,0,23,53,51, + 50,54,53,17,130,92,41,17,20,6,7,6,35,19,50,29,1,134,88,63,51,118,143,46,44,144,236,22,23,45,80,149,14,14,73,14,14,252,80,80,58,1,227,77,253,208,46,96,25,51,3,215,131,79,32,81,130,81, + 130,170,33,0,113,130,88,34,84,2,218,130,175,8,61,0,1,7,21,35,17,51,17,62,1,55,54,55,51,6,7,30,3,23,35,38,1,20,68,95,95,29,89,33,40,51,111,158,62,31,94,69,44,17,113,186,1,15,60,211, + 2,218,254,90,27,80,30,37,44,141,57,40,121,89,56,22,245,131,75,32,141,130,4,36,119,2,190,0,8,130,7,55,7,17,35,17,52,39,35,53,1,119,2,92,1,139,2,190,192,254,2,2,9,40,63,78,130,26,41, + 0,41,0,0,2,69,2,27,0,38,130,12,33,54,51,65,114,13,32,21,130,55,76,176,7,130,10,8,72,51,20,6,21,54,55,50,1,71,46,85,66,29,28,84,15,12,39,38,25,16,84,3,9,17,30,55,14,15,84,77,1,33,89, + 60,1,217,66,47,50,137,254,207,1,45,114,26,26,29,26,111,254,211,1,96,69,16,30,28,26,112,254,211,2,14,8,29,9,57,2,0,1,0,65,231,5,40,27,0,18,0,0,1,52,35,34,65,217,6,33,22,23,130,127,130, + 114,61,1,177,107,100,28,9,92,83,7,2,51,114,171,92,1,71,137,95,31,40,254,214,2,14,49,30,92,212,254,185,130,174,37,0,69,255,243,2,36,130,179,34,15,0,28,66,223,13,131,75,35,19,34,39,38, + 88,17,6,8,51,16,6,166,81,27,34,67,39,37,82,26,35,69,36,37,143,179,46,15,15,46,178,117,61,62,122,1,7,146,44,14,54,53,97,149,41,13,52,51,254,136,157,51,134,51,159,71,70,254,243,142,0, + 131,95,36,95,255,3,2,42,130,95,32,10,131,95,34,37,50,16,132,162,36,20,23,22,23,34,76,96,6,65,40,5,46,20,7,6,1,82,132,132,101,28,9,79,25,34,105,46,131,177,8,32,48,103,99,60,57,127,39, + 59,1,151,117,37,49,147,43,14,72,80,254,192,3,11,41,26,80,74,73,129,196,62,18,0,2,130,187,40,4,2,15,2,26,0,14,0,32,85,95,15,39,20,1,54,55,51,17,35,17,68,93,10,8,33,190,34,65,66,34,35, + 78,25,32,65,34,35,1,24,7,2,83,92,47,105,136,53,25,127,40,50,101,111,54,54,51,99,151,39,130,191,47,199,1,40,38,28,252,248,1,62,81,130,61,74,206,63,19,130,195,34,1,0,129,130,200,32,25, + 130,195,44,25,0,0,1,38,43,1,34,6,7,6,29,1,130,195,8,53,21,35,17,51,22,20,6,21,54,59,1,22,23,2,25,56,84,39,10,63,21,45,1,1,92,90,1,2,56,127,5,82,49,1,155,48,24,21,45,43,42,30,48,146, + 60,2,14,6,18,24,23,84,2,38,130,82,35,0,1,0,106,70,15,6,39,39,0,0,1,34,21,20,23,75,15,9,86,136,10,33,46,1,84,150,5,8,72,55,54,50,23,21,38,1,67,121,25,28,109,12,139,59,59,183,108,108, + 80,57,36,35,29,27,67,10,9,29,66,40,36,55,54,185,83,80,1,211,78,37,17,17,19,2,26,116,78,45,45,32,90,51,24,21,40,36,19,19,13,2,2,6,12,36,34,60,76,41,40,31,84,43,133,123,41,128,255,254, + 1,230,2,174,0,17,0,74,223,5,36,53,17,51,21,51,130,204,130,210,59,59,1,1,230,169,103,43,43,92,221,221,24,22,60,160,2,39,41,94,2,2,160,79,254,237,59,18,18,130,60,51,1,0,84,255,242,2, + 20,2,13,0,24,0,0,37,6,43,1,38,35,34,130,61,8,61,17,20,51,54,55,54,53,54,53,51,20,22,29,1,35,1,190,37,123,9,4,5,184,91,124,73,30,34,3,92,1,86,57,71,1,213,1,69,254,187,139,8,36,40,57, + 240,83,63,194,72,196,0,0,1,0,50,0,0,2,54,2,14,131,135,40,1,3,35,46,3,39,51,23,22,130,1,8,40,62,1,63,1,2,54,198,119,25,72,55,34,13,95,50,30,22,46,15,26,57,30,50,2,14,253,242,64,194, + 143,91,34,135,81,60,125,40,68,157,81,135,131,67,130,148,33,2,104,130,67,32,27,130,12,43,3,35,2,38,39,51,30,2,23,19,51,23,130,5,131,71,32,51,130,87,8,58,1,39,1,52,89,88,89,33,9,91,22, + 49,16,6,72,102,25,16,22,14,5,11,31,12,31,91,131,88,11,32,12,1,33,254,223,1,100,136,34,93,220,70,27,1,4,80,48,71,44,17,50,151,56,153,253,242,35,107,39,130,93,130,167,32,38,130,167,32, + 67,130,99,39,35,0,0,51,54,55,46,2,130,99,46,3,23,62,1,55,51,14,3,7,30,1,23,35,39,38,130,1,33,7,6,130,1,57,38,140,80,61,92,34,14,103,18,55,40,26,9,109,29,10,103,24,74,55,34,14,25,169, + 27,107,130,198,33,45,17,132,4,58,171,103,79,113,44,16,23,70,52,33,12,139,39,12,31,92,69,43,17,30,211,33,65,38,29,58,21,132,4,133,115,8,40,70,255,2,2,25,2,15,0,50,0,0,23,51,54,59,1, + 50,55,54,53,54,52,39,35,34,38,61,1,52,55,53,50,54,51,17,20,23,22,59,1,17,130,241,34,54,51,21,69,131,5,130,5,8,80,20,6,35,33,38,54,119,59,45,37,102,39,17,25,1,1,189,84,100,1,17,57,18, + 24,25,68,163,1,1,35,11,47,1,1,1,88,66,254,248,1,1,174,1,29,45,64,10,18,8,100,63,252,32,28,50,1,254,202,77,31,27,1,82,54,52,1,83,41,37,76,40,66,115,51,32,32,81,127,21,39,0,130,255,32, + 101,130,255,32,8,130,139,32,17,130,255,33,53,54,88,38,5,32,21,131,238,8,34,6,7,33,21,101,39,60,114,109,254,203,1,150,39,59,115,60,27,21,1,65,80,46,70,134,129,68,78,46,70,136,69,33, + 24,71,131,63,40,92,255,151,2,3,3,38,0,44,66,111,6,130,193,83,72,8,130,11,32,55,130,222,71,147,6,32,20,84,214,5,33,29,1,132,219,8,76,2,3,33,122,44,43,26,27,56,72,59,71,25,26,43,43,123, + 33,36,68,22,21,23,26,48,46,28,23,21,24,46,56,105,34,35,109,113,70,28,23,88,21,28,72,111,109,35,35,84,14,19,71,110,74,33,40,11,10,41,33,76,115,63,19,15,0,1,1,6,255,181,1,92,3,9,0,3, + 130,123,43,17,51,17,1,6,86,75,3,84,252,172,0,131,151,32,102,130,151,32,16,130,151,40,50,0,0,23,53,51,50,55,54,132,140,34,55,38,39,130,1,137,163,33,23,22,132,142,35,23,22,51,22,72,59, + 8,130,167,8,99,35,102,34,72,20,22,22,31,43,28,16,37,9,6,22,20,72,34,31,124,43,42,10,6,7,33,65,16,21,28,32,96,35,23,42,42,125,105,83,16,20,70,108,74,34,42,9,6,15,31,40,26,59,97,63,20, + 14,84,35,34,110,113,36,24,11,10,37,1,88,39,33,61,100,109,36,34,0,1,0,40,0,241,2,61,1,215,0,33,0,0,19,39,54,55,54,51,50,23,30,1,130,115,130,149,33,55,23,87,136,6,131,151,8,89,35,34, + 7,14,1,118,78,12,21,41,76,37,19,28,41,11,57,36,56,13,5,3,77,33,36,83,39,22,33,28,51,16,19,19,38,17,7,12,1,20,18,71,36,70,11,15,41,14,76,73,22,27,17,51,59,68,12,19,37,65,10,13,33,27, + 44,0,2,0,232,255,227,1,138,2,193,0,6,0,20,0,0,55,54,55,51,19,21,35,2,52,131,115,33,22,21,133,106,8,34,246,9,29,60,34,132,14,23,21,37,35,46,49,15,17,37,21,181,79,187,254,246,210,2,102, + 76,21,23,46,27,66,18,5,21,0,130,71,48,105,255,109,2,18,2,161,0,8,0,43,0,0,37,17,6,7,79,220,5,34,53,38,39,89,241,5,36,54,55,53,51,21,130,197,32,21,130,16,32,39,71,127,5,32,21,130,36, + 37,35,21,1,93,66,40,130,0,8,70,66,117,60,67,13,22,24,70,115,51,62,49,19,46,23,34,27,8,16,8,48,50,11,9,55,55,59,1,151,6,56,54,87,88,54,56,212,135,9,75,75,115,58,37,60,28,82,12,134,134, + 8,17,8,81,26,5,8,3,254,102,1,3,1,10,28,81,4,4,23,135,0,82,115,8,43,44,2,203,0,27,0,0,19,52,51,50,23,131,115,73,231,8,8,47,21,33,21,33,53,51,53,35,53,51,187,227,62,70,9,8,50,60,103, + 20,8,185,185,1,12,254,26,117,99,99,1,221,238,28,86,5,5,31,96,33,61,86,68,218,80,80,218,68,130,219,42,102,0,92,2,38,2,0,0,13,0,47,70,91,11,8,32,34,7,6,20,23,7,38,39,54,55,46,1,53,52, + 55,38,39,55,23,54,50,23,55,23,22,23,7,22,20,7,22,23,6,130,27,8,86,6,34,250,32,45,46,30,31,31,30,92,30,32,11,82,10,36,80,3,22,7,30,72,12,48,82,50,90,50,83,22,14,9,83,30,31,23,61,38, + 9,80,3,50,90,229,28,28,31,42,43,29,28,28,28,86,92,76,10,32,75,3,36,43,11,44,43,69,10,44,79,29,28,78,22,13,8,79,49,88,39,21,57,33,11,75,3,29,133,231,86,239,7,43,35,0,0,1,6,7,21,51,21, + 35,21,35,131,216,33,53,39,130,221,79,22,8,8,80,23,19,51,7,14,1,7,51,21,1,145,5,38,201,201,101,200,200,45,155,122,19,30,68,33,11,108,44,47,64,27,181,109,50,51,53,11,126,1,130,9,62,17, + 51,247,247,51,17,71,52,32,48,111,55,17,76,79,107,47,1,53,80,80,86,17,52,0,0,2,1,10,255,188,1,96,3,2,0,3,0,7,67,61,5,8,45,3,17,51,17,1,10,86,86,86,68,1,101,254,155,1,226,1,100,254,156, + 0,2,0,99,255,164,2,6,2,203,0,17,0,85,0,0,19,20,23,22,23,54,53,52,39,38,130,1,33,6,7,130,1,32,5,92,10,8,37,43,1,39,46,3,39,70,224,11,35,2,53,52,55,66,44,6,35,51,31,1,22,130,58,86,216, + 5,66,74,6,33,30,1,130,17,8,129,22,181,42,40,112,61,8,12,17,39,117,28,18,4,3,9,1,81,92,50,5,4,51,50,86,20,20,27,18,20,43,11,88,60,73,26,7,61,38,46,87,46,16,92,59,50,35,61,18,18,39,20, + 9,13,20,53,82,60,42,13,33,7,7,18,26,59,5,5,20,92,36,33,1,98,35,37,36,53,38,48,20,13,20,15,35,58,18,25,4,5,19,77,84,48,44,32,14,25,58,39,40,2,3,4,3,12,3,77,36,43,13,15,44,36,25,25,47, + 50,41,25,87,46,39,67,61,38,27,7,3,2,130,0,8,40,3,17,77,37,7,20,15,16,11,22,18,26,33,3,2,10,46,41,37,0,0,0,2,0,160,2,123,1,201,2,217,0,11,0,23,0,0,1,52,59,1,74,174,6,33,53,39,138,11, + 36,1,99,16,70,16,130,2,43,195,14,72,15,15,72,14,2,204,13,13,68,135,2,33,0,3,130,71,51,58,2,104,2,126,0,27,0,51,0,75,0,0,37,50,55,21,6,34,39,91,150,5,46,51,50,23,21,46,2,43,1,34,7,6, + 21,20,22,7,82,126,9,75,202,9,34,20,23,22,79,122,7,68,56,9,89,249,5,8,126,1,85,45,46,52,106,36,73,28,12,13,42,139,57,56,35,43,14,6,13,64,31,33,70,150,55,90,24,26,74,68,64,33,18,76,70, + 111,56,32,137,27,5,32,9,1,105,53,92,160,96,52,35,17,91,165,99,72,45,34,8,50,35,35,42,26,219,25,49,22,11,24,68,31,82,32,103,20,51,17,6,2,34,33,64,60,68,26,63,19,5,42,37,72,42,37,116, + 68,70,14,56,123,23,24,54,64,15,124,35,130,73,87,61,76,24,129,48,31,41,12,70,87,83,52,60,28,20,0,130,219,38,135,0,220,1,224,2,203,130,9,41,17,0,46,0,0,55,53,33,21,3,130,203,130,179, + 33,50,55,130,173,34,61,1,21,73,162,8,80,51,5,8,122,34,7,53,54,63,1,50,23,22,29,1,35,38,146,1,78,138,104,22,8,22,22,62,22,43,18,9,53,80,96,33,9,103,33,56,79,49,27,93,71,40,60,35,132, + 33,11,64,4,220,59,59,1,43,37,13,49,18,18,8,18,46,22,19,22,130,61,70,22,28,89,28,8,1,55,20,11,31,59,16,9,2,92,31,44,211,18,0,0,0,2,0,40,0,67,1,245,1,242,0,12,0,29,0,0,1,23,21,39,53, + 62,3,55,21,14,1,7,22,23,21,38,39,46,1,130,15,32,1,130,148,8,49,21,6,1,94,151,235,29,86,64,40,16,29,93,255,78,72,15,20,53,118,28,28,87,32,61,26,78,1,26,126,89,196,38,24,72,54,34,13, + 90,24,79,23,67,59,89,12,17,45,98,24,130,17,53,27,52,22,90,67,0,1,0,44,0,174,2,60,1,150,0,5,0,0,37,53,33,130,237,41,1,232,254,68,2,16,174,151,81,232,130,131,42,1,0,178,0,225,1,182,1, + 46,0,3,65,11,5,39,178,1,4,225,77,77,0,4,66,3,8,39,10,0,37,0,61,0,85,0,86,143,5,32,53,85,200,8,41,21,20,7,6,7,30,1,23,30,5,81,241,5,35,43,1,21,39,66,12,46,8,32,246,51,45,14,23,19,18, + 42,54,65,119,145,48,16,20,5,11,8,3,8,11,8,18,32,11,72,65,10,18,26,16,23,133,66,20,39,8,32,1,113,9,15,30,33,9,12,254,225,1,71,93,50,24,7,3,1,10,7,4,11,12,11,27,50,17,102,12,19,7,140, + 3,66,31,40,8,40,1,0,159,2,135,1,202,2,205,0,3,0,0,1,21,33,53,1,202,254,213,2,205,70,70,0,0,0,2,0,150,1,160,1,211,2,203,0,13,0,35,130,29,80,201,5,46,35,34,7,6,20,22,50,55,22,23,30,1, + 20,14,1,103,70,13,8,61,1,132,15,6,13,38,14,22,45,24,28,54,92,11,30,31,13,23,23,34,18,32,54,84,46,26,45,46,66,8,7,35,2,4,17,50,16,30,17,7,24,26,76,52,228,13,29,13,55,60,54,30,12,21, + 63,39,38,72,43,44,1,5,132,115,32,44,130,120,34,60,2,38,130,143,38,15,0,0,51,53,33,21,101,69,11,47,44,2,16,254,206,222,222,84,222,222,80,80,160,155,80,155,130,2,130,152,47,0,161,2,14, + 1,190,3,159,0,27,0,0,19,54,51,50,130,153,38,21,20,7,14,2,7,51,130,208,33,54,55,130,1,8,52,52,39,38,34,7,164,66,46,100,43,18,6,15,40,67,59,20,204,254,227,21,36,114,15,21,7,23,106,68, + 3,132,27,48,20,32,10,35,19,51,60,54,18,54,53,20,33,100,27,29,38,12,38,34,130,142,50,0,1,0,163,2,9,1,206,3,161,0,55,0,0,1,20,7,22,23,88,146,5,36,34,47,1,38,39,131,1,32,53,94,4,10,92, + 154,10,38,35,34,14,3,7,53,54,130,139,8,92,22,1,196,86,47,24,25,12,36,133,17,7,7,14,8,7,17,10,20,11,39,24,23,26,95,14,2,28,23,59,32,37,71,18,6,52,17,17,23,39,15,14,14,8,77,38,112,37, + 11,3,59,65,22,8,26,25,67,22,71,1,2,1,1,4,2,4,5,56,15,3,7,56,7,13,29,18,18,51,33,10,13,42,12,4,8,2,5,6,2,57,17,60,19,130,159,40,238,2,81,1,221,3,2,0,9,130,159,34,6,7,35,132,238,53,55, + 1,221,143,20,76,17,25,26,20,38,14,3,2,156,21,21,33,33,24,48,18,133,207,44,83,255,55,2,65,2,14,0,30,0,0,37,6,78,3,5,39,17,20,23,22,51,50,53,17,74,209,6,33,50,55,68,18,5,8,47,1,175,42, + 181,42,83,91,18,33,66,127,93,17,6,5,8,7,23,40,23,39,14,24,60,73,72,254,252,2,215,254,186,54,30,55,158,1,51,254,106,42,8,3,10,70,20,14,24,133,95,36,53,255,164,2,3,85,35,5,43,5,17,38, + 39,38,53,52,54,59,1,17,35,130,1,56,1,23,136,56,34,132,106,224,71,95,92,1,141,10,78,43,67,90,108,252,231,2,224,253,32,130,56,48,1,0,227,1,14,1,133,1,174,0,15,0,0,1,22,21,20,107,176, + 9,8,35,51,50,1,110,23,35,29,17,34,23,24,50,14,17,32,1,152,23,43,26,34,12,23,22,35,54,20,6,0,1,0,198,255,71,1,148,130,65,41,17,0,0,5,50,53,52,38,39,51,130,61,8,33,7,6,43,1,34,39,53, + 22,1,17,62,33,11,59,54,46,33,25,37,28,37,36,128,43,21,49,15,54,49,53,18,11,11,61,131,102,8,57,0,172,2,14,1,202,3,151,0,13,0,0,19,54,55,51,17,51,21,33,53,51,17,14,1,7,172,42,73,68,103, + 254,235,103,21,70,21,3,132,6,13,254,172,53,53,1,30,4,11,4,0,3,0,122,0,220,1,239,69,79,6,32,37,68,67,5,34,39,22,51,101,144,6,106,122,9,32,39,103,204,10,8,71,21,20,138,1,82,213,20,25, + 53,27,29,44,21,70,20,62,244,49,87,46,25,43,16,45,8,3,76,43,67,87,49,51,220,59,59,172,9,37,33,68,79,38,21,9,27,203,39,53,11,19,17,46,57,20,34,98,54,31,53,53,88,89,0,2,0,116,0,67,2,65, + 1,242,91,143,5,34,1,23,21,130,161,41,6,7,53,62,1,55,38,39,7,38,130,230,33,23,22,130,19,8,61,3,7,53,54,1,86,235,29,86,32,59,29,28,94,29,54,97,76,72,78,59,60,78,37,15,40,64,87,28,72, + 1,242,197,38,24,72,27,50,23,89,23,79,24,42,84,126,59,67,90,50,50,65,32,38,13,33,54,72,24,89,59,0,130,0,59,4,0,13,255,129,2,45,3,11,0,5,0,20,0,24,0,36,0,0,37,51,53,6,7,6,23,53,35,131, + 108,44,54,55,51,21,51,21,35,21,19,5,39,37,1,65,45,8,8,65,6,7,1,27,137,9,12,68,89,194,22,67,25,34,34,80,59,59,69,253,237,13,2,19,254,11,115,68,103,254,235,103,63,49,12,195,13,16,94, + 211,87,57,31,91,33,47,46,253,52,87,1,231,123,51,123,1,95,17,254,172,52,52,1,31,12,7,130,122,33,0,3,136,123,36,30,0,34,0,46,130,121,80,150,8,37,7,6,7,51,21,33,133,128,92,31,6,34,34, + 7,37,143,131,59,8,63,48,82,44,43,15,29,39,83,36,205,254,226,22,72,19,54,9,6,6,19,25,23,96,60,1,37,142,143,58,247,26,30,34,47,29,22,40,36,75,34,53,52,20,66,17,50,12,9,6,32,18,33,17, + 17,34,172,144,152,65,19,7,32,19,65,19,6,32,79,65,19,25,47,45,1,50,52,35,34,15,1,14,1,7,53,55,62,1,55,137,192,32,22,75,212,5,41,47,1,34,39,46,2,39,53,30,1,101,182,8,34,43,1,53,65,61, + 22,8,45,135,95,90,37,17,25,7,15,8,18,21,19,11,16,35,71,42,42,49,16,21,96,47,48,85,9,8,29,8,7,13,23,14,8,18,24,7,38,27,93,14,2,6,21,82,33,65,98,20,8,56,212,113,5,7,2,5,2,56,4,5,2,2, + 3,27,28,46,51,23,7,5,20,79,58,31,32,1,2,2,4,4,4,2,58,6,8,2,10,56,8,25,12,40,51,0,2,0,96,255,244,1,239,2,219,0,50,0,67,130,227,33,54,55,66,100,5,72,27,7,35,62,1,63,1,131,211,36,55,54, + 61,1,52,130,3,32,51,131,210,36,7,14,2,15,1,81,137,5,33,51,19,69,25,5,33,35,34,66,247,6,8,119,50,1,82,68,89,31,31,11,33,25,35,38,87,52,56,17,22,53,6,27,8,12,5,15,4,8,1,96,12,18,43,12, + 11,27,5,13,31,19,28,71,40,30,10,4,16,25,23,39,31,6,5,57,7,24,65,7,57,89,17,11,4,14,3,3,44,46,75,40,27,35,49,5,25,7,13,6,17,8,16,32,2,3,5,5,65,72,45,25,40,39,11,10,26,5,13,36,25,10, + 31,22,38,2,149,9,27,13,51,14,23,29,13,13,16,56,14,1,0,0,0,3,90,175,5,39,3,101,0,10,0,23,0,31,98,145,23,39,3,46,1,39,51,30,1,23,98,153,23,39,145,22,70,22,92,19,61,19,98,161,22,36,2, + 49,23,79,23,130,2,137,111,32,104,132,111,32,27,151,111,35,17,7,35,55,151,107,34,114,77,98,151,102,34,177,123,123,138,211,32,102,132,99,32,35,151,99,42,3,38,39,14,1,7,35,54,55,51,22, + 152,215,43,47,48,35,15,52,16,69,85,20,94,44,62,151,116,41,50,51,33,15,53,16,102,23,51,74,138,123,32,81,132,123,32,62,153,123,40,34,7,6,29,1,35,52,55,54,94,110,5,32,22,79,205,5,43,51, + 6,7,6,35,34,46,1,47,1,46,3,151,255,8,33,172,14,18,6,22,63,27,26,42,6,9,30,34,7,10,26,11,19,8,13,62,3,53,17,15,32,18,9,6,14,7,7,18,5,151,169,63,92,7,4,11,30,4,49,27,28,1,6,17,4,5,13, + 9,15,19,3,73,23,8,8,3,3,7,4,4,9,4,0,4,66,11,12,34,35,0,47,151,189,32,19,86,222,6,36,59,1,50,21,7,138,11,151,177,32,19,76,76,5,38,196,15,72,14,14,72,15,151,157,35,93,14,14,67,135,2, + 66,151,8,38,126,0,8,0,22,0,44,132,137,53,1,39,14,3,18,6,20,30,1,51,50,55,54,52,39,38,35,34,3,7,35,19,110,2,8,8,89,21,20,7,22,18,22,23,35,39,202,213,48,46,13,13,39,29,18,35,12,34,26, + 16,33,21,22,5,20,52,29,101,54,105,214,61,14,46,77,56,42,39,61,46,120,34,14,104,56,1,3,158,156,43,43,132,97,62,2,11,26,44,31,11,21,20,45,13,44,253,115,183,2,145,35,72,38,22,70,38,39, + 53,66,41,138,254,141,105,43,183,0,130,0,32,2,132,4,38,78,2,189,0,7,0,23,131,141,46,17,35,14,1,7,6,15,1,35,19,33,21,35,21,51,132,3,63,33,53,164,154,53,12,38,13,30,30,50,92,205,1,120, + 169,153,153,178,254,240,1,3,1,107,45,133,50,106,108,180,2,100,83,5,32,180,131,74,45,1,0,70,255,71,2,25,2,203,0,51,0,0,1,130,202,78,63,5,131,217,43,55,21,6,7,34,6,7,22,23,22,21,20,71, + 149,5,37,51,50,53,52,46,3,71,33,7,8,88,55,54,50,23,2,25,79,87,98,49,49,75,45,76,59,68,20,19,47,43,6,22,8,26,3,15,120,22,25,40,36,39,62,14,3,7,7,4,129,73,78,14,45,116,55,159,78,2,67, + 58,71,74,142,175,70,42,34,10,15,97,23,9,3,1,34,7,32,19,82,11,61,15,43,14,26,8,9,9,6,8,87,96,171,89,50,152,50,25,39,132,226,43,0,98,0,0,2,39,3,104,0,11,0,19,101,29,13,68,3,7,50,98,1, + 188,254,170,1,70,254,186,1,95,240,21,71,21,92,18,62,18,134,217,36,2,237,23,77,23,130,2,130,72,32,2,138,71,32,15,142,71,34,7,35,55,138,67,35,113,114,77,98,134,63,35,3,104,123,123,138, + 59,32,102,130,131,32,24,142,59,67,179,9,33,31,1,138,68,32,151,67,167,7,35,95,20,33,52,134,77,33,2,233,67,152,6,36,23,39,63,0,3,134,143,32,101,130,83,33,25,0,130,234,101,247,11,32,3, + 66,195,6,33,55,54,66,209,11,133,13,138,100,44,85,15,71,15,3,4,28,51,15,196,15,72,14,132,8,134,105,41,3,20,14,14,67,7,4,3,14,67,134,7,36,0,0,2,0,100,130,4,34,3,3,104,130,111,32,18,130, + 195,95,33,5,43,21,35,17,51,21,3,46,1,39,51,22,23,101,128,6,38,216,21,70,22,92,47,52,101,135,7,38,2,237,23,77,23,60,63,140,63,32,15,142,63,34,7,35,55,134,60,35,77,114,77,98,135,57,65, + 60,5,135,119,32,102,130,119,32,21,144,55,33,54,55,130,120,33,35,38,134,61,41,208,82,70,85,20,95,44,62,71,48,136,67,41,61,84,102,23,51,74,51,0,0,3,134,191,32,101,130,71,34,23,0,35,142, + 73,67,255,22,134,87,32,58,67,238,12,136,91,32,20,67,223,11,42,2,0,4,0,0,2,39,2,189,0,19,131,93,38,55,51,50,55,62,1,55,81,133,6,47,43,1,21,51,21,35,3,17,35,53,51,17,51,50,22,21,106, + 19,5,8,54,170,48,66,45,43,36,10,28,9,21,50,54,94,48,132,132,103,63,63,151,171,162,81,45,59,64,99,78,15,17,43,21,57,120,85,36,87,32,33,221,70,254,179,1,77,70,1,42,170,181,179,85,45, + 21,20,130,102,33,0,70,130,4,38,35,3,102,0,16,0,60,130,201,32,17,96,135,5,41,17,51,17,35,38,39,38,39,17,19,69,134,5,33,30,1,84,192,8,48,61,1,51,6,7,6,34,39,46,4,47,1,46,1,39,46,1,80, + 206,5,8,121,70,128,16,44,34,93,65,97,128,74,59,93,26,39,63,27,25,43,28,31,20,3,10,24,4,11,7,15,9,11,62,3,53,17,28,8,18,11,9,12,15,3,18,4,5,3,7,6,3,7,26,9,2,2,189,37,100,78,215,147, + 2,65,253,67,167,137,215,59,253,190,3,0,44,31,27,13,11,1,3,13,1,4,13,11,19,3,72,23,7,1,2,4,3,6,7,2,10,1,4,1,3,3,27,8,6,0,0,3,0,58,255,243,2,46,3,104,0,13,0,26,0,34,83,209,11,43,35,34, + 6,16,39,16,51,50,23,22,21,16,131,164,33,38,19,130,162,131,210,8,53,198,35,75,76,35,34,34,34,77,76,68,106,250,126,63,61,192,27,94,47,140,246,21,70,22,92,18,63,18,130,67,67,64,156,157, + 64,66,132,254,205,152,1,109,90,94,181,254,190,36,5,22,66,2,162,67,178,8,142,115,32,30,156,115,35,1,7,35,55,148,111,36,1,129,114,77,98,150,108,34,3,29,123,71,159,5,133,219,32,102,132, + 219,32,39,157,103,67,240,11,149,112,32,86,67,251,11,150,121,33,2,158,68,11,12,139,127,32,70,156,127,66,27,40,148,155,32,148,66,35,38,151,181,32,181,66,41,34,34,0,0,4,66,43,6,40,101, + 0,13,0,26,0,38,0,50,156,209,32,1,67,188,22,148,192,33,1,143,67,203,12,151,167,32,201,67,218,11,8,34,0,1,0,75,0,82,2,30,2,9,0,36,0,0,37,7,39,54,63,1,54,55,46,3,39,55,30,2,23,54,55,23, + 14,3,7,109,205,5,58,7,38,39,46,1,1,52,174,59,21,32,64,40,18,22,64,48,30,11,58,55,79,30,11,47,128,59,132,12,63,11,30,24,56,32,21,59,11,15,57,69,247,165,55,20,30,60,37,17,20,61,45,28, + 11,55,50,76,28,11,43,122,55,132,12,43,11,28,22,53,30,20,55,11,14,53,67,0,130,0,52,3,0,4,255,223,2,88,2,221,0,18,0,33,0,72,0,0,9,1,30,2,78,109,5,51,38,53,39,38,53,38,39,52,5,54,55,38, + 35,34,7,6,7,6,29,1,68,91,5,34,46,1,39,89,67,5,32,53,73,143,5,41,55,22,23,7,22,23,30,1,23,22,68,121,5,8,134,34,38,39,38,1,186,254,255,15,50,37,21,78,33,34,1,2,1,1,1,254,234,168,84,23, + 91,42,19,36,13,33,2,39,44,28,10,31,10,89,24,5,1,1,4,98,63,88,116,57,70,35,15,84,14,4,13,6,2,3,16,30,92,46,68,49,42,17,41,1,231,254,167,35,33,11,67,73,148,13,23,10,37,8,7,7,6,10,251, + 225,113,78,13,27,30,62,182,47,14,10,18,172,56,39,6,21,6,119,56,69,16,16,39,41,221,88,50,77,95,23,12,112,28,15,49,51,18,27,140,68,133,48,22,14,7,16,130,222,50,0,2,0,74,255,243,2,31, + 3,102,0,34,0,41,0,0,5,34,39,81,86,5,33,38,39,80,141,5,37,51,50,55,62,1,53,131,11,130,223,130,227,37,14,1,3,38,39,51,130,202,8,77,1,46,67,42,39,13,34,9,19,2,2,1,101,11,33,89,85,35,11, + 2,102,22,12,17,30,10,10,48,71,21,49,65,93,18,61,19,13,21,17,12,31,25,41,42,18,23,1,228,254,37,80,20,63,57,19,61,191,1,54,254,80,102,73,19,27,20,5,5,27,4,2,247,57,67,23,77,24,0,136, + 135,32,104,130,135,32,40,164,135,37,19,6,7,35,54,55,156,134,37,106,56,59,76,65,33,161,133,37,3,117,61,62,83,40,65,11,12,32,46,165,131,68,77,9,32,23,156,137,32,68,75,247,10,161,143, + 33,2,246,76,2,11,33,0,3,65,163,6,38,101,0,34,0,46,0,58,165,153,67,149,22,156,165,32,134,67,156,12,161,167,33,3,33,67,167,12,32,2,75,239,6,36,102,0,19,0,24,104,173,21,36,19,7,35,54, + 55,104,178,18,36,148,115,76,44,54,104,183,20,37,1,175,124,58,66,0,72,191,6,42,71,2,189,0,8,0,23,0,0,37,50,86,24,5,8,48,21,7,17,51,21,51,50,23,22,21,20,7,6,43,1,21,1,62,158,60,36,75, + 103,102,102,127,192,46,16,63,65,126,127,250,124,75,30,18,247,250,2,189,127,112,38,38,117,47,50,92,247,5,40,94,255,243,2,62,2,219,0,60,68,217,9,66,246,6,34,53,52,55,67,206,6,35,21,17, + 35,17,130,12,130,91,39,23,6,7,6,21,20,31,2,109,115,5,67,194,9,8,110,39,229,75,60,84,26,7,22,8,26,70,84,6,1,90,30,39,4,114,91,20,7,93,119,39,105,39,116,3,116,35,11,24,10,38,22,32,45, + 19,31,30,10,16,55,97,50,41,9,14,23,86,29,52,12,20,32,32,7,25,35,53,55,10,12,89,42,15,8,103,70,23,34,253,236,2,23,151,33,12,13,36,156,9,60,19,18,38,19,10,25,11,22,27,26,45,54,56,35, + 14,10,41,10,2,3,7,0,0,0,3,0,68,130,179,40,48,3,18,0,13,0,66,0,77,130,183,40,20,23,22,50,54,55,54,61,1,98,167,5,33,7,53,102,237,5,32,51,104,105,8,93,181,6,41,30,1,23,35,38,53,38,39, + 6,7,83,210,9,88,104,5,32,39,95,200,6,8,130,160,88,13,52,60,21,44,116,123,29,10,138,97,92,10,12,20,43,18,37,43,92,55,58,16,3,3,12,1,10,3,4,6,4,1,92,18,2,2,15,44,39,61,37,82,49,51,63, + 62,122,123,76,27,32,50,73,28,11,99,9,24,39,52,17,159,84,15,2,26,25,48,89,18,58,20,1,24,50,87,4,3,5,13,4,7,30,31,44,8,8,30,80,115,14,13,22,35,40,26,10,17,14,2,42,19,9,10,30,28,23,12, + 45,39,83,86,47,46,13,92,20,8,143,55,80,31,11,11,30,49,65,22,142,223,32,72,196,223,68,33,5,180,221,37,143,12,150,77,65,76,184,216,38,1,64,12,165,84,93,0,65,183,16,32,78,196,215,43,3, + 7,35,55,51,30,1,23,35,38,39,38,180,221,43,26,90,69,123,73,23,77,23,69,17,28,29,185,227,40,3,116,177,33,111,33,22,36,36,138,231,39,2,250,0,13,0,66,0,103,196,231,36,55,50,53,51,20,88, + 223,5,33,47,1,130,235,32,35,71,102,5,75,93,5,36,23,30,4,23,22,180,253,8,33,40,37,62,56,18,16,26,12,20,19,10,12,7,14,4,5,10,29,6,2,1,62,26,25,46,18,18,23,18,7,20,10,4,6,65,19,56,41, + 223,73,94,30,8,5,8,15,10,9,130,88,49,39,14,19,61,36,35,6,13,16,6,18,7,2,5,0,0,0,4,67,195,5,41,2,217,0,13,0,66,0,78,0,90,65,37,69,69,233,22,65,27,52,35,123,15,71,15,130,2,32,196,93, + 166,5,65,7,56,32,182,93,222,11,135,247,33,3,77,132,247,34,82,0,96,196,247,48,2,14,1,20,30,1,51,50,54,55,54,53,52,46,1,34,23,85,42,6,37,54,51,50,23,22,20,180,253,55,68,22,11,33,26,16, + 32,33,6,5,32,28,32,115,40,59,56,40,41,82,55,58,41,39,65,7,56,8,47,1,55,20,26,45,30,11,31,12,12,15,31,31,10,162,38,38,37,54,55,74,37,35,113,0,0,3,0,20,255,243,2,88,2,27,0,14,0,26,0, + 80,0,0,55,6,7,6,20,86,151,5,41,61,1,35,34,55,51,53,52,38,39,130,214,38,7,6,21,19,50,55,21,130,29,36,35,34,39,38,39,134,7,34,53,52,55,110,97,6,37,35,34,7,6,7,53,131,244,132,248,35,29, + 1,35,21,86,17,5,8,132,176,51,15,8,23,22,32,67,15,10,24,42,149,164,15,4,18,33,33,16,45,108,75,52,51,42,17,23,80,40,14,8,31,58,21,32,90,39,23,112,36,46,60,24,23,49,49,60,8,8,72,63,91, + 34,34,94,89,34,36,246,1,60,23,236,9,36,18,70,21,24,50,33,46,55,67,24,57,38,7,25,7,8,23,107,254,241,48,80,32,5,2,43,13,18,55,15,4,63,37,56,122,34,10,41,56,30,31,30,4,5,79,32,60,60,56, + 54,145,42,17,1,6,10,123,18,9,0,1,0,82,255,71,2,3,130,223,34,56,0,0,90,23,5,103,203,9,32,55,132,170,36,23,21,38,39,38,130,189,32,21,95,10,7,82,168,7,71,203,5,8,94,34,39,53,22,1,53,63, + 14,2,4,11,4,116,66,73,14,25,36,74,125,67,52,19,21,56,57,20,66,34,103,104,34,56,11,70,46,7,8,40,46,5,20,7,44,46,33,26,36,26,40,36,128,43,16,24,4,8,14,6,6,66,73,131,71,36,61,35,73,22, + 8,10,91,47,8,3,14,40,149,150,40,14,1,10,34,6,7,90,25,9,3,1,48,44,51,20,90,130,5,54,0,3,0,62,255,243,2,44,3,18,0,12,0,39,0,50,0,0,19,51,54,59,1,130,152,132,154,65,121,6,34,43,1,34,119, + 116,8,33,22,29,109,161,5,32,3,71,60,6,8,34,162,64,25,22,192,2,8,12,17,35,136,42,43,170,87,108,74,75,12,12,23,129,75,73,111,66,86,110,61,60,254,114,140,19,8,71,41,6,8,45,38,52,17,1, + 53,1,44,20,34,19,39,42,41,254,188,54,86,32,6,2,73,73,129,161,74,42,67,68,119,42,3,150,28,3,2,38,55,80,31,11,11,31,48,65,22,0,130,0,141,155,32,47,169,155,37,19,7,35,62,3,55,161,153, + 39,167,162,77,17,51,39,24,9,159,150,38,215,177,22,65,48,31,11,145,147,32,51,169,147,70,180,11,161,153,32,2,70,161,8,33,29,28,159,157,32,154,70,135,11,32,4,65,207,5,41,2,217,0,12,0, + 39,0,51,0,63,169,161,86,133,23,161,173,38,147,15,71,16,16,71,15,69,53,6,159,175,32,77,69,28,11,50,2,0,109,255,252,2,34,3,6,0,14,0,27,0,0,5,35,34,38,109,250,6,37,23,22,59,1,1,38,73, + 163,7,8,54,2,34,117,81,92,122,214,52,16,22,108,254,237,20,29,30,45,28,10,99,9,24,38,52,17,4,100,91,1,16,67,254,173,86,24,7,2,15,21,33,33,48,31,11,11,31,48,66,21,0,0,0,2,0,134,136,91, + 130,15,142,91,37,3,7,35,62,2,55,138,87,38,50,162,78,27,81,24,9,139,80,35,192,177,34,101,65,247,5,139,75,32,25,145,167,84,8,6,34,39,6,7,138,80,43,254,100,92,31,74,92,31,70,68,22,68, + 22,139,85,40,16,132,44,132,44,86,29,86,29,130,163,32,3,133,163,33,2,217,130,255,34,26,0,38,144,89,85,74,7,85,72,11,131,11,138,102,35,100,15,71,15,130,2,38,195,15,72,14,14,72,15,139, + 104,32,66,70,134,12,34,0,2,0,109,235,5,46,219,0,46,0,65,0,0,1,22,23,14,1,7,22,21,72,98,6,69,82,5,43,22,59,2,50,23,46,2,39,38,39,46,1,130,205,34,39,54,55,85,93,5,32,3,112,248,11,8,123, + 38,43,1,34,7,6,1,211,10,6,23,78,24,190,98,56,86,112,65,62,61,62,123,17,5,2,2,1,2,4,1,8,11,5,7,8,16,11,5,15,124,15,79,40,17,58,16,109,36,28,157,37,37,68,67,39,37,55,7,9,25,13,23,113, + 30,10,2,196,30,16,7,24,7,190,186,151,72,38,69,72,123,127,67,70,1,1,2,9,13,7,10,9,17,12,5,5,38,46,25,12,18,58,18,39,28,254,99,92,49,51,51,51,89,113,68,4,2,6,109,36,0,0,0,2,110,239,6, + 39,225,0,18,0,53,0,0,19,110,229,5,32,17,110,248,10,73,53,10,32,39,131,200,32,35,130,170,32,7,73,51,6,80,132,5,8,88,189,51,115,170,92,110,97,28,9,92,83,7,186,38,62,26,25,45,43,38,4, + 9,11,8,4,3,7,8,17,10,7,2,63,27,25,45,34,36,7,3,19,16,3,5,1,191,92,212,254,185,1,71,137,95,30,41,254,214,2,14,49,188,72,65,33,35,38,3,9,10,5,3,2,3,18,11,44,63,35,35,28,7,4,18,9,3,3, + 0,3,65,95,5,43,3,18,0,13,0,27,0,40,0,0,1,34,114,203,7,36,53,52,39,38,3,69,68,10,37,16,6,3,46,1,39,130,2,8,69,51,30,3,23,1,52,142,80,27,35,106,27,10,81,26,36,175,49,15,136,45,58,117, + 61,62,122,124,20,60,28,16,28,11,100,9,24,38,52,17,1,210,203,150,41,13,116,38,50,151,39,13,254,33,158,51,67,202,56,18,71,72,254,243,140,2,110,22,65,32,16,69,52,9,141,131,32,33,157,131, + 76,32,5,149,126,37,51,23,140,76,82,58,152,119,38,3,31,23,154,106,71,0,142,243,32,38,157,111,69,3,8,33,46,1,149,116,42,118,90,70,123,74,23,77,23,70,17,56,152,121,33,2,226,68,239,5,32, + 72,135,123,39,2,225,0,13,0,27,0,62,158,123,75,76,9,66,22,22,149,146,32,53,66,32,31,65,153,24,32,166,66,41,25,34,0,0,4,66,43,5,33,2,217,132,187,34,39,0,51,157,189,69,155,23,149,179, + 32,31,80,199,12,65,73,25,32,149,68,31,13,49,3,0,44,0,71,2,60,2,22,0,11,0,15,0,27,0,0,37,75,90,10,36,37,53,33,21,39,138,15,44,1,114,16,92,15,15,92,16,254,186,2,16,202,133,10,41,85,14, + 14,87,13,13,90,80,80,170,130,8,49,15,15,0,3,0,24,255,211,2,75,2,57,0,10,0,20,0,47,130,225,36,6,7,22,23,22,98,170,6,114,7,6,37,54,3,6,7,38,39,106,2,5,38,51,50,23,54,55,22,23,68,147, + 5,8,102,43,1,38,1,182,40,191,21,35,25,55,27,81,42,36,65,103,31,10,14,187,215,50,30,44,2,85,40,136,44,58,101,59,29,45,21,25,82,43,137,45,59,26,87,1,111,46,218,25,12,7,13,41,148,67,94, + 44,111,34,31,74,56,212,254,182,55,32,34,2,94,67,111,202,56,18,52,33,49,18,17,93,63,115,204,55,17,7,0,0,0,2,0,97,255,243,2,13,3,5,0,24,0,34,130,229,74,83,7,83,241,8,33,54,53,130,10, + 38,35,38,3,46,2,39,51,130,176,8,60,23,1,177,35,78,24,36,119,33,11,92,27,29,54,97,28,9,92,83,2,138,28,96,28,11,100,13,29,70,28,79,67,19,6,119,40,54,1,69,254,187,74,31,34,96,31,40,1, + 41,253,243,23,2,61,29,106,31,11,17,36,90,130,96,139,111,32,30,154,111,67,142,6,145,108,37,37,20,143,76,41,99,150,104,36,238,21,156,55,122,140,211,32,35,154,99,32,1,79,57,7,33,6,7,146, + 213,33,254,220,67,126,5,35,67,23,67,23,150,110,36,61,177,33,111,33,70,188,5,32,3,65,71,5,39,2,217,0,24,0,36,0,48,154,117,66,190,24,145,235,32,17,66,187,12,150,132,32,113,66,184,12, + 44,2,0,52,255,55,2,65,3,5,0,38,0,44,130,133,44,19,51,14,3,7,14,2,15,1,14,2,7,6,131,1,48,43,1,53,51,50,55,54,55,46,1,39,38,39,51,23,30,1,65,105,6,8,89,59,164,98,55,58,25,21,8,13,14, + 5,2,28,10,17,13,6,18,15,26,12,38,41,60,54,61,27,12,22,35,77,28,73,3,98,50,62,42,173,44,119,76,31,109,115,1,155,132,140,62,49,20,33,32,14,6,72,25,32,26,11,30,10,18,3,12,73,59,23,54, + 85,187,65,174,7,125,152,107,2,119,47,129,42,134,0,0,0,2,0,95,130,143,40,42,2,224,0,10,0,30,0,0,107,185,5,37,23,22,51,50,16,5,99,147,8,34,35,34,39,130,141,8,58,17,35,17,51,1,68,101, + 27,9,77,26,34,134,254,241,48,103,99,60,57,58,60,99,40,20,41,38,11,92,92,1,210,115,38,50,148,43,13,1,151,7,80,74,73,130,131,72,72,8,16,36,20,254,244,3,169,0,0,3,133,243,33,2,204,130, + 243,34,50,0,62,133,245,35,1,7,14,9,130,248,33,7,6,145,240,32,21,67,186,9,32,7,138,11,56,1,59,164,98,55,58,12,16,25,7,5,3,4,2,4,4,7,7,22,47,13,6,40,65,83,65,2,13,32,153,65,148,12,53, + 115,1,155,132,140,31,37,60,17,13,8,7,6,8,12,18,19,61,92,16,7,43,65,10,12,38,47,62,18,14,66,15,15,132,5,43,0,1,0,18,255,243,2,18,2,203,0,65,130,167,32,6,130,247,46,38,39,35,55,54,55, + 51,53,38,61,1,38,52,55,53,130,2,37,35,55,51,54,55,54,111,182,10,48,7,51,6,7,35,21,20,6,29,1,22,21,51,14,1,7,35,104,231,5,48,62,1,55,2,18,65,146,91,32,63,28,87,13,7,5,58,1,130,0,8,86, + 83,25,62,42,130,45,38,104,66,8,8,58,78,108,43,14,6,240,15,9,221,1,1,180,5,15,5,150,10,45,44,73,53,65,8,17,8,25,38,1,33,33,62,139,26,16,10,10,2,5,13,9,11,10,15,1,2,10,50,205,48,17,39, + 97,6,7,47,110,36,48,34,16,9,2,6,4,62,2,3,10,32,10,92,52,50,36,6,102,24,5,35,0,14,0,174,130,193,32,0,132,0,34,1,0,4,134,11,32,1,130,7,32,10,134,11,32,2,130,7,32,16,134,11,36,3,0,29, + 0,78,134,11,131,43,32,112,134,11,36,5,0,9,0,134,134,11,32,6,130,7,44,148,0,3,0,1,4,9,0,0,0,2,0,0,134,11,32,1,130,11,32,6,134,11,32,2,130,11,32,12,134,11,36,3,0,58,0,18,134,11,32,4, + 130,23,32,108,134,11,32,5,130,21,32,114,134,11,32,6,130,23,35,144,0,46,0,143,2,39,70,0,111,0,110,0,116,0,131,7,40,114,0,103,0,101,0,32,0,50,130,36,32,48,130,7,32,58,130,3,32,46,134, + 7,38,50,0,49,0,45,0,56,130,3,34,50,0,48,130,33,51,53,0,0,70,111,110,116,70,111,114,103,101,32,50,46,48,32,58,32,46,130,3,39,50,49,45,56,45,50,48,50,130,30,133,107,32,86,130,81,36,114, + 0,115,0,105,132,103,32,32,130,89,40,0,86,101,114,115,105,111,110,32,136,140,33,2,0,132,0,35,255,156,0,35,130,8,32,1,130,3,141,2,32,195,132,21,32,2,130,201,58,4,0,5,0,6,0,7,0,8,0,9, + 0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,130,235,62,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,130,93,50,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44, + 0,45,130,145,32,47,130,209,32,49,130,211,9,38,51,0,52,0,53,0,54,0,55,0,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,0,67,0,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0, + 78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,92,0,93,0,94,0,95,0,96,0,97,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,1,2, + 0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0, + 207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0,212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0, + 114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,1,3,7,117,110,105,48,48,97,100,131,7,45,50,48,97,99, + 0,0,0,1,255,255,0,2,0,1,130,9,32,12,130,3,32,16,130,3,36,2,0,0,0,4,134,7,32,0,132,25,36,0,223,214,203,49,130,17,24,92,127,12,5,250,205,249,72,146, +}; + +static const char* GetDefaultCompressedFontDataProggyVector(int* out_size) +{ + *out_size = proggy_vector_minimal_ttf_compressed_size; + return (const char*)proggy_vector_minimal_ttf_compressed_data; +} + +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui_internal.h b/libs/imgui/imgui_internal.h new file mode 100644 index 0000000..e3954bd --- /dev/null +++ b/libs/imgui/imgui_internal.h @@ -0,0 +1,4282 @@ +// dear imgui, v1.92.6 WIP +// (internal structures/api) + +// You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. + +/* + +Index of this file: + +// [SECTION] Header mess +// [SECTION] Forward declarations +// [SECTION] Context pointer +// [SECTION] STB libraries includes +// [SECTION] Macros +// [SECTION] Generic helpers +// [SECTION] ImDrawList support +// [SECTION] Style support +// [SECTION] Data types support +// [SECTION] Widgets support: flags, enums, data structures +// [SECTION] Popup support +// [SECTION] Inputs support +// [SECTION] Clipper support +// [SECTION] Navigation support +// [SECTION] Typing-select support +// [SECTION] Columns support +// [SECTION] Box-select support +// [SECTION] Multi-select support +// [SECTION] Docking support +// [SECTION] Viewport support +// [SECTION] Settings support +// [SECTION] Localization support +// [SECTION] Error handling, State recovery support +// [SECTION] Metrics, Debug tools +// [SECTION] Generic context hooks +// [SECTION] ImGuiContext (main imgui context) +// [SECTION] ImGuiWindowTempData, ImGuiWindow +// [SECTION] Tab bar, Tab item support +// [SECTION] Table support +// [SECTION] ImGui internal API +// [SECTION] ImFontLoader +// [SECTION] ImFontAtlas internal API +// [SECTION] Test Engine specific hooks (imgui_test_engine) + +*/ + +#pragma once +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +#ifndef IMGUI_VERSION +#include "imgui.h" +#endif + +#include // FILE*, sscanf +#include // NULL, malloc, free, qsort, atoi, atof +#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf +#include // INT_MIN, INT_MAX + +// Enable SSE intrinsics if available +#if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE) +#define IMGUI_ENABLE_SSE +#include +#if (defined __AVX__ || defined __SSE4_2__) +#define IMGUI_ENABLE_SSE4_2 +#include +#endif +#endif +// Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213 +#if defined(IMGUI_ENABLE_SSE4_2) && !defined(IMGUI_USE_LEGACY_CRC32_ADLER) && !defined(__EMSCRIPTEN__) +#define IMGUI_ENABLE_SSE4_2_CRC +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloor() +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning: function 'xxx' could be declared with attribute 'noreturn' +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result +#endif + +// In 1.89.4, we moved the implementation of "courtesy maths operators" from imgui_internal.h in imgui.h +// As they are frequently requested, we do not want to encourage to many people using imgui_internal.h +#if defined(IMGUI_DEFINE_MATH_OPERATORS) && !defined(IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED) +#error Please '#define IMGUI_DEFINE_MATH_OPERATORS' _BEFORE_ including imgui.h! +#endif + +// Legacy defines +#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 +#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS +#endif +#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 +#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS +#endif + +// Enable stb_truetype by default unless FreeType is enabled. +// You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. +#ifndef IMGUI_ENABLE_FREETYPE +#define IMGUI_ENABLE_STB_TRUETYPE +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations +//----------------------------------------------------------------------------- + +// Utilities +// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImStableVector<>, ImPool<>, ImChunkStream<>) +struct ImBitVector; // Store 1-bit per value +struct ImRect; // An axis-aligned rectangle (2 points) +struct ImGuiTextIndex; // Maintain a line index for a text buffer. + +// ImDrawList/ImFontAtlas +struct ImDrawDataBuilder; // Helper to build a ImDrawData instance +struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions +struct ImFontAtlasRectEntry; // Packed rectangle lookup entry + +// ImGui +struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) +struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it +struct ImGuiContext; // Main Dear ImGui context +struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine +struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum +struct ImGuiDeactivatedItemData; // Data for IsItemDeactivated()/IsItemDeactivatedAfterEdit() function. +struct ImGuiDockContext; // Docking system context +struct ImGuiDockRequest; // Docking system dock/undock queued request +struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes) +struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session) +struct ImGuiErrorRecoveryState; // Storage of stack sizes for error handling and recovery +struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() +struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box +struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a deactivating InputText() while another is stealing active id +struct ImGuiLastItemData; // Status storage for last submitted items +struct ImGuiLocEntry; // A localization entry. +struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only +struct ImGuiMultiSelectState; // Multi-selection persistent state (for focused selection). +struct ImGuiMultiSelectTempData; // Multi-selection temporary state (while traversing). +struct ImGuiNavItemData; // Result of a keyboard/gamepad directional navigation move query result +struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions +struct ImGuiNextWindowData; // Storage for SetNextWindow** functions +struct ImGuiNextItemData; // Storage for SetNextItem** functions +struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api +struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api +struct ImGuiPopupData; // Storage for current popup stack +struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file +struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum) +struct ImGuiTabBar; // Storage for a tab bar +struct ImGuiTabItem; // Storage for a tab item (within a tab bar) +struct ImGuiTable; // Storage for a table +struct ImGuiTableHeaderData; // Storage for TableAngledHeadersRow() +struct ImGuiTableColumn; // Storage for one column of a table +struct ImGuiTableInstanceData; // Storage for one instance of a same table +struct ImGuiTableTempData; // Temporary storage for one table (one per table in the stack), shared between tables. +struct ImGuiTableSettings; // Storage for a table .ini settings +struct ImGuiTableColumnsSettings; // Storage for a column .ini settings +struct ImGuiTreeNodeStackData; // Temporary storage for TreeNode(). +struct ImGuiTypingSelectState; // Storage for GetTypingSelectRequest() +struct ImGuiTypingSelectRequest; // Storage for GetTypingSelectRequest() (aimed to be public) +struct ImGuiWindow; // Storage for one window +struct ImGuiWindowDockStyle; // Storage for window-style data which needs to be stored for docking purpose +struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window) +struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) + +// Enumerations +// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. +enum ImGuiLocKey : int; // -> enum ImGuiLocKey // Enum: a localization entry for translation. +typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // Enum: for storing the source authority (dock node vs window) of a field +typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical + +// Flags +typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Flags: for ImTextCalcWordWrapPositionEx() +typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) +typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags +typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow() +typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for g.LastItemData.StatusFlags +typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() +typedef int ImGuiLogFlags; // -> enum ImGuiLogFlags_ // Flags: for LogBegin() text capturing function +typedef int ImGuiNavRenderCursorFlags; // -> enum ImGuiNavRenderCursorFlags_//Flags: for RenderNavCursor() +typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests +typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions +typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions +typedef int ImGuiScrollFlags; // -> enum ImGuiScrollFlags_ // Flags: for ScrollToItem() and navigation requests +typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() +typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() +typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() +typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() +typedef int ImGuiWindowBgClickFlags; // -> enum ImGuiWindowBgClickFlags_ // Flags: for overriding behavior of clicking on window background/void. +typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() + +// Table column indexing +typedef ImS16 ImGuiTableColumnIdx; +typedef ImU16 ImGuiTableDrawChannelIdx; + +//----------------------------------------------------------------------------- +// [SECTION] Context pointer +// See implementation of this variable in imgui.cpp for comments and details. +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Macros +//----------------------------------------------------------------------------- + +// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_WINDOW "_IMWINDOW" // Payload == ImGuiWindow* + +// Debug Printing Into TTY +// (since IMGUI_VERSION_NUM >= 18729: IMGUI_DEBUG_LOG was reworked into IMGUI_DEBUG_PRINTF (and removed framecount from it). If you were using a #define IMGUI_DEBUG_LOG please rename) +#ifndef IMGUI_DEBUG_PRINTF +#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS +#define IMGUI_DEBUG_PRINTF(_FMT,...) printf(_FMT, __VA_ARGS__) +#else +#define IMGUI_DEBUG_PRINTF(_FMT,...) ((void)0) +#endif +#endif + +// Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. +#define IMGUI_DEBUG_LOG_ERROR(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g.DebugLogSkippedErrors++; } while (0) +#define IMGUI_DEBUG_LOG_ACTIVEID(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_FOCUS(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_POPUP(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_NAV(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventNav) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext* g2 = GImGui; if (g2 && g2->DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Called from ImFontAtlas function which may operate without a context. +#define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_DOCKING(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventDocking) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_VIEWPORT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventViewport) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) + +// Static Asserts +#define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") + +// "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much. +// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code. +//#define IMGUI_DEBUG_PARANOID +#ifdef IMGUI_DEBUG_PARANOID +#define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR) +#else +#define IM_ASSERT_PARANOID(_EXPR) +#endif + +// Misc Macros +#define IM_PI 3.14159265358979323846f +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) +#else +#define IM_NEWLINE "\n" +#endif +#ifndef IM_TABSIZE // Until we move this to runtime and/or add proper tab support, at least allow users to compile-time override +#define IM_TABSIZE (4) +#endif +#define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 +#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! ImTrunc() is not inlined in MSVC debug builds +#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! +//#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) + +// Hint for branch prediction +#if (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 202002L)) +#define IM_LIKELY [[likely]] +#define IM_UNLIKELY [[unlikely]] +#else +#define IM_LIKELY +#define IM_UNLIKELY +#endif + +// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif + +// Warnings +#if defined(_MSC_VER) && !defined(__clang__) +#define IM_MSVC_WARNING_SUPPRESS(XXXX) __pragma(warning(suppress: XXXX)) +#else +#define IM_MSVC_WARNING_SUPPRESS(XXXX) +#endif + +// Debug Tools +// Use 'Metrics/Debugger->Tools->Item Picker' to break into the call-stack of a specific item. +// This will call IM_DEBUG_BREAK() which you may redefine yourself. See https://github.com/scottt/debugbreak for more reference. +#ifndef IM_DEBUG_BREAK +#if defined (_MSC_VER) +#define IM_DEBUG_BREAK() __debugbreak() +#elif defined(__clang__) +#define IM_DEBUG_BREAK() __builtin_debugtrap() +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define IM_DEBUG_BREAK() __asm__ volatile("int3;nop") +#elif defined(__GNUC__) && defined(__thumb__) +#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xde01") +#elif defined(__GNUC__) && defined(__arm__) && !defined(__thumb__) +#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xe7f001f0") +#else +#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! +#endif +#endif // #ifndef IM_DEBUG_BREAK + +// Format specifiers, printing 64-bit hasn't been decently standardized... +// In a real application you should be using PRId64 and PRIu64 from (non-windows) and on Windows define them yourself. +#if defined(_MSC_VER) && !defined(__clang__) +#define IM_PRId64 "I64d" +#define IM_PRIu64 "I64u" +#define IM_PRIX64 "I64X" +#else +#define IM_PRId64 "lld" +#define IM_PRIu64 "llu" +#define IM_PRIX64 "llX" +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Generic helpers +// Note that the ImXXX helpers functions are lower-level than ImGui functions. +// ImGui functions or the ImGui context are never called/used from other ImXXX functions. +//----------------------------------------------------------------------------- +// - Helpers: Hashing +// - Helpers: Sorting +// - Helpers: Bit manipulation +// - Helpers: String +// - Helpers: Formatting +// - Helpers: UTF-8 <> wchar conversions +// - Helpers: ImVec2/ImVec4 operators +// - Helpers: Maths +// - Helpers: Geometry +// - Helper: ImVec1 +// - Helper: ImVec2ih +// - Helper: ImRect +// - Helper: ImBitArray +// - Helper: ImBitVector +// - Helper: ImSpan<>, ImSpanAllocator<> +// - Helper: ImStableVector<> +// - Helper: ImPool<> +// - Helper: ImChunkStream<> +// - Helper: ImGuiTextIndex +// - Helper: ImGuiStorage +//----------------------------------------------------------------------------- + +// Helpers: Hashing +IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImGuiID seed = 0); +IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0); +IMGUI_API const char* ImHashSkipUncontributingPrefix(const char* label); + +// Helpers: Sorting +#ifndef ImQsort +inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); } +#endif + +// Helpers: Color Blending +IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); + +// Helpers: Bit manipulation +inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } +inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } +inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; } + +// Helpers: String +#define ImStrlen strlen +#define ImMemchr memchr +IMGUI_API int ImStricmp(const char* str1, const char* str2); // Case insensitive compare. +IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count. +IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). +IMGUI_API char* ImStrdup(const char* str); // Duplicate a string. +IMGUI_API void* ImMemdup(const void* src, size_t size); // Duplicate a chunk of memory. +IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed. +IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range. +IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); // Find a substring in a string range. +IMGUI_API void ImStrTrimBlanks(char* str); // Remove leading and trailing blanks from a buffer. +IMGUI_API const char* ImStrSkipBlank(const char* str); // Find first non-blank character. +IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) +IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line +IM_MSVC_RUNTIME_CHECKS_OFF +inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } +inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } +inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } +inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Helpers: Formatting +IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3); +IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3); +IMGUI_API void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) IM_FMTARGS(3); +IMGUI_API void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) IM_FMTLIST(3); +IMGUI_API const char* ImParseFormatFindStart(const char* format); +IMGUI_API const char* ImParseFormatFindEnd(const char* format); +IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size); +IMGUI_API void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size); +IMGUI_API const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size); +IMGUI_API int ImParseFormatPrecision(const char* format, int default_value); + +// Helpers: UTF-8 <> wchar conversions +IMGUI_API int ImTextCharToUtf8(char out_buf[5], unsigned int c); // return output UTF-8 bytes count +IMGUI_API int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count +IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8 +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8 +IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_p); // return previous UTF-8 code-point. +IMGUI_API const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const char* in_text_end, const char* in_p); // return previous UTF-8 code-point if 'in_p' is not the end of a valid one. +IMGUI_API int ImTextCountLines(const char* in_text, const char* in_text_end); // return number of lines taken by text. trailing carriage return doesn't count as an extra line. + +// Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) +enum ImDrawTextFlags_ +{ + ImDrawTextFlags_None = 0, + ImDrawTextFlags_CpuFineClip = 1 << 0, // Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText() + ImDrawTextFlags_WrapKeepBlanks = 1 << 1, + ImDrawTextFlags_StopOnNewLine = 1 << 2, +}; +IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags); +IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags = 0); +IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags = 0); // trim trailing space and find beginning of next line + +// Character classification for word-wrapping logic +enum ImWcharClass +{ + ImWcharClass_Blank, ImWcharClass_Punct, ImWcharClass_Other +}; +IMGUI_API void ImTextInitClassifiers(); +IMGUI_API void ImTextClassifierClear(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class); +IMGUI_API void ImTextClassifierSetCharClass(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, unsigned int c); +IMGUI_API void ImTextClassifierSetCharClassFromStr(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, const char* s); + +// Helpers: File System +#ifdef IMGUI_DISABLE_FILE_FUNCTIONS +#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS +typedef void* ImFileHandle; +inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } +inline bool ImFileClose(ImFileHandle) { return false; } +inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } +inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } +inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } +#endif +#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS +typedef FILE* ImFileHandle; +IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); +IMGUI_API bool ImFileClose(ImFileHandle file); +IMGUI_API ImU64 ImFileGetSize(ImFileHandle file); +IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file); +IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file); +#else +#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions +#endif +IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0); + +// Helpers: Maths +IM_MSVC_RUNTIME_CHECKS_OFF +// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS +#define ImFabs(X) fabsf(X) +#define ImSqrt(X) sqrtf(X) +#define ImFmod(X, Y) fmodf((X), (Y)) +#define ImCos(X) cosf(X) +#define ImSin(X) sinf(X) +#define ImAcos(X) acosf(X) +#define ImAtan2(Y, X) atan2f((Y), (X)) +#define ImAtof(STR) atof(STR) +#define ImCeil(X) ceilf(X) +inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +inline double ImPow(double x, double y) { return pow(x, y); } +inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision +inline double ImLog(double x) { return log(x); } +inline int ImAbs(int x) { return x < 0 ? -x : x; } +inline float ImAbs(float x) { return fabsf(x); } +inline double ImAbs(double x) { return fabs(x); } +inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument +inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } +#ifdef IMGUI_ENABLE_SSE +inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } +#else +inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } +#endif +inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } +#endif +// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double +// (Exceptionally using templates here but we could also redefine them for those types) +template T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } +template T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } +template T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +template T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } +template void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } +template T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } +template T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } +// - Misc maths helpers +inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } +inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } +inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx){ return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } +inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } +inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } +inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } +inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } +inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } +inline float ImTrunc(float f) { return (float)(int)(f); } +inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } +inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() +inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } +inline float ImTrunc64(float f) { return (float)(ImS64)(f); } +inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } // FIXME: Positive values only. +inline int ImModPositive(int a, int b) { return (a + b) % b; } +inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } +inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } +inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } +inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } +inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } +inline float ImExponentialMovingAverage(float avg, float sample, int n){ avg -= avg / n; avg += sample / n; return avg; } +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Helpers: Geometry +IMGUI_API ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t); +IMGUI_API ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments); // For curves with explicit number of segments +IMGUI_API ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol +IMGUI_API ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t); +IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p); +IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); +IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); +IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w); +inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } +inline bool ImTriangleIsClockwise(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) > 0.0f; } + +// Helper: ImVec1 (1D vector) +// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec1 +{ + float x; + constexpr ImVec1() : x(0.0f) { } + constexpr ImVec1(float _x) : x(_x) { } +}; + +// Helper: ImVec2i (2D vector, integer) +struct ImVec2i +{ + int x, y; + constexpr ImVec2i() : x(0), y(0) {} + constexpr ImVec2i(int _x, int _y) : x(_x), y(_y) {} +}; + +// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) +struct ImVec2ih +{ + short x, y; + constexpr ImVec2ih() : x(0), y(0) {} + constexpr ImVec2ih(short _x, short _y) : x(_x), y(_y) {} + constexpr explicit ImVec2ih(const ImVec2& rhs) : x((short)rhs.x), y((short)rhs.y) {} +}; + +// Helper: ImRect (2D axis aligned bounding-box) +// NB: we can't rely on ImVec2 math operators being available here! +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + constexpr ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} + constexpr ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + constexpr ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + constexpr ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } + float GetWidth() const { return Max.x - Min.x; } + float GetHeight() const { return Max.y - Min.y; } + float GetArea() const { return (Max.x - Min.x) * (Max.y - Min.y); } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool ContainsWithPad(const ImVec2& p, const ImVec2& pad) const { return p.x >= Min.x - pad.x && p.y >= Min.y - pad.y && p.x < Max.x + pad.x && p.y < Max.y + pad.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } + void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } + void TranslateX(float dx) { Min.x += dx; Max.x += dx; } + void TranslateY(float dy) { Min.y += dy; Max.y += dy; } + void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. + void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. + bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } + const ImVec4& AsVec4() const { return *(const ImVec4*)&Min.x; } +}; + +// Helper: ImBitArray +#define IM_BITARRAY_TESTBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] & ((ImU32)1 << ((_N) & 31))) != 0) // Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! +#define IM_BITARRAY_CLEARBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] &= ~((ImU32)1 << ((_N) & 31)))) // Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! +inline size_t ImBitArrayGetStorageSizeInBytes(int bitcount) { return (size_t)((bitcount + 31) >> 5) << 2; } +inline void ImBitArrayClearAllBits(ImU32* arr, int bitcount){ memset(arr, 0, ImBitArrayGetStorageSizeInBytes(bitcount)); } +inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } +inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } +inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } +inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) // Works on range [n..n2) +{ + n2--; + while (n <= n2) + { + int a_mod = (n & 31); + int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1; + ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1); + arr[n >> 5] |= mask; + n = (n + 32) & ~31; + } +} + +typedef ImU32* ImBitArrayPtr; // Name for use in structs + +// Helper: ImBitArray class (wrapper over ImBitArray functions) +// Store 1-bit per value. +template +struct ImBitArray +{ + ImU32 Data[(BITCOUNT + 31) >> 5]; + ImBitArray() { ClearAllBits(); } + void ClearAllBits() { memset(Data, 0, sizeof(Data)); } + void SetAllBits() { memset(Data, 255, sizeof(Data)); } + bool TestBit(int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Data, n); } + void SetBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArraySetBit(Data, n); } + void ClearBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArrayClearBit(Data, n); } + void SetBitRange(int n, int n2) { n += OFFSET; n2 += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); ImBitArraySetBitRange(Data, n, n2); } // Works on range [n..n2) + bool operator[](int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Data, n); } +}; + +// Helper: ImBitVector +// Store 1-bit per value. +struct IMGUI_API ImBitVector +{ + ImVector Storage; + void Create(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); } + void Clear() { Storage.clear(); } + bool TestBit(int n) const { IM_ASSERT(n < (Storage.Size << 5)); return IM_BITARRAY_TESTBIT(Storage.Data, n); } + void SetBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); } + void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Helper: ImSpan<> +// Pointing to a span of data we don't own. +template +struct ImSpan +{ + T* Data; + T* DataEnd; + + // Constructors, destructor + inline ImSpan() { Data = DataEnd = NULL; } + inline ImSpan(T* data, int size) { Data = data; DataEnd = data + size; } + inline ImSpan(T* data, T* data_end) { Data = data; DataEnd = data_end; } + + inline void set(T* data, int size) { Data = data; DataEnd = data + size; } + inline void set(T* data, T* data_end) { Data = data; DataEnd = data_end; } + inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); } + inline int size_in_bytes() const { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); } + inline T& operator[](int i) { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } + inline const T& operator[](int i) const { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return DataEnd; } + inline const T* end() const { return DataEnd; } + + // Utilities + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; } +}; + +// Helper: ImSpanAllocator<> +// Facilitate storing multiple chunks into a single large block (the "arena") +// - Usage: call Reserve() N times, allocate GetArenaSizeInBytes() worth, pass it to SetArenaBasePtr(), call GetSpan() N times to retrieve the aligned ranges. +template +struct ImSpanAllocator +{ + char* BasePtr; + int CurrOff; + int CurrIdx; + int Offsets[CHUNKS]; + int Sizes[CHUNKS]; + + ImSpanAllocator() { memset(this, 0, sizeof(*this)); } + inline void Reserve(int n, size_t sz, int a=4) { IM_ASSERT(n == CurrIdx && n < CHUNKS); CurrOff = IM_MEMALIGN(CurrOff, a); Offsets[n] = CurrOff; Sizes[n] = (int)sz; CurrIdx++; CurrOff += (int)sz; } + inline int GetArenaSizeInBytes() { return CurrOff; } + inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } + inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n]); } + inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n] + Sizes[n]); } + template + inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } +}; + +// Helper: ImStableVector<> +// Allocating chunks of BLOCKSIZE items. Objects pointers are never invalidated when growing, only by clear(). +// Important: does not destruct anything! +// Implemented only the minimum set of functions we need for it. +template +struct ImStableVector +{ + int Size = 0; + int Capacity = 0; + ImVector Blocks; + + // Functions + inline ~ImStableVector() { for (T* block : Blocks) IM_FREE(block); } + + inline void clear() { Size = Capacity = 0; Blocks.clear_delete(); } + inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } + inline void reserve(int new_cap) + { + new_cap = IM_MEMALIGN(new_cap, BLOCKSIZE); + int old_count = Capacity / BLOCKSIZE; + int new_count = new_cap / BLOCKSIZE; + if (new_count <= old_count) + return; + Blocks.resize(new_count); + for (int n = old_count; n < new_count; n++) + Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCKSIZE); + Capacity = new_cap; + } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; } + inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCKSIZE); void* ptr = &Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } +}; + +// Helper: ImPool<> +// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, +// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. +typedef int ImPoolIdx; +template +struct ImPool +{ + ImVector Buf; // Contiguous data + ImGuiStorage Map; // ID->Index + ImPoolIdx FreeIdx; // Next free idx to use + ImPoolIdx AliveCount; // Number of active/alive items (for display purpose) + + ImPool() { FreeIdx = AliveCount = 0; } + ~ImPool() { Clear(); } + T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; } + T* GetByIndex(ImPoolIdx n) { return &Buf[n]; } + ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); } + T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); } + bool Contains(const T* p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); } + void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = AliveCount = 0; } + T* Add() { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); AliveCount++; return &Buf[idx]; } + void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); } + void Remove(ImGuiID key, ImPoolIdx idx) { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); AliveCount--; } + void Reserve(int capacity) { Buf.reserve(capacity); Map.Data.reserve(capacity); } + + // To iterate a ImPool: for (int n = 0; n < pool.GetMapSize(); n++) if (T* t = pool.TryGetMapData(n)) { ... } + // Can be avoided if you know .Remove() has never been called on the pool, or AliveCount == GetMapSize() + int GetAliveCount() const { return AliveCount; } // Number of active/alive items in the pool (for display purpose) + int GetBufSize() const { return Buf.Size; } + int GetMapSize() const { return Map.Data.Size; } // It is the map we need iterate to find valid items, since we don't have "alive" storage anywhere + T* TryGetMapData(ImPoolIdx n) { int idx = Map.Data[n].val_i; if (idx == -1) return NULL; return GetByIndex(idx); } +}; + +// Helper: ImChunkStream<> +// Build and iterate a contiguous stream of variable-sized structures. +// This is used by Settings to store persistent data while reducing allocation count. +// We store the chunk size first, and align the final size on 4 bytes boundaries. +// The tedious/zealous amount of casting is to avoid -Wcast-align warnings. +template +struct ImChunkStream +{ + ImVector Buf; + + void clear() { Buf.clear(); } + bool empty() const { return Buf.Size == 0; } + int size() const { return Buf.Size; } + T* alloc_chunk(size_t sz) { size_t HDR_SZ = 4; sz = IM_MEMALIGN(HDR_SZ + sz, 4u); int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); } + T* begin() { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); } + T* next_chunk(T* p) { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; } + int chunk_size(const T* p) { return ((const int*)p)[-1]; } + T* end() { return (T*)(void*)(Buf.Data + Buf.Size); } + int offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; } + T* ptr_from_offset(int off) { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); } + void swap(ImChunkStream& rhs) { rhs.Buf.swap(Buf); } +}; + +// Helper: ImGuiTextIndex +// Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. +struct ImGuiTextIndex +{ + ImVector Offsets; + int EndOffset = 0; // Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) + + void clear() { Offsets.clear(); EndOffset = 0; } + int size() { return Offsets.Size; } + const char* get_line_begin(const char* base, int n) { return base + (Offsets.Size != 0 ? Offsets[n] : 0); } + const char* get_line_end(const char* base, int n) { return base + (n + 1 < Offsets.Size ? (Offsets[n + 1] - 1) : EndOffset); } + void append(const char* base, int old_size, int new_size); +}; + +// Helper: ImGuiStorage +IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key); + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList support +//----------------------------------------------------------------------------- + +// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. +// Estimation of number of circle segment based on error is derived using method described in https://stackoverflow.com/a/2244088/15194693 +// Number of segments (N) is calculated using equation: +// N = ceil ( pi / acos(1 - error / r) ) where r > 0, error <= r +// Our equation is significantly simpler that one in the post thanks for choosing segment that is +// perpendicular to X axis. Follow steps in the article from this starting condition and you will +// will get this result. +// +// Rendering circles with an odd number of segments, while mathematically correct will produce +// asymmetrical results on the raster grid. Therefore we're rounding N to next even number (7->8, 8->8, 9->10 etc.) +#define IM_ROUNDUP_TO_EVEN(_V) ((((_V) + 1) / 2) * 2) +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 4 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp(IM_ROUNDUP_TO_EVEN((int)ImCeil(IM_PI / ImAcos(1 - ImMin((_MAXERROR), (_RAD)) / (_RAD)))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) + +// Raw equation from IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC rewritten for 'r' and 'error'. +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) + +// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. +#ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE +#define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. +#endif +#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. + +// Data shared between all ImDrawList instances +// Conceptually this could have been called e.g. ImDrawListSharedContext +// Typically one ImGui context would create and maintain one of this. +// You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. +struct IMGUI_API ImDrawListSharedData +{ + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) + ImFontAtlas* FontAtlas; // Current font atlas + ImFont* Font; // Current font (used for simplified AddText overload) + float FontSize; // Current font size (used for for simplified AddText overload) + float FontScale; // Current font scale (== FontSize / Font->FontSize) + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() + float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc + float InitialFringeScale; // Initial scale to apply to AA fringe + ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + ImVector TempBuffer; // Temporary write buffer + ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData + ImGuiContext* Context; // [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. + + // Lookup tables + ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. + float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() + ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) + + ImDrawListSharedData(); + ~ImDrawListSharedData(); + void SetCircleTessellationMaxError(float max_error); +}; + +struct ImDrawDataBuilder +{ + ImVector* Layers[2]; // Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. + ImVector LayerData1; + + ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } +}; + +struct ImFontStackData +{ + ImFont* Font; + float FontSizeBeforeScaling; // ~~ style.FontSizeBase + float FontSizeAfterScaling; // ~~ g.FontSize +}; + +//----------------------------------------------------------------------------- +// [SECTION] Style support +//----------------------------------------------------------------------------- + +struct ImGuiStyleVarInfo +{ + ImU32 Count : 8; // 1+ + ImGuiDataType DataType : 8; + ImU32 Offset : 16; // Offset in parent structure + void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); } +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Data types support +//----------------------------------------------------------------------------- + +struct ImGuiDataTypeStorage +{ + ImU8 Data[8]; // Opaque storage to fit any data up to ImGuiDataType_COUNT +}; + +// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). +struct ImGuiDataTypeInfo +{ + size_t Size; // Size in bytes + const char* Name; // Short descriptive name for the type, for debugging + const char* PrintFmt; // Default printf format for the type + const char* ScanFmt; // Default scanf format for the type +}; + +// Extend ImGuiDataType_ +enum ImGuiDataTypePrivate_ +{ + ImGuiDataType_Pointer = ImGuiDataType_COUNT, + ImGuiDataType_ID, +}; + +//----------------------------------------------------------------------------- +// [SECTION] Widgets support: flags, enums, data structures +//----------------------------------------------------------------------------- + +// Extend ImGuiItemFlags +// - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too. +// - output: stored in g.LastItemData.ItemFlags +enum ImGuiItemFlagsPrivate_ +{ + // Controlled by user + ImGuiItemFlags_ReadOnly = 1 << 11, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. + ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, // false // Disable hoverable check in ItemHoverable() + ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. + ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, // false // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). + ImGuiItemFlags_NoMarkEdited = 1 << 16, // false // Skip calling MarkItemEdited() + ImGuiItemFlags_NoFocus = 1 << 17, // false // [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags_NoFocus + ImGuiButtonFlags_NoNavFocus in ButtonBehavior(). + + // Controlled by widget code + ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. + ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() + ImGuiItemFlags_IsMultiSelect = 1 << 22, // false // Set by SetNextItemSelectionUserData() + + ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, // Please don't change, use PushItemFlag() instead. + + // Obsolete + //ImGuiItemFlags_SelectableDontClosePopup = !ImGuiItemFlags_AutoClosePopups, // Can't have a redirect as we inverted the behavior +}; + +// Status flags for an already submitted item +// - output: stored in g.LastItemData.StatusFlags +enum ImGuiItemStatusFlags_ +{ + ImGuiItemStatusFlags_None = 0, + ImGuiItemStatusFlags_HoveredRect = 1 << 0, // Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) + ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, // g.LastItemData.DisplayRect is valid + ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. + ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. + ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. + ImGuiItemStatusFlags_Deactivated = 1 << 6, // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. + ImGuiItemStatusFlags_HoveredWindow = 1 << 7, // Override the HoveredWindow test to allow cross-window hover testing. + ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). + ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid. + ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd(). + //ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Removed IN 1.90.1 (Dec 2023). The trigger is part of g.NavActivateId. See commit 54c1bdeceb. + + // Additional status + semantic for ImGuiTestEngine +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiItemStatusFlags_Openable = 1 << 20, // Item is an openable (e.g. TreeNode) + ImGuiItemStatusFlags_Opened = 1 << 21, // Opened status + ImGuiItemStatusFlags_Checkable = 1 << 22, // Item is a checkable (e.g. CheckBox, MenuItem) + ImGuiItemStatusFlags_Checked = 1 << 23, // Checked status + ImGuiItemStatusFlags_Inputable = 1 << 24, // Item is a text-inputable (e.g. InputText, SliderXXX, DragXXX) +#endif +}; + +// Extend ImGuiHoveredFlags_ +enum ImGuiHoveredFlagsPrivate_ +{ + ImGuiHoveredFlags_DelayMask_ = ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay, + ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, + ImGuiHoveredFlags_AllowedMaskForIsItemHovered = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayMask_, +}; + +// Extend ImGuiInputTextFlags_ +enum ImGuiInputTextFlagsPrivate_ +{ + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() + ImGuiInputTextFlags_MergedItem = 1 << 27, // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. + ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 28, // For internal use by InputScalar() and TempInputScalar() +}; + +// Extend ImGuiButtonFlags_ +enum ImGuiButtonFlagsPrivate_ +{ + ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) + ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using + ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item + ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) + //ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat -> use ImGuiItemFlags_ButtonRepeat instead. + ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping + ImGuiButtonFlags_AllowOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable. + //ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press + //ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled + ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + ImGuiButtonFlags_NoKeyModsAllowed = 1 << 16, // disable mouse interaction if a key modifier is held + ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) + ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags) + ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item + ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) + ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) + ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. + ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, + ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, + //ImGuiButtonFlags_NoKeyModifiers = ImGuiButtonFlags_NoKeyModsAllowed, // Renamed in 1.91.4 +}; + +// Extend ImGuiComboFlags_ +enum ImGuiComboFlagsPrivate_ +{ + ImGuiComboFlags_CustomPreview = 1 << 20, // enable BeginComboPreview() +}; + +// Extend ImGuiSliderFlags_ +enum ImGuiSliderFlagsPrivate_ +{ + ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? + ImGuiSliderFlags_ReadOnly = 1 << 21, // Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags_ReadOnly instead. +}; + +// Extend ImGuiSelectableFlags_ +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release) + ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release) + ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem) + ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26, // Disable padding each side with ItemSpacing * 0.5f + ImGuiSelectableFlags_NoSetKeyOwner = 1 << 27, // Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) +}; + +// Extend ImGuiTreeNodeFlags_ +enum ImGuiTreeNodeFlagsPrivate_ +{ + ImGuiTreeNodeFlags_NoNavFocus = 1 << 27,// Don't claim nav focus when interacting with this item (#8551) + ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() + ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) + ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, + ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes, +}; + +enum ImGuiSeparatorFlags_ +{ + ImGuiSeparatorFlags_None = 0, + ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar + ImGuiSeparatorFlags_Vertical = 1 << 1, + ImGuiSeparatorFlags_SpanAllColumns = 1 << 2, // Make separator cover all columns of a legacy Columns() set. +}; + +// Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. +// FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() +// and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. +enum ImGuiFocusRequestFlags_ +{ + ImGuiFocusRequestFlags_None = 0, + ImGuiFocusRequestFlags_RestoreFocusedChild = 1 << 0, // Find last focused child (if any) and focus it instead. + ImGuiFocusRequestFlags_UnlessBelowModal = 1 << 1, // Do not set focus if the window is below a modal. +}; + +enum ImGuiTextFlags_ +{ + ImGuiTextFlags_None = 0, + ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0, +}; + +enum ImGuiTooltipFlags_ +{ + ImGuiTooltipFlags_None = 0, + ImGuiTooltipFlags_OverridePrevious = 1 << 1, // Clear/ignore previously submitted tooltip (defaults to append) +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Horizontal = 0, + ImGuiLayoutType_Vertical = 1 +}; + +// Flags for LogBegin() text capturing function +enum ImGuiLogFlags_ +{ + ImGuiLogFlags_None = 0, + + ImGuiLogFlags_OutputTTY = 1 << 0, + ImGuiLogFlags_OutputFile = 1 << 1, + ImGuiLogFlags_OutputBuffer = 1 << 2, + ImGuiLogFlags_OutputClipboard = 1 << 3, + ImGuiLogFlags_OutputMask_ = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard, +}; + +// X/Y enums are fixed to 0/1 so they may be used to index ImVec2 +enum ImGuiAxis +{ + ImGuiAxis_None = -1, + ImGuiAxis_X = 0, + ImGuiAxis_Y = 1 +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram, +}; + +// Storage data for BeginComboPreview()/EndComboPreview() +struct IMGUI_API ImGuiComboPreviewData +{ + ImRect PreviewRect; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec2 BackupCursorPosPrevLine; + float BackupPrevLineTextBaseOffset; + ImGuiLayoutType BackupLayout; + + ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); } +}; + +// Stacked storage data for BeginGroup()/EndGroup() +struct IMGUI_API ImGuiGroupData +{ + ImGuiID WindowID; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec2 BackupCursorPosPrevLine; + ImVec1 BackupIndent; + ImVec1 BackupGroupOffset; + ImVec2 BackupCurrLineSize; + float BackupCurrLineTextBaseOffset; + ImGuiID BackupActiveIdIsAlive; + bool BackupActiveIdHasBeenEditedThisFrame; + bool BackupDeactivatedIdIsAlive; + bool BackupHoveredIdIsAlive; + bool BackupIsSameLine; + bool EmitItem; +}; + +// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiMenuColumns +{ + ImU32 TotalWidth; + ImU32 NextTotalWidth; + ImU16 Spacing; + ImU16 OffsetIcon; // Always zero for now + ImU16 OffsetLabel; // Offsets are locked in Update() + ImU16 OffsetShortcut; + ImU16 OffsetMark; + ImU16 Widths[4]; // Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) + + ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } + void Update(float spacing, bool window_reappearing); + float DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark); + void CalcNextTotalWidth(bool update_offsets); +}; + +// Internal temporary state for deactivating InputText() instances. +struct IMGUI_API ImGuiInputTextDeactivatedState +{ + ImGuiID ID; // widget id owning the text state (which just got deactivated) + ImVector TextA; // text buffer + + ImGuiInputTextDeactivatedState() { memset(this, 0, sizeof(*this)); } + void ClearFreeMemory() { ID = 0; TextA.clear(); } +}; + +// Forward declare imstb_textedit.h structure + make its main configuration define accessible +#undef IMSTB_TEXTEDIT_STRING +#undef IMSTB_TEXTEDIT_CHARTYPE +#define IMSTB_TEXTEDIT_STRING ImGuiInputTextState +#define IMSTB_TEXTEDIT_CHARTYPE char +#define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) +#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 +#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 +namespace ImStb { struct STB_TexteditState; } +typedef ImStb::STB_TexteditState ImStbTexteditState; + +// Internal state of the currently focused/edited text input box +// For a given item ID, access with ImGui::GetInputTextState() +struct IMGUI_API ImGuiInputTextState +{ + ImGuiContext* Ctx; // parent UI context (needs to be set explicitly by parent). + ImStbTexteditState* Stb; // State for stb_textedit.h + ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set. + ImGuiID ID; // widget id owning the text state + int TextLen; // UTF-8 length of the string in TextA (in bytes) + const char* TextSrc; // == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call. + ImVector TextA; // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). + ImVector TextToRevertTo; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector CallbackTextBackup; // temporary storage for callback to support automatic reconcile of undo-stack + int BufCapacity; // end-user buffer capacity (include zero terminator) + ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) + int LineCount; // last line count (solely for debugging) + float WrapWidth; // word-wrapping width + float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately + bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) + bool CursorCenterY; // set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field) + bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection + bool Edited; // edited this frame + bool WantReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version. + ImS8 LastMoveDirectionLR; // ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s + int ReloadSelectionStart; + int ReloadSelectionEnd; + + ImGuiInputTextState(); + ~ImGuiInputTextState(); + void ClearText() { TextLen = 0; TextA[0] = 0; CursorClamp(); } + void ClearFreeMemory() { TextA.clear(); TextToRevertTo.clear(); } + void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation + void OnCharPressed(unsigned int c); + float GetPreferredOffsetX() const; + + // Cursor & Selection + void CursorAnimReset(); + void CursorClamp(); + bool HasSelection() const; + void ClearSelection(); + int GetCursorPos() const; + int GetSelectionStart() const; + int GetSelectionEnd() const; + void SetSelection(int start, int end); + void SelectAll(); + + // Reload user buf (WIP #2890) + // If you modify underlying user-passed const char* while active you need to call this (InputText V2 may lift this) + // strcpy(my_buf, "hello"); + // if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item + // state->ReloadUserBufAndSelectAll(); + void ReloadUserBufAndSelectAll(); + void ReloadUserBufAndKeepSelection(); + void ReloadUserBufAndMoveToEnd(); +}; + +enum ImGuiWindowRefreshFlags_ +{ + ImGuiWindowRefreshFlags_None = 0, + ImGuiWindowRefreshFlags_TryToAvoidRefresh = 1 << 0, // [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. + ImGuiWindowRefreshFlags_RefreshOnHover = 1 << 1, // [EXPERIMENTAL] Always refresh on hover + ImGuiWindowRefreshFlags_RefreshOnFocus = 1 << 2, // [EXPERIMENTAL] Always refresh on focus + // Refresh policy/frequency, Load Balancing etc. +}; + +enum ImGuiWindowBgClickFlags_ +{ + ImGuiWindowBgClickFlags_None = 0, + ImGuiWindowBgClickFlags_Move = 1 << 0, // Click on bg/void + drag to move window. Cleared by default when using io.ConfigWindowsMoveFromTitleBarOnly. +}; + +enum ImGuiNextWindowDataFlags_ +{ + ImGuiNextWindowDataFlags_None = 0, + ImGuiNextWindowDataFlags_HasPos = 1 << 0, + ImGuiNextWindowDataFlags_HasSize = 1 << 1, + ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, + ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, + ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, + ImGuiNextWindowDataFlags_HasFocus = 1 << 5, + ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, + ImGuiNextWindowDataFlags_HasScroll = 1 << 7, + ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8, + ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9, + ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10, + ImGuiNextWindowDataFlags_HasViewport = 1 << 11, + ImGuiNextWindowDataFlags_HasDock = 1 << 12, + ImGuiNextWindowDataFlags_HasWindowClass = 1 << 13, +}; + +// Storage for SetNexWindow** functions +struct ImGuiNextWindowData +{ + ImGuiNextWindowDataFlags HasFlags; + + // Members below are NOT cleared. Always rely on HasFlags. + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond CollapsedCond; + ImGuiCond DockCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + ImVec2 ScrollVal; + ImGuiWindowFlags WindowFlags; // Only honored by BeginTable() + ImGuiChildFlags ChildFlags; + bool PosUndock; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void* SizeCallbackUserData; + float BgAlphaVal; // Override background alpha + ImGuiID ViewportId; + ImGuiID DockId; + ImGuiWindowClass WindowClass; + ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) + ImGuiWindowRefreshFlags RefreshFlagsVal; + + ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } + inline void ClearFlags() { HasFlags = ImGuiNextWindowDataFlags_None; } +}; + +enum ImGuiNextItemDataFlags_ +{ + ImGuiNextItemDataFlags_None = 0, + ImGuiNextItemDataFlags_HasWidth = 1 << 0, + ImGuiNextItemDataFlags_HasOpen = 1 << 1, + ImGuiNextItemDataFlags_HasShortcut = 1 << 2, + ImGuiNextItemDataFlags_HasRefVal = 1 << 3, + ImGuiNextItemDataFlags_HasStorageID = 1 << 4, + ImGuiNextItemDataFlags_HasColorMarker = 1 << 5, +}; + +struct ImGuiNextItemData +{ + ImGuiNextItemDataFlags HasFlags; // Called HasFlags instead of Flags to avoid mistaking this + ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData. + + // Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. + ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() + ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) + float Width; // Set by SetNextItemWidth() + ImGuiKeyChord Shortcut; // Set by SetNextItemShortcut() + ImGuiInputFlags ShortcutFlags; // Set by SetNextItemShortcut() + bool OpenVal; // Set by SetNextItemOpen() + ImU8 OpenCond; // Set by SetNextItemOpen() + ImGuiDataTypeStorage RefVal; // Not exposed yet, for ImGuiInputTextFlags_ParseEmptyAsRefVal + ImGuiID StorageId; // Set by SetNextItemStorageID() + ImU32 ColorMarker; // Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags_ColorMarkers. + + ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } + inline void ClearFlags() { HasFlags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! +}; + +// Status storage for the last submitted item +struct ImGuiLastItemData +{ + ImGuiID ID; + ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_ (called 'InFlags' before v1.91.4). + ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_ + ImRect Rect; // Full rectangle + ImRect NavRect; // Navigation scoring rectangle (not displayed) + // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. + ImRect DisplayRect; // Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) is set. + ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set.. + ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set.. + + ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } +}; + +// Store data emitted by TreeNode() for usage by TreePop() +// - To implement ImGuiTreeNodeFlags_NavLeftJumpsToParent: store the minimum amount of data +// which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). +// Only stored when the node is a potential candidate for landing on a Left arrow jump. +struct ImGuiTreeNodeStackData +{ + ImGuiID ID; + ImGuiTreeNodeFlags TreeFlags; + ImGuiItemFlags ItemFlags; // Used for nav landing + ImRect NavRect; // Used for nav landing + float DrawLinesX1; + float DrawLinesToNodesY2; + ImGuiTableColumnIdx DrawLinesTableColumn; +}; + +// sizeof() = 20 +struct IMGUI_API ImGuiErrorRecoveryState +{ + short SizeOfWindowStack; + short SizeOfIDStack; + short SizeOfTreeStack; + short SizeOfColorStack; + short SizeOfStyleVarStack; + short SizeOfFontStack; + short SizeOfFocusScopeStack; + short SizeOfGroupStack; + short SizeOfItemFlagsStack; + short SizeOfBeginPopupStack; + short SizeOfDisabledStack; + + ImGuiErrorRecoveryState() { memset(this, 0, sizeof(*this)); } +}; + +// Data saved for each window pushed into the stack +struct ImGuiWindowStackData +{ + ImGuiWindow* Window; + ImGuiLastItemData ParentLastItemDataBackup; + ImGuiErrorRecoveryState StackSizesInBegin; // Store size of various stacks for asserting + bool DisabledOverrideReenable; // Non-child window override disabled flag + float DisabledOverrideReenableAlphaBackup; +}; + +struct ImGuiShrinkWidthItem +{ + int Index; + float Width; + float InitialWidth; +}; + +struct ImGuiPtrOrIndex +{ + void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. + int Index; // Usually index in a main pool. + + ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } + ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } +}; + +// Data used by IsItemDeactivated()/IsItemDeactivatedAfterEdit() functions +struct ImGuiDeactivatedItemData +{ + ImGuiID ID; + int ElapseFrame; + bool HasBeenEditedBefore; + bool IsAlive; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Popup support +//----------------------------------------------------------------------------- + +enum ImGuiPopupPositionPolicy +{ + ImGuiPopupPositionPolicy_Default, + ImGuiPopupPositionPolicy_ComboBox, + ImGuiPopupPositionPolicy_Tooltip, +}; + +// Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) +struct ImGuiPopupData +{ + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* RestoreNavWindow;// Set on OpenPopup(), a NavWindow that will be restored on popup close + int ParentNavLayer; // Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value + int OpenFrameCount; // Set on OpenPopup() + ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup + + ImGuiPopupData() { memset(this, 0, sizeof(*this)); ParentNavLayer = OpenFrameCount = -1; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Inputs support +//----------------------------------------------------------------------------- + +// Bit array for named keys +typedef ImBitArray ImBitArrayForNamedKeys; + +// [Internal] Key ranges +#define ImGuiKey_LegacyNativeKey_BEGIN 0 +#define ImGuiKey_LegacyNativeKey_END 512 +#define ImGuiKey_Keyboard_BEGIN (ImGuiKey_NamedKey_BEGIN) +#define ImGuiKey_Keyboard_END (ImGuiKey_GamepadStart) +#define ImGuiKey_Gamepad_BEGIN (ImGuiKey_GamepadStart) +#define ImGuiKey_Gamepad_END (ImGuiKey_GamepadRStickDown + 1) +#define ImGuiKey_Mouse_BEGIN (ImGuiKey_MouseLeft) +#define ImGuiKey_Mouse_END (ImGuiKey_MouseWheelY + 1) +#define ImGuiKey_Aliases_BEGIN (ImGuiKey_Mouse_BEGIN) +#define ImGuiKey_Aliases_END (ImGuiKey_Mouse_END) + +// [Internal] Named shortcuts for Navigation +#define ImGuiKey_NavKeyboardTweakSlow ImGuiMod_Ctrl +#define ImGuiKey_NavKeyboardTweakFast ImGuiMod_Shift +#define ImGuiKey_NavGamepadTweakSlow ImGuiKey_GamepadL1 +#define ImGuiKey_NavGamepadTweakFast ImGuiKey_GamepadR1 +#define ImGuiKey_NavGamepadActivate (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceRight : ImGuiKey_GamepadFaceDown) +#define ImGuiKey_NavGamepadCancel (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceDown : ImGuiKey_GamepadFaceRight) +#define ImGuiKey_NavGamepadMenu ImGuiKey_GamepadFaceLeft +#define ImGuiKey_NavGamepadInput ImGuiKey_GamepadFaceUp + +enum ImGuiInputEventType +{ + ImGuiInputEventType_None = 0, + ImGuiInputEventType_MousePos, + ImGuiInputEventType_MouseWheel, + ImGuiInputEventType_MouseButton, + ImGuiInputEventType_MouseViewport, + ImGuiInputEventType_Key, + ImGuiInputEventType_Text, + ImGuiInputEventType_Focus, + ImGuiInputEventType_COUNT +}; + +enum ImGuiInputSource : int +{ + ImGuiInputSource_None = 0, + ImGuiInputSource_Mouse, // Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. + ImGuiInputSource_Keyboard, + ImGuiInputSource_Gamepad, + ImGuiInputSource_COUNT +}; + +// FIXME: Structures in the union below need to be declared as anonymous unions appears to be an extension? +// Using ImVec2() would fail on Clang 'union member 'MousePos' has a non-trivial default constructor' +struct ImGuiInputEventMousePos { float PosX, PosY; ImGuiMouseSource MouseSource; }; +struct ImGuiInputEventMouseWheel { float WheelX, WheelY; ImGuiMouseSource MouseSource; }; +struct ImGuiInputEventMouseButton { int Button; bool Down; ImGuiMouseSource MouseSource; }; +struct ImGuiInputEventMouseViewport { ImGuiID HoveredViewportID; }; +struct ImGuiInputEventKey { ImGuiKey Key; bool Down; float AnalogValue; }; +struct ImGuiInputEventText { unsigned int Char; }; +struct ImGuiInputEventAppFocused { bool Focused; }; + +struct ImGuiInputEvent +{ + ImGuiInputEventType Type; + ImGuiInputSource Source; + ImU32 EventId; // Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). + union + { + ImGuiInputEventMousePos MousePos; // if Type == ImGuiInputEventType_MousePos + ImGuiInputEventMouseWheel MouseWheel; // if Type == ImGuiInputEventType_MouseWheel + ImGuiInputEventMouseButton MouseButton; // if Type == ImGuiInputEventType_MouseButton + ImGuiInputEventMouseViewport MouseViewport; // if Type == ImGuiInputEventType_MouseViewport + ImGuiInputEventKey Key; // if Type == ImGuiInputEventType_Key + ImGuiInputEventText Text; // if Type == ImGuiInputEventType_Text + ImGuiInputEventAppFocused AppFocused; // if Type == ImGuiInputEventType_Focus + }; + bool AddedByTestEngine; + + ImGuiInputEvent() { memset(this, 0, sizeof(*this)); } +}; + +// Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. +#define ImGuiKeyOwner_Any ((ImGuiID)0) // Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. +#define ImGuiKeyOwner_NoOwner ((ImGuiID)-1) // Require key to have no owner. +//#define ImGuiKeyOwner_None ImGuiKeyOwner_NoOwner // We previously called this 'ImGuiKeyOwner_None' but it was inconsistent with our pattern that _None values == 0 and quite dangerous. Also using _NoOwner makes the IsKeyPressed() calls more explicit. + +typedef ImS16 ImGuiKeyRoutingIndex; + +// Routing table entry (sizeof() == 16 bytes) +struct ImGuiKeyRoutingData +{ + ImGuiKeyRoutingIndex NextEntryIndex; + ImU16 Mods; // Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. + ImU16 RoutingCurrScore; // [DEBUG] For debug display + ImU16 RoutingNextScore; // Lower is better (0: perfect score) + ImGuiID RoutingCurr; + ImGuiID RoutingNext; + + ImGuiKeyRoutingData() { NextEntryIndex = -1; Mods = 0; RoutingCurrScore = RoutingNextScore = 0; RoutingCurr = RoutingNext = ImGuiKeyOwner_NoOwner; } +}; + +// Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. +// Stored in main context (1 instance) +struct ImGuiKeyRoutingTable +{ + ImGuiKeyRoutingIndex Index[ImGuiKey_NamedKey_COUNT]; // Index of first entry in Entries[] + ImVector Entries; + ImVector EntriesNext; // Double-buffer to avoid reallocation (could use a shared buffer) + + ImGuiKeyRoutingTable() { Clear(); } + void Clear() { for (int n = 0; n < IM_COUNTOF(Index); n++) Index[n] = -1; Entries.clear(); EntriesNext.clear(); } +}; + +// This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) +// Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. +struct ImGuiKeyOwnerData +{ + ImGuiID OwnerCurr; + ImGuiID OwnerNext; + bool LockThisFrame; // Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags_LockThisFrame. + bool LockUntilRelease; // Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags_LockUntilRelease. When this is true LockThisFrame is always true as well. + + ImGuiKeyOwnerData() { OwnerCurr = OwnerNext = ImGuiKeyOwner_NoOwner; LockThisFrame = LockUntilRelease = false; } +}; + +// Extend ImGuiInputFlags_ +// Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() +// Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) +enum ImGuiInputFlagsPrivate_ +{ + // Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() + // - Repeat mode: Repeat rate selection + ImGuiInputFlags_RepeatRateDefault = 1 << 1, // Repeat rate: Regular (default) + ImGuiInputFlags_RepeatRateNavMove = 1 << 2, // Repeat rate: Fast + ImGuiInputFlags_RepeatRateNavTweak = 1 << 3, // Repeat rate: Faster + // - Repeat mode: Specify when repeating key pressed can be interrupted. + // - In theory ImGuiInputFlags_RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. + ImGuiInputFlags_RepeatUntilRelease = 1 << 4, // Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. + ImGuiInputFlags_RepeatUntilKeyModsChange = 1 << 5, // Stop repeating when released OR if keyboard mods are changed (default for Shortcut) + ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone = 1 << 6, // Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. + ImGuiInputFlags_RepeatUntilOtherKeyPress = 1 << 7, // Stop repeating when released OR if any other keyboard key is pressed during the repeat + + // Flags for SetKeyOwner(), SetItemKeyOwner() + // - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. + ImGuiInputFlags_LockThisFrame = 1 << 20, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. + ImGuiInputFlags_LockUntilRelease = 1 << 21, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. + + // - Condition for SetItemKeyOwner() + ImGuiInputFlags_CondHovered = 1 << 22, // Only set if item is hovered (default to both) + ImGuiInputFlags_CondActive = 1 << 23, // Only set if item is active (default to both) + ImGuiInputFlags_CondDefault_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, + + // [Internal] Mask of which function support which flags + ImGuiInputFlags_RepeatRateMask_ = ImGuiInputFlags_RepeatRateDefault | ImGuiInputFlags_RepeatRateNavMove | ImGuiInputFlags_RepeatRateNavTweak, + ImGuiInputFlags_RepeatUntilMask_ = ImGuiInputFlags_RepeatUntilRelease | ImGuiInputFlags_RepeatUntilKeyModsChange | ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone | ImGuiInputFlags_RepeatUntilOtherKeyPress, + ImGuiInputFlags_RepeatMask_ = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_, + ImGuiInputFlags_CondMask_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, + ImGuiInputFlags_RouteTypeMask_ = ImGuiInputFlags_RouteActive | ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteAlways, + ImGuiInputFlags_RouteOptionsMask_ = ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused | ImGuiInputFlags_RouteFromRootWindow, + ImGuiInputFlags_SupportedByIsKeyPressed = ImGuiInputFlags_RepeatMask_, + ImGuiInputFlags_SupportedByIsMouseClicked = ImGuiInputFlags_Repeat, + ImGuiInputFlags_SupportedByShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_, + ImGuiInputFlags_SupportedBySetNextItemShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_ | ImGuiInputFlags_Tooltip, + ImGuiInputFlags_SupportedBySetKeyOwner = ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease, + ImGuiInputFlags_SupportedBySetItemKeyOwner = ImGuiInputFlags_SupportedBySetKeyOwner | ImGuiInputFlags_CondMask_, +}; + +//----------------------------------------------------------------------------- +// [SECTION] Clipper support +//----------------------------------------------------------------------------- + +// Note that Max is exclusive, so perhaps should be using a Begin/End convention. +struct ImGuiListClipperRange +{ + int Min; + int Max; + bool PosToIndexConvert; // Begin/End are absolute position (will be converted to indices later) + ImS8 PosToIndexOffsetMin; // Add to Min after converting to indices + ImS8 PosToIndexOffsetMax; // Add to Min after converting to indices + + static ImGuiListClipperRange FromIndices(int min, int max) { ImGuiListClipperRange r = { min, max, false, 0, 0 }; return r; } + static ImGuiListClipperRange FromPositions(float y1, float y2, int off_min, int off_max) { ImGuiListClipperRange r = { (int)y1, (int)y2, true, (ImS8)off_min, (ImS8)off_max }; return r; } +}; + +// Temporary clipper data, buffers shared/reused between instances +struct ImGuiListClipperData +{ + ImGuiListClipper* ListClipper; + float LossynessOffset; + int StepNo; + int ItemsFrozen; + ImVector Ranges; + + ImGuiListClipperData() { memset(this, 0, sizeof(*this)); } + void Reset(ImGuiListClipper* clipper) { ListClipper = clipper; StepNo = ItemsFrozen = 0; Ranges.resize(0); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Navigation support +//----------------------------------------------------------------------------- + +enum ImGuiActivateFlags_ +{ + ImGuiActivateFlags_None = 0, + ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. + ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used. + ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) + ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request (ImGuiNavMoveFlags_IsTabbing) + ImGuiActivateFlags_FromShortcut = 1 << 4, // Activation requested by an item shortcut via SetNextItemShortcut() function. + ImGuiActivateFlags_FromFocusApi = 1 << 5, // Activation requested by an api request (ImGuiNavMoveFlags_FocusApi) +}; + +// Early work-in-progress API for ScrollToItem() +enum ImGuiScrollFlags_ +{ + ImGuiScrollFlags_None = 0, + ImGuiScrollFlags_KeepVisibleEdgeX = 1 << 0, // If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] + ImGuiScrollFlags_KeepVisibleEdgeY = 1 << 1, // If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] + ImGuiScrollFlags_KeepVisibleCenterX = 1 << 2, // If item is not visible: scroll to make the item centered on X axis [rarely used] + ImGuiScrollFlags_KeepVisibleCenterY = 1 << 3, // If item is not visible: scroll to make the item centered on Y axis + ImGuiScrollFlags_AlwaysCenterX = 1 << 4, // Always center the result item on X axis [rarely used] + ImGuiScrollFlags_AlwaysCenterY = 1 << 5, // Always center the result item on Y axis [default for Y axis for appearing window) + ImGuiScrollFlags_NoScrollParent = 1 << 6, // Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). + ImGuiScrollFlags_MaskX_ = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX, + ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY, +}; + +enum ImGuiNavRenderCursorFlags_ +{ + ImGuiNavRenderCursorFlags_None = 0, + ImGuiNavRenderCursorFlags_Compact = 1 << 1, // Compact highlight, no padding/distance from focused item + ImGuiNavRenderCursorFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse. + ImGuiNavRenderCursorFlags_NoRounding = 1 << 3, +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiNavHighlightFlags_None = ImGuiNavRenderCursorFlags_None, // Renamed in 1.91.4 + ImGuiNavHighlightFlags_Compact = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.91.4 + ImGuiNavHighlightFlags_AlwaysDraw = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4 + ImGuiNavHighlightFlags_NoRounding = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4 + //ImGuiNavHighlightFlags_TypeThin = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.90.2 +#endif +}; + +enum ImGuiNavMoveFlags_ +{ + ImGuiNavMoveFlags_None = 0, + ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side + ImGuiNavMoveFlags_LoopY = 1 << 1, + ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful but provided for completeness + ImGuiNavMoveFlags_WrapMask_ = ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_WrapY, + ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) + ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword as ImGuiScrollFlags + ImGuiNavMoveFlags_Forwarded = 1 << 7, + ImGuiNavMoveFlags_DebugNoResult = 1 << 8, // Dummy scoring for debug purpose, don't apply result + ImGuiNavMoveFlags_FocusApi = 1 << 9, // Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) + ImGuiNavMoveFlags_IsTabbing = 1 << 10, // == Focus + Activate if item is Inputable + DontChangeNavHighlight + ImGuiNavMoveFlags_IsPageMove = 1 << 11, // Identify a PageDown/PageUp request. + ImGuiNavMoveFlags_Activate = 1 << 12, // Activate/select target item. + ImGuiNavMoveFlags_NoSelect = 1 << 13, // Don't trigger selection by not setting g.NavJustMovedTo + ImGuiNavMoveFlags_NoSetNavCursorVisible = 1 << 14, // Do not alter the nav cursor visible state + ImGuiNavMoveFlags_NoClearActiveId = 1 << 15, // (Experimental) Do not clear active id when applying move result +}; + +enum ImGuiNavLayer +{ + ImGuiNavLayer_Main = 0, // Main scrolling layer + ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt) + ImGuiNavLayer_COUNT +}; + +// Storage for navigation query/results +struct ImGuiNavItemData +{ + ImGuiWindow* Window; // Init,Move // Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) + ImGuiID ID; // Init,Move // Best candidate item ID + ImGuiID FocusScopeId; // Init,Move // Best candidate focus scope ID + ImRect RectRel; // Init,Move // Best candidate bounding box in window relative space + ImGuiItemFlags ItemFlags; // ????,Move // Best candidate item flags + float DistBox; // Move // Best candidate box distance to current NavId + float DistCenter; // Move // Best candidate center distance to current NavId + float DistAxial; // Move // Best candidate axial distance to current NavId + ImGuiSelectionUserData SelectionUserData;//I+Mov // Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags_HasSelectionUserData) + + ImGuiNavItemData() { Clear(); } + void Clear() { Window = NULL; ID = FocusScopeId = 0; ItemFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; } +}; + +// Storage for PushFocusScope(), g.FocusScopeStack[], g.NavFocusRoute[] +struct ImGuiFocusScopeData +{ + ImGuiID ID; + ImGuiID WindowID; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Typing-select support +//----------------------------------------------------------------------------- + +// Flags for GetTypingSelectRequest() +enum ImGuiTypingSelectFlags_ +{ + ImGuiTypingSelectFlags_None = 0, + ImGuiTypingSelectFlags_AllowBackspace = 1 << 0, // Backspace to delete character inputs. If using: ensure GetTypingSelectRequest() is not called more than once per frame (filter by e.g. focus state) + ImGuiTypingSelectFlags_AllowSingleCharMode = 1 << 1, // Allow "single char" search mode which is activated when pressing the same character multiple times. +}; + +// Returned by GetTypingSelectRequest(), designed to eventually be public. +struct IMGUI_API ImGuiTypingSelectRequest +{ + ImGuiTypingSelectFlags Flags; // Flags passed to GetTypingSelectRequest() + int SearchBufferLen; + const char* SearchBuffer; // Search buffer contents (use full string. unless SingleCharMode is set, in which case use SingleCharSize). + bool SelectRequest; // Set when buffer was modified this frame, requesting a selection. + bool SingleCharMode; // Notify when buffer contains same character repeated, to implement special mode. In this situation it preferred to not display any on-screen search indication. + ImS8 SingleCharSize; // Length in bytes of first letter codepoint (1 for ascii, 2-4 for UTF-8). If (SearchBufferLen==RepeatCharSize) only 1 letter has been input. +}; + +// Storage for GetTypingSelectRequest() +struct IMGUI_API ImGuiTypingSelectState +{ + ImGuiTypingSelectRequest Request; // User-facing data + char SearchBuffer[64]; // Search buffer: no need to make dynamic as this search is very transient. + ImGuiID FocusScope; + int LastRequestFrame = 0; + float LastRequestTime = 0.0f; + bool SingleCharModeLock = false; // After a certain single char repeat count we lock into SingleCharMode. Two benefits: 1) buffer never fill, 2) we can provide an immediate SingleChar mode without timer elapsing. + + ImGuiTypingSelectState() { memset(this, 0, sizeof(*this)); } + void Clear() { SearchBuffer[0] = 0; SingleCharModeLock = false; } // We preserve remaining data for easier debugging +}; + +//----------------------------------------------------------------------------- +// [SECTION] Columns support +//----------------------------------------------------------------------------- + +// Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! +enum ImGuiOldColumnFlags_ +{ + ImGuiOldColumnFlags_None = 0, + ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, // Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, + //ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, + //ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, + //ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, + //ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, + //ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize, +#endif +}; + +struct ImGuiOldColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + float OffsetNormBeforeResize; + ImGuiOldColumnFlags Flags; // Not exposed + ImRect ClipRect; + + ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } +}; + +struct ImGuiOldColumns +{ + ImGuiID ID; + ImGuiOldColumnFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x + float LineMinY, LineMaxY; + float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() + float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() + ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() + ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() + ImVector Columns; + ImDrawListSplitter Splitter; + + ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Box-select support +//----------------------------------------------------------------------------- + +struct ImGuiBoxSelectState +{ + // Active box-selection data (persistent, 1 active at a time) + ImGuiID ID; + bool IsActive; + bool IsStarting; + bool IsStartedFromVoid; // Starting click was not from an item. + bool IsStartedSetNavIdOnce; + bool RequestClear; + ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. + ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) + ImVec2 EndPosRel; // End position in window-contents relative space + ImVec2 ScrollAccum; // Scrolling accumulator (to behave at high-frame spaces) + ImGuiWindow* Window; + + // Temporary/Transient data + bool UnclipMode; // (Temp/Transient, here in hot area). Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. + ImRect UnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. + ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) + ImRect BoxSelectRectCurr; + + ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Multi-select support +//----------------------------------------------------------------------------- + +// We always assume that -1 is an invalid value (which works for indices and pointers) +#define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) + +// Temporary storage for multi-select +struct IMGUI_API ImGuiMultiSelectTempData +{ + ImGuiMultiSelectIO IO; // MUST BE FIRST FIELD. Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. + ImGuiMultiSelectState* Storage; + ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) + ImGuiMultiSelectFlags Flags; + ImVec2 ScopeRectMin; + ImVec2 BackupCursorMaxPos; + ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. + ImGuiID BoxSelectId; + ImGuiKeyChord KeyMods; + ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. + bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. + bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. + bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool NavIdPassedBy; + bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. + bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. + + ImGuiMultiSelectTempData() { Clear(); } + void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. + void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = ImGuiSelectionUserData_Invalid; IO.NavIdSelected = IO.RangeSrcReset = false; } +}; + +// Persistent storage for multi-select (as long as selection is alive) +struct IMGUI_API ImGuiMultiSelectState +{ + ImGuiWindow* Window; + ImGuiID ID; + int LastFrameActive; // Last used frame-count, for GC. + int LastSelectionSize; // Set by BeginMultiSelect() based on optional info provided by user. May be -1 if unknown. + ImS8 RangeSelected; // -1 (don't have) or true/false + ImS8 NavIdSelected; // -1 (don't have) or true/false + ImGuiSelectionUserData RangeSrcItem; // + ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) + + ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = LastSelectionSize = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Docking support +//----------------------------------------------------------------------------- + +#define DOCKING_HOST_DRAW_CHANNEL_BG 0 // Dock host: background fill +#define DOCKING_HOST_DRAW_CHANNEL_FG 1 // Dock host: decorations and contents + +#ifdef IMGUI_HAS_DOCK + +// Extend ImGuiDockNodeFlags_ +enum ImGuiDockNodeFlagsPrivate_ +{ + // [Internal] + ImGuiDockNodeFlags_DockSpace = 1 << 10, // Saved // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + ImGuiDockNodeFlags_CentralNode = 1 << 11, // Saved // The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. + ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Saved // Tab bar is completely unavailable. No triangle in the corner to enable it back. + ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Saved // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Saved // Disable window/docking menu (that one that appears instead of the collapse button) + ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Saved // Disable close button + ImGuiDockNodeFlags_NoResizeX = 1 << 16, // // + ImGuiDockNodeFlags_NoResizeY = 1 << 17, // // + ImGuiDockNodeFlags_DockedWindowsInFocusRoute= 1 << 18, // // Any docked window will be automatically be focus-route chained (window->ParentWindowForFocusRoute set to this) so Shortcut() in this window can run when any docked window is focused. + + // Disable docking/undocking actions in this dockspace or individual node (existing docked nodes will be preserved) + // Those are not exposed in public because the desirable sharing/inheriting/copy-flag-on-split behaviors are quite difficult to design and understand. + // The two public flags ImGuiDockNodeFlags_NoDockingOverCentralNode/ImGuiDockNodeFlags_NoDockingSplit don't have those issues. + ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 19, // // Disable this node from splitting other windows/nodes. + ImGuiDockNodeFlags_NoDockingOverMe = 1 << 20, // // Disable other windows/nodes from being docked over this node. + ImGuiDockNodeFlags_NoDockingOverOther = 1 << 21, // // Disable this node from being docked over another window or non-empty node. + ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 22, // // Disable this node from being docked over an empty node (e.g. DockSpace with no other windows) + ImGuiDockNodeFlags_NoDocking = ImGuiDockNodeFlags_NoDockingOverMe | ImGuiDockNodeFlags_NoDockingOverOther | ImGuiDockNodeFlags_NoDockingOverEmpty | ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoDockingSplitOther, + + // Masks + ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = (int)ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + + // When splitting, those local flags are moved to the inheriting child, never duplicated + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = (int)ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | (int)ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, +}; + +// Store the source authority (dock node vs window) of a field +enum ImGuiDataAuthority_ +{ + ImGuiDataAuthority_Auto, + ImGuiDataAuthority_DockNode, + ImGuiDataAuthority_Window, +}; + +enum ImGuiDockNodeState +{ + ImGuiDockNodeState_Unknown, + ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow, + ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing, + ImGuiDockNodeState_HostWindowVisible, +}; + +// sizeof() 156~192 +struct IMGUI_API ImGuiDockNode +{ + ImGuiID ID; + ImGuiDockNodeFlags SharedFlags; // (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + ImGuiDockNodeFlags LocalFlags; // (Write) Flags specific to this node + ImGuiDockNodeFlags LocalFlagsInWindows; // (Write) Flags specific to this node, applied from windows + ImGuiDockNodeFlags MergedFlags; // (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) + ImGuiDockNodeState State; + ImGuiDockNode* ParentNode; + ImGuiDockNode* ChildNodes[2]; // [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. + ImVector Windows; // Note: unordered list! Iterate TabBar->Tabs for user-order. + ImGuiTabBar* TabBar; + ImVec2 Pos; // Current position + ImVec2 Size; // Current size + ImVec2 SizeRef; // [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. + ImGuiAxis SplitAxis; // [Split node only] Split axis (X or Y) + ImGuiWindowClass WindowClass; // [Root node only] + ImU32 LastBgColor; + + ImGuiWindow* HostWindow; + ImGuiWindow* VisibleWindow; // Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. + ImGuiDockNode* CentralNode; // [Root node only] Pointer to central node. + ImGuiDockNode* OnlyNodeWithWindows; // [Root node only] Set when there is a single visible node within the hierarchy. + int CountNodeWithWindows; // [Root node only] + int LastFrameAlive; // Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags_KeepAliveOnly + int LastFrameActive; // Last frame number the node was updated. + int LastFrameFocused; // Last frame number the node was focused. + ImGuiID LastFocusedNodeId; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. + ImGuiID SelectedTabId; // [Leaf node only] Which of our tab/window is selected. + ImGuiID WantCloseTabId; // [Leaf node only] Set when closing a specific tab/window. + ImGuiID RefViewportId; // Reference viewport ID from visible window when HostWindow == NULL. + ImGuiDataAuthority AuthorityForPos :3; + ImGuiDataAuthority AuthorityForSize :3; + ImGuiDataAuthority AuthorityForViewport :3; + bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window) + bool IsFocused :1; + bool IsBgDrawnThisFrame :1; + bool HasCloseButton :1; // Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. + bool HasWindowMenuButton :1; + bool HasCentralNodeChild :1; + bool WantCloseAll :1; // Set when closing all tabs at once. + bool WantLockSizeOnce :1; + bool WantMouseMove :1; // After a node extraction we need to transition toward moving the newly created host window + bool WantHiddenTabBarUpdate :1; + bool WantHiddenTabBarToggle :1; + + ImGuiDockNode(ImGuiID id); + ~ImGuiDockNode(); + bool IsRootNode() const { return ParentNode == NULL; } + bool IsDockSpace() const { return (MergedFlags & ImGuiDockNodeFlags_DockSpace) != 0; } + bool IsFloatingNode() const { return ParentNode == NULL && (MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0; } + bool IsCentralNode() const { return (MergedFlags & ImGuiDockNodeFlags_CentralNode) != 0; } + bool IsHiddenTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle + bool IsNoTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar + bool IsSplitNode() const { return ChildNodes[0] != NULL; } + bool IsLeafNode() const { return ChildNodes[0] == NULL; } + bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + + void SetLocalFlags(ImGuiDockNodeFlags flags) { LocalFlags = flags; UpdateMergedFlags(); } + void UpdateMergedFlags() { MergedFlags = SharedFlags | LocalFlags | LocalFlagsInWindows; } +}; + +// List of colors that are stored at the time of Begin() into Docked Windows. +// We currently store the packed colors in a simple array window->DockStyle.Colors[]. +// A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, +// but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. +enum ImGuiWindowDockStyleCol +{ + ImGuiWindowDockStyleCol_Text, + ImGuiWindowDockStyleCol_TabHovered, + ImGuiWindowDockStyleCol_TabFocused, + ImGuiWindowDockStyleCol_TabSelected, + ImGuiWindowDockStyleCol_TabSelectedOverline, + ImGuiWindowDockStyleCol_TabDimmed, + ImGuiWindowDockStyleCol_TabDimmedSelected, + ImGuiWindowDockStyleCol_TabDimmedSelectedOverline, + ImGuiWindowDockStyleCol_UnsavedMarker, + ImGuiWindowDockStyleCol_COUNT +}; + +// We don't store style.Alpha: dock_node->LastBgColor embeds it and otherwise it would only affect the docking tab, which intuitively I would say we don't want to. +struct ImGuiWindowDockStyle +{ + ImU32 Colors[ImGuiWindowDockStyleCol_COUNT]; +}; + +struct ImGuiDockContext +{ + ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes + ImVector Requests; + ImVector NodesSettings; + bool WantFullRebuild; + ImGuiDockContext() { memset(this, 0, sizeof(*this)); } +}; + +#endif // #ifdef IMGUI_HAS_DOCK + +//----------------------------------------------------------------------------- +// [SECTION] Viewport support +//----------------------------------------------------------------------------- + +// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) +// Every instance of ImGuiViewport is in fact a ImGuiViewportP. +struct ImGuiViewportP : public ImGuiViewport +{ + ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set) + int Idx; + int LastFrameActive; // Last frame number this viewport was activated by a window + int LastFocusedStampCount; // Last stamp number from when a window hosted by this viewport was focused (by comparing this value between two viewport we have an implicit viewport z-order we use as fallback) + ImGuiID LastNameHash; + ImVec2 LastPos; + ImVec2 LastSize; + float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent) + float LastAlpha; + bool LastFocusedHadNavWindow;// Instead of maintaining a LastFocusedWindow (which may harder to correctly maintain), we merely store weither NavWindow != NULL last time the viewport was focused. + short PlatformMonitor; + int BgFgDrawListsLastFrame[2]; // Last frame number the background (0) and foreground (1) draw lists were used + ImDrawList* BgFgDrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. + ImDrawData DrawDataP; + ImDrawDataBuilder DrawDataBuilder; // Temporary data while building final ImDrawData + ImVec2 LastPlatformPos; + ImVec2 LastPlatformSize; + ImVec2 LastRendererSize; + + // Per-viewport work area + // - Insets are >= 0.0f values, distance from viewport corners to work area. + // - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. + // - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + ImVec2 WorkInsetMin; // Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). + ImVec2 WorkInsetMax; // " + ImVec2 BuildWorkInsetMin; // Work Area inset accumulator for current frame, to become next frame's WorkInset + ImVec2 BuildWorkInsetMax; // " + + ImGuiViewportP() { Window = NULL; Idx = -1; LastFrameActive = BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = LastFocusedStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; LastFocusedHadNavWindow = false; PlatformMonitor = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); } + ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } + void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; } + + // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) + ImVec2 CalcWorkRectPos(const ImVec2& inset_min) const { return ImVec2(Pos.x + inset_min.x, Pos.y + inset_min.y); } + ImVec2 CalcWorkRectSize(const ImVec2& inset_min, const ImVec2& inset_max) const { return ImVec2(ImMax(0.0f, Size.x - inset_min.x - inset_max.x), ImMax(0.0f, Size.y - inset_min.y - inset_max.y)); } + void UpdateWorkRect() { WorkPos = CalcWorkRectPos(WorkInsetMin); WorkSize = CalcWorkRectSize(WorkInsetMin, WorkInsetMax); } // Update public fields + + // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) + ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + ImRect GetWorkRect() const { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); } + ImRect GetBuildWorkRect() const { ImVec2 pos = CalcWorkRectPos(BuildWorkInsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkInsetMin, BuildWorkInsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Settings support +//----------------------------------------------------------------------------- + +// Windows data saved in imgui.ini file +// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. +// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) +struct ImGuiWindowSettings +{ + ImGuiID ID; + ImVec2ih Pos; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. + ImVec2ih Size; + ImVec2ih ViewportPos; + ImGuiID ViewportId; + ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. + ImGuiID ClassId; // ID of window class if specified + short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + bool Collapsed; + bool IsChild; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + bool WantDelete; // Set to invalidate/delete the settings entry + + ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); DockOrder = -1; } + char* GetName() { return (char*)(this + 1); } +}; + +struct ImGuiSettingsHandler +{ + const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) + void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" + void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' + void* UserData; + + ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Localization support +//----------------------------------------------------------------------------- + +// This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. +enum ImGuiLocKey : int +{ + ImGuiLocKey_VersionStr, + ImGuiLocKey_TableSizeOne, + ImGuiLocKey_TableSizeAllFit, + ImGuiLocKey_TableSizeAllDefault, + ImGuiLocKey_TableResetOrder, + ImGuiLocKey_WindowingMainMenuBar, + ImGuiLocKey_WindowingPopup, + ImGuiLocKey_WindowingUntitled, + ImGuiLocKey_OpenLink_s, + ImGuiLocKey_CopyLink, + ImGuiLocKey_DockingHideTabBar, + ImGuiLocKey_DockingHoldShiftToDock, + ImGuiLocKey_DockingDragToUndockOrMoveNode, + ImGuiLocKey_COUNT +}; + +struct ImGuiLocEntry +{ + ImGuiLocKey Key; + const char* Text; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Error handling, State recovery support +//----------------------------------------------------------------------------- + +// Macros used by Recoverable Error handling +// - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro). +// - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. +// - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. +// - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. +#ifndef IM_ASSERT_USER_ERROR +#define IM_ASSERT_USER_ERROR(_EXPR,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } } while (0) // Recoverable User Error +#define IM_ASSERT_USER_ERROR_RET(_EXPR,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } return; } } while (0) // Recoverable User Error +#define IM_ASSERT_USER_ERROR_RETV(_EXPR,_RETV,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } return _RETV; } } while (0) // Recoverable User Error +#endif + +// The error callback is currently not public, as it is expected that only advanced users will rely on it. +typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); // Function signature for g.ErrorCallback + +//----------------------------------------------------------------------------- +// [SECTION] Metrics, Debug Tools +//----------------------------------------------------------------------------- + +// See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros. +enum ImGuiDebugLogFlags_ +{ + // Event types + ImGuiDebugLogFlags_None = 0, + ImGuiDebugLogFlags_EventError = 1 << 0, // Error submitted by IM_ASSERT_USER_ERROR() + ImGuiDebugLogFlags_EventActiveId = 1 << 1, + ImGuiDebugLogFlags_EventFocus = 1 << 2, + ImGuiDebugLogFlags_EventPopup = 1 << 3, + ImGuiDebugLogFlags_EventNav = 1 << 4, + ImGuiDebugLogFlags_EventClipper = 1 << 5, + ImGuiDebugLogFlags_EventSelection = 1 << 6, + ImGuiDebugLogFlags_EventIO = 1 << 7, + ImGuiDebugLogFlags_EventFont = 1 << 8, + ImGuiDebugLogFlags_EventInputRouting = 1 << 9, + ImGuiDebugLogFlags_EventDocking = 1 << 10, + ImGuiDebugLogFlags_EventViewport = 1 << 11, + + ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, + ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY + ImGuiDebugLogFlags_OutputToDebugger = 1 << 21, // Also send output to Debugger Console [Windows only] + ImGuiDebugLogFlags_OutputToTestEngine = 1 << 22, // Also send output to Dear ImGui Test Engine +}; + +struct ImGuiDebugAllocEntry +{ + int FrameCount; + ImS16 AllocCount; + ImS16 FreeCount; +}; + +struct ImGuiDebugAllocInfo +{ + int TotalAllocCount; // Number of call to MemAlloc(). + int TotalFreeCount; + ImS16 LastEntriesIdx; // Current index in buffer + ImGuiDebugAllocEntry LastEntriesBuf[6]; // Track last 6 frames that had allocations + + ImGuiDebugAllocInfo() { memset(this, 0, sizeof(*this)); } +}; + +struct ImGuiMetricsConfig +{ + bool ShowDebugLog = false; + bool ShowIDStackTool = false; + bool ShowWindowsRects = false; + bool ShowWindowsBeginOrder = false; + bool ShowTablesRects = false; + bool ShowDrawCmdMesh = true; + bool ShowDrawCmdBoundingBoxes = true; + bool ShowTextEncodingViewer = false; + bool ShowTextureUsedRect = false; + bool ShowDockingNodes = false; + int ShowWindowsRectsType = -1; + int ShowTablesRectsType = -1; + int HighlightMonitorIdx = -1; + ImGuiID HighlightViewportID = 0; + bool ShowFontPreview = true; +}; + +struct ImGuiStackLevelInfo +{ + ImGuiID ID; + ImS8 QueryFrameCount; // >= 1: Sub-query in progress + bool QuerySuccess; // Sub-query obtained result from DebugHookIdInfo() + ImS8 DataType; // ImGuiDataType + int DescOffset; // -1 or offset into parent's ResultsPathsBuf + + ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DataType = -1; DescOffset = -1; } +}; + +struct ImGuiDebugItemPathQuery +{ + ImGuiID MainID; // ID to query details for. + bool Active; // Used to disambiguate the case when ID == 0 and e.g. some code calls PushOverrideID(0). + bool Complete; // All sub-queries are finished (some may have failed). + ImS8 Step; // -1: query stack + init Results, >= 0: filling individual stack level. + ImVector Results; + ImGuiTextBuffer ResultsDescBuf; + ImGuiTextBuffer ResultPathBuf; + + ImGuiDebugItemPathQuery() { memset(this, 0, sizeof(*this)); } +}; + +// State for ID Stack tool queries +struct ImGuiIDStackTool +{ + bool OptHexEncodeNonAsciiChars; + bool OptCopyToClipboardOnCtrlC; + int LastActiveFrame; + float CopyToClipboardLastTime; + + ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Generic context hooks +//----------------------------------------------------------------------------- + +typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); +enum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ }; + +struct ImGuiContextHook +{ + ImGuiID HookId; // A unique ID assigned by AddContextHook() + ImGuiContextHookType Type; + ImGuiID Owner; + ImGuiContextHookCallback Callback; + void* UserData; + + ImGuiContextHook() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiContext (main Dear ImGui context) +//----------------------------------------------------------------------------- + +struct ImGuiContext +{ + bool Initialized; + bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() + bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed + bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() + int FrameCount; + int FrameCountEnded; + int FrameCountPlatformEnded; + int FrameCountRendered; + double Time; + char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) + ImGuiIO IO; + ImGuiPlatformIO PlatformIO; + ImGuiStyle Style; + ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame() + ImGuiConfigFlags ConfigFlagsLastFrame; + ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) + ImFont* Font; // Currently bound font. (== FontStack.back().Font) + ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) + float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. + float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. + float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). + float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale + ImDrawListSharedData DrawListSharedData; + ImGuiID WithinEndChildID; // Set within EndChild() + void* TestEngine; // Test engine user data + + // Inputs + ImVector InputEventsQueue; // Input events which will be trickled/written into IO structure. + ImVector InputEventsTrail; // Past input events processed in NewFrame(). This is to allow domain-specific application to access e.g mouse/pen trail. + ImGuiMouseSource InputEventsNextMouseSource; + ImU32 InputEventsNextEventId; + + // Windows state + ImVector Windows; // Windows, sorted in display order, back to front + ImVector WindowsFocusOrder; // Root windows, sorted in focus order, back to front. + ImVector WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child + ImVector CurrentWindowStack; + ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* + int WindowsActiveCount; // Number of unique windows submitted by frame + float WindowsBorderHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, style.WindowBorderHoverPadding). This isn't so multi-dpi friendly. + ImGuiID DebugBreakInWindow; // Set to break in Begin() call. + ImGuiWindow* CurrentWindow; // Window being drawn into + ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. + ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiWindow* HoveredWindowBeforeClear; // Window the mouse is hovering. Filled even with _NoMouse. This is currently useful for multi-context compositors. + ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindowDockTree. + ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + ImVec2 WheelingWindowRefMousePos; + int WheelingWindowStartFrame; // This may be set one frame before WheelingWindow is != NULL + int WheelingWindowScrolledFrame; + float WheelingWindowReleaseTimer; + ImVec2 WheelingWindowWheelRemainder; + ImVec2 WheelingAxisAvg; + + // Item/widgets state and tracking information + ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier + ImGuiID DebugHookIdInfoId; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] + ImGuiID HoveredId; // Hovered widget, filled during the frame + ImGuiID HoveredIdPreviousFrame; + int HoveredIdPreviousFrameItemCount; // Count numbers of items using the same ID as last frame's hovered id + float HoveredIdTimer; // Measure contiguous hovering time + float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active + bool HoveredIdAllowOverlap; + bool HoveredIdIsDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. + bool ItemUnclipByLog; // Disable ItemAdd() clipping, essentially a memory-locality friendly copy of LogEnabled + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) + float ActiveIdTimer; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. + bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. + bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. + bool ActiveIdHasBeenEditedThisFrame; + bool ActiveIdFromShortcut; + ImS8 ActiveIdMouseButton; + ImGuiID ActiveIdDisabledId; // When clicking a disabled item we set ActiveId=window->MoveId to avoid interference with widget code. Actual item ID is stored here. + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad + ImGuiWindow* ActiveIdWindow; + ImGuiID ActiveIdPreviousFrame; + ImGuiDeactivatedItemData DeactivatedItemData; + ImGuiDataTypeStorage ActiveIdValueOnActivation; // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. + ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. + float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. + + // Key/Input Ownership + Shortcut Routing system + // - The idea is that instead of "eating" a given key, we can link to an owner. + // - Input query can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. + // - Routing is requested ahead of time for a given chord (Key + Mods) and granted in NewFrame(). + double LastKeyModsChangeTime; // Record the last time key mods changed (affect repeat delay when using shortcut logic) + double LastKeyModsChangeFromNoneTime; // Record the last time key mods changed away from being 0 (affect repeat delay when using shortcut logic) + double LastKeyboardKeyPressTime; // Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. + ImBitArrayForNamedKeys KeysMayBeCharInput; // Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). sizeof() = 20 bytes + ImGuiKeyOwnerData KeysOwnerData[ImGuiKey_NamedKey_COUNT]; + ImGuiKeyRoutingTable KeysRoutingTable; + ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) + bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) + ImGuiKeyChord DebugBreakInShortcutRouting; // Set to break in SetShortcutRouting()/Shortcut() calls. + //ImU32 ActiveIdUsingNavInputMask; // [OBSOLETE] Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes --> 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' + + // Next window/item data + ImGuiID CurrentFocusScopeId; // Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. + ImGuiItemFlags CurrentItemFlags; // Value for currently appending items == g.ItemFlagsStack.back() + ImGuiID DebugLocateId; // Storage for DebugLocateItemOnHover() feature: this is read by ItemAdd() so we keep it in a hot/cached location + ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions + ImGuiLastItemData LastItemData; // Storage for last submitted item (setup by ItemAdd) + ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions + bool DebugShowGroupRects; + bool GcCompactAll; // Request full GC + + // Shared stacks + ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) + ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() + ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() + ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() + ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() + ImVector ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() + ImVector OpenPopupStack; // Which popups are open (persistent) + ImVector BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) + ImVectorTreeNodeStack; // Stack for TreeNode() + + // Viewports + ImVector Viewports; // Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. + ImGuiViewportP* CurrentViewport; // We track changes of viewport (happening in Begin) so we can call Platform_OnChangedViewport() + ImGuiViewportP* MouseViewport; + ImGuiViewportP* MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag. + ImGuiID PlatformLastFocusedViewportId; + ImGuiPlatformMonitor FallbackMonitor; // Virtual monitor used as fallback if backend doesn't provide monitor information. + ImRect PlatformMonitorsFullWorkRect; // Bounding box of all platform monitors + int ViewportCreatedCount; // Unique sequential creation counter (mostly for testing/debugging) + int PlatformWindowsCreatedCount; // Unique sequential creation counter (mostly for testing/debugging) + int ViewportFocusedStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter + + // Keyboard/Gamepad Navigation + bool NavCursorVisible; // Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move. + bool NavHighlightItemUnderNav; // Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item. + //bool NavDisableHighlight; // Old name for !g.NavCursorVisible before 1.91.4 (2024/10/18). OPPOSITE VALUE (g.NavDisableHighlight == !g.NavCursorVisible) + //bool NavDisableMouseHover; // Old name for g.NavHighlightItemUnderNav before 1.91.1 (2024/10/18) this was called When user starts using keyboard/gamepad, we hide mouse hovering highlight until mouse is touched again. + bool NavMousePosDirty; // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default) + bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid + ImGuiID NavId; // Focused item for navigation + ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' + ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) + ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) + ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() + ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 + ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) + ImGuiActivateFlags NavActivateFlags; + ImVector NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. + ImGuiID NavHighlightActivatedId; + float NavHighlightActivatedTimer; + ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame. + ImGuiActivateFlags NavNextActivateFlags; + ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Gamepad + ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. + ImS8 NavCursorHideFrames; + //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606. + + // Navigation: Init & Move Requests + bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() + bool NavInitRequest; // Init request for appearing window to select first item + bool NavInitRequestFromMove; + ImGuiNavItemData NavInitResult; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + bool NavMoveSubmitted; // Move request submitted, will process result on next NewFrame() + bool NavMoveScoringItems; // Move request submitted, still scoring incoming items + bool NavMoveForwardToNextFrame; + ImGuiNavMoveFlags NavMoveFlags; + ImGuiScrollFlags NavMoveScrollFlags; + ImGuiKeyChord NavMoveKeyMods; + ImGuiDir NavMoveDir; // Direction of the move request (left/right/up/down) + ImGuiDir NavMoveDirForDebug; + ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename? + ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. + ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted + int NavScoringDebugCount; // Metrics for debugging + int NavTabbingDir; // Generally -1 or +1, 0 when tabbing without a nav id + int NavTabbingCounter; // >0 when counting items for tabbing + ImGuiNavItemData NavMoveResultLocal; // Best move request candidate within NavWindow + ImGuiNavItemData NavMoveResultLocalVisible; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) + ImGuiNavItemData NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) + ImGuiNavItemData NavTabbingResultFirst; // First tabbing request candidate within NavWindow and flattened hierarchy + + // Navigation: record of last move request + ImGuiID NavJustMovedFromFocusScopeId; // Just navigated from this focus scope id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). + ImGuiKeyChord NavJustMovedToKeyMods; + bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. + bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. + + // Navigation: Windowing (Ctrl+Tab for list, or Menu button + keys or directional pads to move/resize) + bool ConfigNavWindowingWithGamepad; // = true. Enable Ctrl+Tab by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. + ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) + ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) + ImGuiWindow* NavWindowingTarget; // Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! + ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. + ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the Ctrl+Tab contents + float NavWindowingTimer; + float NavWindowingHighlightAlpha; + ImGuiInputSource NavWindowingInputSource; + bool NavWindowingToggleLayer; // Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key. + ImGuiKey NavWindowingToggleKey; // Keyboard/gamepad key used when toggling to menu layer. + ImVec2 NavWindowingAccumDeltaPos; + ImVec2 NavWindowingAccumDeltaSize; + + // Render + float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and Ctrl+Tab list) + + // Drag and Drop + bool DragDropActive; + bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. + bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. + ImGuiDragDropFlags DragDropSourceFlags; + int DragDropSourceFrameCount; + int DragDropMouseButton; + ImGuiPayload DragDropPayload; + ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping) + ImRect DragDropTargetClipRect; // Store ClipRect at the time of item's drawing + ImGuiID DragDropTargetId; + ImGuiID DragDropTargetFullViewport; + ImGuiDragDropFlags DragDropAcceptFlagsCurr; + ImGuiDragDropFlags DragDropAcceptFlagsPrev; + float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) + ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) + int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source + ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press. + ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size + unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads + + // Clipper + int ClipperTempDataStacked; + ImVector ClipperTempData; + + // Tables + ImGuiTable* CurrentTable; + ImGuiID DebugBreakInTable; // Set to break in BeginTable() call. + int TablesTempDataStacked; // Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) + ImVector TablesTempData; // Temporary table data (buffers reused/shared across instances, support nesting) + ImPool Tables; // Persistent table data + ImVector TablesLastTimeActive; // Last used timestamp of each tables (SOA, for efficient GC) + ImVector DrawChannelsTempMergeBuffer; + + // Tab bars + ImGuiTabBar* CurrentTabBar; + ImPool TabBars; + ImVector CurrentTabBarStack; + ImVector ShrinkWidthBuffer; + + // Multi-Select state + ImGuiBoxSelectState BoxSelectState; + ImGuiMultiSelectTempData* CurrentMultiSelect; + int MultiSelectTempDataStacked; // Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) + ImVector MultiSelectTempData; + ImPool MultiSelectStorage; + + // Hover Delay system + ImGuiID HoverItemDelayId; + ImGuiID HoverItemDelayIdPreviousFrame; + float HoverItemDelayTimer; // Currently used by IsItemHovered() + float HoverItemDelayClearTimer; // Currently used by IsItemHovered(): grace time before g.TooltipHoverTimer gets cleared. + ImGuiID HoverItemUnlockedStationaryId; // Mouse has once been stationary on this item. Only reset after departing the item. + ImGuiID HoverWindowUnlockedStationaryId; // Mouse has once been stationary on this window. Only reset after departing the window. + + // Mouse state + ImGuiMouseCursor MouseCursor; + float MouseStationaryTimer; // Time the mouse has been stationary (with some loose heuristic) + ImVec2 MouseLastValidPos; + + // Widget state + ImGuiInputTextState InputTextState; + ImGuiTextIndex InputTextLineIndex; // Temporary storage + ImGuiInputTextDeactivatedState InputTextDeactivatedState; + ImFontBaked InputTextPasswordFontBackupBaked; + ImFontFlags InputTextPasswordFontBackupFlags; + ImGuiID TempInputId; // Temporary text input when using Ctrl+Click on a slider, etc. + ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types + int BeginMenuDepth; + int BeginComboDepth; + ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets + ImGuiID ColorEditCurrentID; // Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). + ImGuiID ColorEditSavedID; // ID we are saving/restoring HS for + float ColorEditSavedHue; // Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips + float ColorEditSavedSat; // Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips + ImU32 ColorEditSavedColor; // RGB value with alpha set to 0. + ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. + ImGuiComboPreviewData ComboPreviewData; + ImRect WindowResizeBorderExpectedRect; // Expected border rect, switch to relative edit if moving + bool WindowResizeRelativeMode; + short ScrollbarSeekMode; // 0: scroll to clicked location, -1/+1: prev/next page. + float ScrollbarClickDeltaToGrabCenter; // When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space. + float SliderGrabClickOffset; + float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. + bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? + bool DragCurrentAccumDirty; + float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + float DisabledAlphaBackup; // Backup for style.Alpha for BeginDisabled() + short DisabledStackSize; + short TooltipOverrideCount; + ImGuiWindow* TooltipPreviousWindow; // Window of last tooltip submitted during the frame + ImVector ClipboardHandlerData; // If no custom clipboard handler is defined + ImVector MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once + ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest() + + // Platform support + ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message. + ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. + + // Extensions + // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? + ImVector UserTextures; // List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. + ImGuiDockContext DockContext; + void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); + + // Settings + bool SettingsLoaded; + float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero + ImGuiTextBuffer SettingsIniData; // In memory .ini settings + ImVector SettingsHandlers; // List of .ini settings handlers + ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries + ImChunkStream SettingsTables; // ImGuiTable .ini settings entries + ImVector Hooks; // Hooks for extensions (e.g. test engine) + ImGuiID HookIdNext; // Next available HookId + + // Localization + const char* LocalizationTable[ImGuiLocKey_COUNT]; + + // Capture/Logging + bool LogEnabled; // Currently capturing + bool LogLineFirstItem; + ImGuiLogFlags LogFlags; // Capture flags/type + ImGuiWindow* LogWindow; + ImFileHandle LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + const char* LogNextPrefix; // See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! + const char* LogNextSuffix; + float LogLinePosY; + int LogDepthRef; + int LogDepthToExpand; + int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. + + // Error Handling + ImGuiErrorCallback ErrorCallback; // = NULL. May be exposed in public API eventually. + void* ErrorCallbackUserData; // = NULL + ImVec2 ErrorTooltipLockedPos; + bool ErrorFirst; + int ErrorCountCurrentFrame; // [Internal] Number of errors submitted this frame. + ImGuiErrorRecoveryState StackSizesInNewFrame; // [Internal] + ImGuiErrorRecoveryState*StackSizesInBeginForCurrentWindow; // [Internal] + + // Debug Tools + // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.) + int DebugDrawIdConflictsCount; // Locked count (preserved when holding Ctrl) + ImGuiDebugLogFlags DebugLogFlags; + ImGuiTextBuffer DebugLogBuf; + ImGuiTextIndex DebugLogIndex; + int DebugLogSkippedErrors; + ImGuiDebugLogFlags DebugLogAutoDisableFlags; + ImU8 DebugLogAutoDisableFrames; + ImU8 DebugLocateFrames; // For DebugLocateItemOnHover(). This is used together with DebugLocateId which is in a hot/cached spot above. + bool DebugBreakInLocateId; // Debug break in ItemAdd() call for g.DebugLocateId. + ImGuiKeyChord DebugBreakKeyChord; // = ImGuiKey_Pause + ImS8 DebugBeginReturnValueCullDepth; // Cycle between 0..9 then wrap around. + bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) + ImU8 DebugItemPickerMouseButton; + ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this ID + float DebugFlashStyleColorTime; + ImVec4 DebugFlashStyleColorBackup; + ImGuiMetricsConfig DebugMetricsConfig; + ImGuiDebugItemPathQuery DebugItemPathQuery; + ImGuiIDStackTool DebugIDStackTool; + ImGuiDebugAllocInfo DebugAllocInfo; + ImGuiDockNode* DebugHoveredDockNode; // Hovered dock node. +#if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) + ImGuiStorage DebugDrawIdConflictsAliveCount; + ImGuiStorage DebugDrawIdConflictsHighlightSet; +#endif + + // Misc + float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. + int FramerateSecPerFrameIdx; + int FramerateSecPerFrameCount; + float FramerateSecPerFrameAccum; + int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. + int WantCaptureKeyboardNextFrame; // " + int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. + ImVector TempBuffer; // Temporary text buffer + char TempKeychordName[64]; + + ImGuiContext(ImFontAtlas* shared_font_atlas); + ~ImGuiContext(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiWindowTempData, ImGuiWindow +//----------------------------------------------------------------------------- + +#define IMGUI_WINDOW_HARD_MIN_SIZE 4.0f + +// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) +// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) +struct IMGUI_API ImGuiWindowTempData +{ + // Layout + ImVec2 CursorPos; // Current emitting position, in absolute coordinates. + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding. + ImVec2 CursorMaxPos; // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. + ImVec2 IdealMaxPos; // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. + ImVec2 CurrLineSize; + ImVec2 PrevLineSize; + float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added). + float PrevLineTextBaseOffset; + bool IsSameLine; + bool IsSetPos; + ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + ImVec1 GroupOffset; + ImVec2 CursorStartPosLossyness;// Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. + + // Keyboard/Gamepad navigation + ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) + short NavLayersActiveMask; // Which layers have been written to (result from previous frame) + short NavLayersActiveMaskNext;// Which layers have been written to (accumulator for current frame) + bool NavIsScrollPushableX; // Set when current work location may be scrolled horizontally when moving left / right. This is generally always true UNLESS within a column. + bool NavHideHighlightOneFrame; + bool NavWindowHasScrollY; // Set per window when scrolling can be used (== ScrollMax.y > 0.0f) + + // Miscellaneous + bool MenuBarAppending; // FIXME: Remove this + ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. + ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement + int TreeDepth; // Current tree depth. + ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. + ImU32 TreeRecordsClippedNodesY2Mask; // Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. + ImVector ChildWindows; + ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) + ImGuiOldColumns* CurrentColumns; // Current columns set + int CurrentTableIdx; // Current table index (into g.Tables) + ImGuiLayoutType LayoutType; + ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() + ImU32 ModalDimBgColor; + + // Status flags + ImGuiItemStatusFlags WindowItemStatusFlags; + ImGuiItemStatusFlags ChildItemStatusFlags; + ImGuiItemStatusFlags DockTabItemStatusFlags; + ImRect DockTabItemRect; + + // Local parameters stacks + // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. + float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). + float ItemWidthDefault; + float TextWrapPos; // Current text wrap pos. + ImVector ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth) + ImVector TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos) +}; + +// Storage for one window +struct IMGUI_API ImGuiWindow +{ + ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). + char* Name; // Window name, owned by the window. + ImGuiID ID; // == ImHashStr(Name) + ImGuiWindowFlags Flags, FlagsPreviousFrame; // See enum ImGuiWindowFlags_ + ImGuiChildFlags ChildFlags; // Set when window is a child window. See enum ImGuiChildFlags_ + ImGuiWindowClass WindowClass; // Advanced users only. Set with SetNextWindowClass() + ImGuiViewportP* Viewport; // Always set in Begin(). Inactive windows may have a NULL value here if their viewport was discarded. + ImGuiID ViewportId; // We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) + ImVec2 ViewportPos; // We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) + int ViewportAllowPlatformMonitorExtend; // Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + ImVec2 Pos; // Position (always rounded-up to nearest pixel) + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. + ImVec2 ContentSizeIdeal; + ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). + ImVec2 WindowPadding; // Window padding at the time of Begin(). + float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. + float WindowBorderSize; // Window border size at the time of Begin(). + float TitleBarHeight, MenuBarHeight; // Note that those used to be function before 2024/05/28. If you have old code calling TitleBarHeight() you can change it to TitleBarHeight. + float DecoOuterSizeX1, DecoOuterSizeY1; // Left/Up offsets. Sum of non-scrolling outer decorations (X1 generally == 0.0f. Y1 generally = TitleBarHeight + MenuBarHeight). Locked during Begin(). + float DecoOuterSizeX2, DecoOuterSizeY2; // Right/Down offsets (X2 generally == ScrollbarSize.x, Y2 == ScrollbarSizes.y). + float DecoInnerSizeX1, DecoInnerSizeY1; // Applied AFTER/OVER InnerRect. Specialized for Tables as they use specialized form of clipping and frozen rows/columns are inside InnerRect (and not part of regular decoration sizes). + int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! + ImGuiID MoveId; // == window->GetID("#MOVE") + ImGuiID TabId; // == window->GetID("#TAB") + ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + ImVec2 Scroll; + ImVec2 ScrollMax; + ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) + ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold + ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. + bool ScrollbarX, ScrollbarY; // Are scrollbars visible? + bool ScrollbarXStabilizeEnabled; // Was ScrollbarX previously auto-stabilized? + ImU8 ScrollbarXStabilizeToggledHistory; // Used to stabilize scrollbar visibility in case of feedback loops + bool ViewportOwned; + bool Active; // Set to true on Begin(), unless Collapsed + bool WasActive; + bool WriteAccessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool WantCollapseToggle; + bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) + bool SkipRefresh; // [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. + bool Appearing; // Set during the frame where the window is appearing (or re-appearing) + bool Hidden; // Do not display (== HiddenFrames*** > 0) + bool IsFallbackWindow; // Set on the "Debug##Default" window. + bool IsExplicitChild; // Set when passed _ChildWindow, left to false by BeginDocked() + bool HasCloseButton; // Set when the window has a close button (p_open != NULL) + signed char ResizeBorderHovered; // Current border being hovered for resize (-1: none, otherwise 0-3) + signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) + short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + short BeginCountPreviousFrame; // Number of Begin() during the previous frame + short BeginOrderWithinParent; // Begin() order within immediate parent window, if we are a child window. Otherwise 0. + short BeginOrderWithinContext; // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. + short FocusOrder; // Order within WindowsFocusOrder[], altered when windows are focused. + ImGuiDir AutoPosLastDirection; + ImS8 AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames + ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size + ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only + ImS8 DisableInputsFrames; // Disable window interactions for N frames + ImGuiWindowBgClickFlags BgClickFlags : 8; // Configure behavior of click+dragging on window bg/void or over items. Default sets by io.ConfigWindowsMoveFromTitleBarOnly. If you use this please report in #3379. + ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. + ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. + ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. + ImGuiCond SetWindowDockAllowFlags : 8; // store acceptable condition flags for SetNextWindowDock() use. + ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. + + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) + ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. + + // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer. + // The main 'OuterRect', omitted as a field, is window->Rect(). + ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. + ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) + ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. + ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? + ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). + ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. + ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. + ImVec2ih HitTestHoleOffset; + + int LastFrameActive; // Last frame number the window was Active. + int LastFrameJustFocused; // Last frame number the window was made Focused. + float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) + ImGuiStorage StateStorage; + ImVector ColumnsStorage; + float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() + float FontWindowScaleParents; + float FontRefSize; // This is a copy of window->CalcFontSize() at the time of Begin(), trying to phase out CalcFontSize() especially as it may be called on non-current window. + int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) + + ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) + ImDrawList DrawListInst; + ImGuiWindow* ParentWindow; // If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise NULL. + ImGuiWindow* ParentWindowInBeginStack; + ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + ImGuiWindow* RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. + ImGuiWindow* RootWindowDockTree; // Point to ourself or first ancestor that is not a child window. Cross through dock nodes. + ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. + ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. + ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honored (e.g. Tool linked to Document) + + ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) + ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) + ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space + ImVec2 NavPreferredScoringPosRel[ImGuiNavLayer_COUNT]; // Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. + ImGuiID NavRootFocusScopeId; // Focus Scope ID at the time of Begin() + + int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy + int MemoryDrawListVtxCapacity; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected + + // Docking + bool DockIsActive :1; // When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != NULL. ~~ (DockNode != NULL) && (DockNode->Windows.Size > 1). + bool DockNodeIsVisible :1; + bool DockTabIsVisible :1; // Is our window visible this frame? ~~ is the corresponding tab selected? + bool DockTabWantClose :1; + short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + ImGuiWindowDockStyle DockStyle; + ImGuiDockNode* DockNode; // Which node are we docked into. Important: Prefer testing DockIsActive in many cases as this will still be set when the dock node is hidden. + ImGuiDockNode* DockNodeAsHost; // Which node are we owning (for parent windows) + ImGuiID DockId; // Backup of last valid DockNode->ID, so single window remember their dock node id even when they are not bound any more + +public: + ImGuiWindow(ImGuiContext* context, const char* name); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(const void* ptr); + ImGuiID GetID(int n); + ImGuiID GetIDFromPos(const ImVec2& p_abs); + ImGuiID GetIDFromRectangle(const ImRect& r_abs); + + // We don't use g.FontSize because the window may be != g.CurrentWindow. + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } + + // [OBSOLETE] ImGuiWindow::CalcFontSize() was removed in 1.92.0 because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. + //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontDpiScale * FontWindowScaleParents; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Tab bar, Tab item support +//----------------------------------------------------------------------------- + +// Extend ImGuiTabBarFlags_ +enum ImGuiTabBarFlagsPrivate_ +{ + ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] + ImGuiTabBarFlags_IsFocused = 1 << 21, + ImGuiTabBarFlags_SaveSettings = 1 << 22, // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs +}; + +// Extend ImGuiTabItemFlags_ +enum ImGuiTabItemFlagsPrivate_ +{ + ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, + ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button + ImGuiTabItemFlags_Invisible = 1 << 22, // To reserve space e.g. with ImGuiTabItemFlags_Leading + ImGuiTabItemFlags_Unsorted = 1 << 23, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. +}; + +// Storage for one active tab item (sizeof() 48 bytes) +struct ImGuiTabItem +{ + ImGuiID ID; + ImGuiTabItemFlags Flags; + ImGuiWindow* Window; // When TabItem is part of a DockNode's TabBar, we hold on to a window. + int LastFrameVisible; + int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance + float Offset; // Position relative to beginning of tab bar + float Width; // Width currently displayed + float ContentWidth; // Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) + float RequestedWidth; // Width optionally requested by caller, -1.0f is unused + ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames + ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable + ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. + bool WantClose; // Marked as closed by SetTabItemClosed() + + ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } +}; + +// Storage for a tab bar (sizeof() 160 bytes) +struct IMGUI_API ImGuiTabBar +{ + ImGuiWindow* Window; + ImVector Tabs; + ImGuiTabBarFlags Flags; + ImGuiID ID; // Zero for tab-bars used by docking + ImGuiID SelectedTabId; // Selected tab/window + ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation + ImGuiID NextScrollToTabId; + ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) + int CurrFrameVisible; + int PrevFrameVisible; + ImRect BarRect; + float BarRectPrevWidth; // Backup of previous width. When width change we enforce keep horizontal scroll on focused tab. + float CurrTabsContentsHeight; + float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar + float WidthAllTabs; // Actual width of all tabs (locked during layout) + float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped + float ScrollingAnim; + float ScrollingTarget; + float ScrollingTargetDistToVisibility; + float ScrollingSpeed; + float ScrollingRectMinX; + float ScrollingRectMaxX; + float SeparatorMinX; + float SeparatorMaxX; + ImGuiID ReorderRequestTabId; + ImS16 ReorderRequestOffset; + ImS8 BeginCount; + bool WantLayout; + bool VisibleTabWasSubmitted; + bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame + bool ScrollButtonEnabled; + ImS16 TabsActiveCount; // Number of tabs submitted this frame. + ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + float ItemSpacingY; + ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImVec2 BackupCursorPos; + ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. + + ImGuiTabBar(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Table support +//----------------------------------------------------------------------------- + +#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color. +#define IMGUI_TABLE_MAX_COLUMNS 512 // Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. + +// [Internal] sizeof() ~ 112 +// We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. +// We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. +// This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". +struct ImGuiTableColumn +{ + ImGuiTableColumnFlags Flags; // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_ + float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space. + float MinX; // Absolute positions + float MaxX; + float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout() + float WidthAuto; // Automatic width + float WidthMax; // Maximum width (FIXME: overwritten by each instance) + float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. + float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_). + ImRect ClipRect; // Clipping rectangle for the column + ImGuiID UserID; // Optional, value passed to TableSetupColumn() + float WorkMinX; // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column + float WorkMaxX; // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2) + float ItemWidth; // Current item width for the column, preserved across rows + float ContentMaxXFrozen; // Contents maximum position for frozen rows (apart from headers), from which we can infer content width. + float ContentMaxXUnfrozen; + float ContentMaxXHeadersUsed; // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls + float ContentMaxXHeadersIdeal; + ImS16 NameOffset; // Offset into parent ColumnsNames[] + ImGuiTableColumnIdx DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) + ImGuiTableColumnIdx IndexWithinEnabledSet; // Index within enabled/visible set (<= IndexToDisplayOrder) + ImGuiTableColumnIdx PrevEnabledColumn; // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column + ImGuiTableColumnIdx NextEnabledColumn; // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column + ImGuiTableColumnIdx SortOrder; // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort + ImGuiTableDrawChannelIdx DrawChannelCurrent; // Index within DrawSplitter.Channels[] + ImGuiTableDrawChannelIdx DrawChannelFrozen; // Draw channels for frozen rows (often headers) + ImGuiTableDrawChannelIdx DrawChannelUnfrozen; // Draw channels for unfrozen rows + bool IsEnabled; // IsUserEnabled && (Flags & ImGuiTableColumnFlags_Disabled) == 0 + bool IsUserEnabled; // Is the column not marked Hidden by the user? (unrelated to being off view, e.g. clipped by scrolling). + bool IsUserEnabledNextFrame; + bool IsVisibleX; // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled). + bool IsVisibleY; + bool IsRequestOutput; // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not. + bool IsSkipItems; // Do we want item submissions to this column to be completely ignored (no layout will happen). + bool IsPreserveWidthAuto; + ImS8 NavLayerCurrent; // ImGuiNavLayer in 1 byte + ImU8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit + ImU8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem + ImU8 SortDirection : 2; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending + ImU8 SortDirectionsAvailCount : 2; // Number of available sort directions (0 to 3) + ImU8 SortDirectionsAvailMask : 4; // Mask of available sort directions (1-bit each) + ImU8 SortDirectionsAvailList; // Ordered list of available sort directions (2-bits each, total 8-bits) + + ImGuiTableColumn() + { + memset(this, 0, sizeof(*this)); + StretchWeight = WidthRequest = -1.0f; + NameOffset = -1; + DisplayOrder = IndexWithinEnabledSet = -1; + PrevEnabledColumn = NextEnabledColumn = -1; + SortOrder = -1; + SortDirection = ImGuiSortDirection_None; + DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1; + } +}; + +// Transient cell data stored per row. +// sizeof() ~ 6 bytes +struct ImGuiTableCellData +{ + ImU32 BgColor; // Actual color + ImGuiTableColumnIdx Column; // Column number +}; + +// Parameters for TableAngledHeadersRowEx() +// This may end up being refactored for more general purpose. +// sizeof() ~ 12 bytes +struct ImGuiTableHeaderData +{ + ImGuiTableColumnIdx Index; // Column index + ImU32 TextColor; + ImU32 BgColor0; + ImU32 BgColor1; +}; + +// Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) +// sizeof() ~ 24 bytes +struct ImGuiTableInstanceData +{ + ImGuiID TableInstanceID; + float LastOuterHeight; // Outer height from last frame + float LastTopHeadersRowHeight; // Height of first consecutive header rows from last frame (FIXME: this is used assuming consecutive headers are in same frozen set) + float LastFrozenHeight; // Height of frozen section from last frame + int HoveredRowLast; // Index of row which was hovered last frame. + int HoveredRowNext; // Index of row hovered this frame, set after encountering it. + + ImGuiTableInstanceData() { TableInstanceID = 0; LastOuterHeight = LastTopHeadersRowHeight = LastFrozenHeight = 0.0f; HoveredRowLast = HoveredRowNext = -1; } +}; + +// sizeof() ~ 592 bytes + heap allocs described in TableBeginInitMemory() +struct IMGUI_API ImGuiTable +{ + ImGuiID ID; + ImGuiTableFlags Flags; + void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[], and RowCellData[] + ImGuiTableTempData* TempData; // Transient data while table is active. Point within g.CurrentTableStack[] + ImSpan Columns; // Point within RawData[] + ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) + ImSpan RowCellData; // Point within RawData[]. Store cells background requests for current row. + ImBitArrayPtr EnabledMaskByDisplayOrder; // Column DisplayOrder -> IsEnabled map + ImBitArrayPtr EnabledMaskByIndex; // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data + ImBitArrayPtr VisibleMaskByIndex; // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect) + ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) + int SettingsOffset; // Offset in g.SettingsTables + int LastFrameActive; + int ColumnsCount; // Number of columns declared in BeginTable() + int CurrentRow; + int CurrentColumn; + ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple tables with the same ID are multiple tables, they are just synced. + ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with + float RowPosY1; + float RowPosY2; + float RowMinHeight; // Height submitted to TableNextRow() + float RowCellPaddingY; // Top and bottom padding. Reloaded during row change. + float RowTextBaseline; + float RowIndentOffsetX; + ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ + ImGuiTableRowFlags LastRowFlags : 16; + int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this. + ImU32 RowBgColor[2]; // Background color override for current row. + ImU32 BorderColorStrong; + ImU32 BorderColorLight; + float BorderX1; + float BorderX2; + float HostIndentX; + float MinColumnWidth; + float OuterPaddingX; + float CellPaddingX; // Padding from each borders. Locked in BeginTable()/Layout. + float CellSpacingX1; // Spacing between non-bordered cells. Locked in BeginTable()/Layout. + float CellSpacingX2; + float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. + float ColumnsGivenWidth; // Sum of current column width + float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window + float ColumnsStretchSumWeights; // Sum of weight of all enabled stretching columns + float ResizedColumnNextWidth; + float ResizeLockMinContentsX2; // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table. + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. + float AngledHeadersHeight; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() + float AngledHeadersSlope; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() + ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). + ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is " + ImRect WorkRect; + ImRect InnerClipRect; + ImRect BgClipRect; // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries + ImRect Bg0ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped + ImRect Bg2ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect. + ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. + ImRect HostBackupInnerClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() + ImGuiWindow* OuterWindow; // Parent window for the table + ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) + ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names + ImDrawListSplitter* DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly + ImGuiTableInstanceData InstanceDataFirst; + ImVector InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableColumnSortSpecs SortSpecsSingle; + ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() + ImGuiTableColumnIdx SortSpecsCount; + ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) + ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns using fixed width (<= ColumnsCount) + ImGuiTableColumnIdx DeclColumnsCount; // Count calls to TableSetupColumn() + ImGuiTableColumnIdx AngledHeadersCount; // Count columns with angled headers + ImGuiTableColumnIdx HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column! + ImGuiTableColumnIdx HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). + ImGuiTableColumnIdx HighlightColumnHeader; // Index of column which should be highlighted. + ImGuiTableColumnIdx AutoFitSingleColumn; // Index of single column requesting auto-fit. + ImGuiTableColumnIdx ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. + ImGuiTableColumnIdx LastResizedColumn; // Index of column being resized from previous frame. + ImGuiTableColumnIdx HeldHeaderColumn; // Index of column header being held. + ImGuiTableColumnIdx ReorderColumn; // Index of column being reordered. (not cleared) + ImGuiTableColumnIdx ReorderColumnDir; // -1 or +1 + ImGuiTableColumnIdx LeftMostEnabledColumn; // Index of left-most non-hidden column. + ImGuiTableColumnIdx RightMostEnabledColumn; // Index of right-most non-hidden column. + ImGuiTableColumnIdx LeftMostStretchedColumn; // Index of left-most stretched column. + ImGuiTableColumnIdx RightMostStretchedColumn; // Index of right-most stretched column. + ImGuiTableColumnIdx ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot + ImGuiTableColumnIdx FreezeRowsRequest; // Requested frozen rows count + ImGuiTableColumnIdx FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) + ImGuiTableColumnIdx FreezeColumnsRequest; // Requested frozen columns count + ImGuiTableColumnIdx FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) + ImGuiTableColumnIdx RowCellDataCurrent; // Index of current RowCellData[] entry in current row + ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here. + ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[] + ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; + ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable(). + bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. + bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). + bool IsInitializing; + bool IsSortSpecsDirty; + bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. + bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). + bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup() + bool IsSettingsRequestLoad; + bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSettings data. + bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) + bool IsResetAllRequest; + bool IsResetDisplayOrderRequest; + bool IsUnfrozenRows; // Set when we got past the frozen row. + bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() + bool IsActiveIdAliveBeforeTable; + bool IsActiveIdInTable; + bool HasScrollbarYCurr; // Whether ANY instance of this table had a vertical scrollbar during the current frame. + bool HasScrollbarYPrev; // Whether ANY instance of this table had a vertical scrollbar during the previous. + bool MemoryCompacted; + bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis + + ImGuiTable() { memset(this, 0, sizeof(*this)); LastFrameActive = -1; } + ~ImGuiTable() { IM_FREE(RawData); } +}; + +// Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). +// - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. +// - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. +// FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. +// sizeof() ~ 136 bytes. +struct IMGUI_API ImGuiTableTempData +{ + ImGuiID WindowID; // Shortcut to g.Tables[TableIndex]->OuterWindow->ID. + int TableIndex; // Index in g.Tables.Buf[] pool + float LastTimeActive; // Last timestamp this structure was used + float AngledHeadersExtraWidth; // Used in EndTable() + ImVector AngledHeadersRequests; // Used in TableAngledHeadersRow() + + ImVec2 UserOuterSize; // outer_size.x passed to BeginTable() + ImDrawListSplitter DrawSplitter; + + ImRect HostBackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() + ImVec2 HostBackupPrevLineSize; // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable() + ImVec2 HostBackupCurrLineSize; // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable() + ImVec2 HostBackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() + ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() + float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() + int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() + + ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; } +}; + +// sizeof() ~ 16 +struct ImGuiTableColumnSettings +{ + float WidthOrWeight; + ImGuiID UserID; + ImGuiTableColumnIdx Index; + ImGuiTableColumnIdx DisplayOrder; + ImGuiTableColumnIdx SortOrder; + ImU8 SortDirection : 2; + ImS8 IsEnabled : 2; // "Visible" in ini file + ImU8 IsStretch : 1; + + ImGuiTableColumnSettings() + { + WidthOrWeight = 0.0f; + UserID = 0; + Index = -1; + DisplayOrder = SortOrder = -1; + SortDirection = ImGuiSortDirection_None; + IsEnabled = -1; + IsStretch = 0; + } +}; + +// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.) +struct ImGuiTableSettings +{ + ImGuiID ID; // Set to 0 to invalidate/delete the setting + ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. + ImGuiTableColumnIdx ColumnsCount; + ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + + ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } + ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGui internal API +// No guarantee of forward compatibility here! +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Windows + // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) + // If this ever crashes because g.CurrentWindow is NULL, it means that either: + // - ImGui::NewFrame() has never been called, which is illegal. + // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + IMGUI_API ImGuiIO& GetIO(ImGuiContext* ctx); + IMGUI_API ImGuiPlatformIO& GetPlatformIO(ImGuiContext* ctx); + inline float GetScale() { ImGuiContext& g = *GImGui; return g.Style._MainScale; } // FIXME-DPI: I don't want to formalize this just yet. Because reasons. Please don't use. + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } + IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); + IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); + IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); + IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy); + IMGUI_API bool IsWindowInBeginStack(ImGuiWindow* window); + IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent); + IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); + IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); + IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); + IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); + IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); + IMGUI_API void SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window); + inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } // You may also use SetNextWindowClass()'s FocusRouteParentWindowId field. + inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } + inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } + inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } + inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } + + // Windows: Display Order and Focus Order + IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); + IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags); + IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); + IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); + IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); + IMGUI_API void BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* above_window); + IMGUI_API int FindWindowDisplayIndex(ImGuiWindow* window); + IMGUI_API ImGuiWindow* FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window); + + // Windows: Idle, Refresh Policies [EXPERIMENTAL] + IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); + + // Fonts, drawing + IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture. EXPERIMENTAL: DO NOT USE YET. + IMGUI_API void UnregisterUserTexture(ImTextureData* tex); + IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); + IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); + IMGUI_API void SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling); + IMGUI_API void UpdateCurrentFontSize(float restore_font_size_after_scaling); + IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); + inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } + inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } + IMGUI_API ImFont* GetDefaultFont(); + IMGUI_API void PushPasswordFont(); + IMGUI_API void PopPasswordFont(); + inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { return GetForegroundDrawList(window->Viewport); } + IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector* out_list, ImDrawList* draw_list); + + // Init + IMGUI_API void Initialize(); + IMGUI_API void Shutdown(); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). + + // Context name & generic context hooks + IMGUI_API void SetContextName(ImGuiContext* ctx, const char* name); + IMGUI_API ImGuiID AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook); + IMGUI_API void RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_to_remove); + IMGUI_API void CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType type); + + // NewFrame + IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); + IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); + IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); + IMGUI_API void StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock); + IMGUI_API void StopMouseMovingWindow(); + IMGUI_API void UpdateMouseMovingWindowNewFrame(); + IMGUI_API void UpdateMouseMovingWindowEndFrame(); + + // Viewports + IMGUI_API void TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size); + IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); + IMGUI_API void DestroyPlatformWindow(ImGuiViewportP* viewport); + IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); + IMGUI_API void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport); + IMGUI_API const ImGuiPlatformMonitor* GetViewportPlatformMonitor(ImGuiViewport* viewport); + IMGUI_API ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos); + + // Settings + IMGUI_API void MarkIniSettingsDirty(); + IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); + IMGUI_API void ClearIniSettings(); + IMGUI_API void AddSettingsHandler(const ImGuiSettingsHandler* handler); + IMGUI_API void RemoveSettingsHandler(const char* type_name); + IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); + + // Settings - Windows + IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); + IMGUI_API ImGuiWindowSettings* FindWindowSettingsByID(ImGuiID id); + IMGUI_API ImGuiWindowSettings* FindWindowSettingsByWindow(ImGuiWindow* window); + IMGUI_API void ClearWindowSettings(const char* name); + + // Localization + IMGUI_API void LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count); + inline const char* LocalizeGetMsg(ImGuiLocKey key) { ImGuiContext& g = *GImGui; const char* msg = g.LocalizationTable[key]; return msg ? msg : "*Missing Text*"; } + + // Scrolling + IMGUI_API void SetScrollX(ImGuiWindow* window, float scroll_x); + IMGUI_API void SetScrollY(ImGuiWindow* window, float scroll_y); + IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio); + IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio); + + // Early work-in-progress API (ScrollToItem() will become public) + IMGUI_API void ScrollToItem(ImGuiScrollFlags flags = 0); + IMGUI_API void ScrollToRect(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); + IMGUI_API ImVec2 ScrollToRectEx(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); +//#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& rect) { ScrollToRect(window, rect, ImGuiScrollFlags_KeepVisibleEdgeY); } +//#endif + + // Basic Accessors + inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } + inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } + inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void ClearActiveID(); + IMGUI_API ImGuiID GetHoveredID(); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. + IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) + IMGUI_API ImGuiID GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed); + IMGUI_API ImGuiID GetIDWithSeed(int n, ImGuiID seed); + + // Basic Helpers for widget code + IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); + inline void ItemSize(const ImRect& bb, float text_baseline_y = -1.0f) { ItemSize(bb.GetSize(), text_baseline_y); } // FIXME: This is a misleading API since we expect CursorPos to be bb.Min. + IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL, ImGuiItemFlags extra_flags = 0); + IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags); + IMGUI_API bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags = 0); + IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id); + IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); + IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + IMGUI_API void PushMultiItemsWidths(int components, float width_full); + IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min); + IMGUI_API void CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end); + + // Parameter stacks (shared) + IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); + IMGUI_API void BeginDisabledOverrideReenable(); + IMGUI_API void EndDisabledOverrideReenable(); + + // Logging/Capture + IMGUI_API void LogBegin(ImGuiLogFlags flags, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. + IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer + IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); + IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix); + + // Childs + IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); + + // Popups, Modals + IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags); + IMGUI_API bool BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags); + IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); + IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); + IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); + IMGUI_API void ClosePopupsExceptModals(); + IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); + IMGUI_API ImRect GetPopupAllowedExtentRect(ImGuiWindow* window); + IMGUI_API ImGuiWindow* GetTopMostPopupModal(); + IMGUI_API ImGuiWindow* GetTopMostAndVisiblePopupModal(); + IMGUI_API ImGuiWindow* FindBlockingModal(ImGuiWindow* window); + IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); + IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); + IMGUI_API ImGuiMouseButton GetMouseButtonFromPopupFlags(ImGuiPopupFlags flags); + + // Tooltips + IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); + IMGUI_API bool BeginTooltipHidden(); + + // Menus + IMGUI_API bool BeginViewportSideBar(const char* name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); + IMGUI_API bool BeginMenuEx(const char* label, const char* icon, bool enabled = true); + IMGUI_API bool MenuItemEx(const char* label, const char* icon, const char* shortcut = NULL, bool selected = false, bool enabled = true); + + // Combos + IMGUI_API bool BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags); + IMGUI_API bool BeginComboPreview(); + IMGUI_API void EndComboPreview(); + + // Keyboard/Gamepad Navigation + IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); + IMGUI_API void NavInitRequestApplyResult(); + IMGUI_API bool NavMoveRequestButNoResultYet(); + IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); + IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); + IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); + IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data); + IMGUI_API void NavMoveRequestCancel(); + IMGUI_API void NavMoveRequestApplyResult(); + IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); + IMGUI_API void NavHighlightActivated(ImGuiID id); + IMGUI_API void NavClearPreferredPosForAxis(ImGuiAxis axis); + IMGUI_API void SetNavCursorVisibleAfterMove(); + IMGUI_API void NavUpdateCurrentWindowIsScrollPushableX(); + IMGUI_API void SetNavWindow(ImGuiWindow* window); + IMGUI_API void SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel); + IMGUI_API void SetNavFocusScope(ImGuiID focus_scope_id); + + // Focus/Activation + // This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are + // much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones. + IMGUI_API void FocusItem(); // Focus last item (no selection/activation). + IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. Was called 'ActivateItem()' before 1.89.7. + + // Inputs + // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. + inline bool IsNamedKey(ImGuiKey key) { return key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END; } + inline bool IsNamedKeyOrMod(ImGuiKey key) { return (key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END) || key == ImGuiMod_Ctrl || key == ImGuiMod_Shift || key == ImGuiMod_Alt || key == ImGuiMod_Super; } + inline bool IsLegacyKey(ImGuiKey key) { return key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_LegacyNativeKey_END; } + inline bool IsKeyboardKey(ImGuiKey key) { return key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END; } + inline bool IsGamepadKey(ImGuiKey key) { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; } + inline bool IsMouseKey(ImGuiKey key) { return key >= ImGuiKey_Mouse_BEGIN && key < ImGuiKey_Mouse_END; } + inline bool IsAliasKey(ImGuiKey key) { return key >= ImGuiKey_Aliases_BEGIN && key < ImGuiKey_Aliases_END; } + inline bool IsLRModKey(ImGuiKey key) { return key >= ImGuiKey_LeftCtrl && key <= ImGuiKey_RightSuper; } + ImGuiKeyChord FixupKeyChord(ImGuiKeyChord key_chord); + inline ImGuiKey ConvertSingleModFlagToKey(ImGuiKey key) + { + if (key == ImGuiMod_Ctrl) return ImGuiKey_ReservedForModCtrl; + if (key == ImGuiMod_Shift) return ImGuiKey_ReservedForModShift; + if (key == ImGuiMod_Alt) return ImGuiKey_ReservedForModAlt; + if (key == ImGuiMod_Super) return ImGuiKey_ReservedForModSuper; + return key; + } + + IMGUI_API ImGuiKeyData* GetKeyData(ImGuiContext* ctx, ImGuiKey key); + inline ImGuiKeyData* GetKeyData(ImGuiKey key) { ImGuiContext& g = *GImGui; return GetKeyData(&g, key); } + IMGUI_API const char* GetKeyChordName(ImGuiKeyChord key_chord); + inline ImGuiKey MouseButtonToKey(ImGuiMouseButton button) { IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT); return (ImGuiKey)(ImGuiKey_MouseLeft + button); } + IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f); + IMGUI_API ImVec2 GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down); + IMGUI_API float GetNavTweakPressedAmount(ImGuiAxis axis); + IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate); + IMGUI_API void GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate); + IMGUI_API void TeleportMousePos(const ImVec2& pos); + IMGUI_API void SetActiveIdUsingAllKeyboardKeys(); + inline bool IsActiveIdUsingNavDir(ImGuiDir dir) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; } + + // [EXPERIMENTAL] Low-Level: Key/Input Ownership + // - The idea is that instead of "eating" a given input, we can link to an owner id. + // - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). + // - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. + // - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). + // - Input ownership is automatically released on the frame after a key is released. Therefore: + // - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). + // - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). + // - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. + // - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. + // Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. + IMGUI_API ImGuiID GetKeyOwner(ImGuiKey key); + IMGUI_API void SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0); + IMGUI_API void SetKeyOwnersForKeyChord(ImGuiKeyChord key, ImGuiID owner_id, ImGuiInputFlags flags = 0); + IMGUI_API void SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags); // Set key owner to last item if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. + IMGUI_API bool TestKeyOwner(ImGuiKey key, ImGuiID owner_id); // Test that key is either not owned, either owned by 'owner_id' + inline ImGuiKeyOwnerData* GetKeyOwnerData(ImGuiContext* ctx, ImGuiKey key) { if (key & ImGuiMod_Mask_) key = ConvertSingleModFlagToKey(key); IM_ASSERT(IsNamedKey(key)); return &ctx->KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN]; } + + // [EXPERIMENTAL] High-Level: Input Access functions w/ support for Key/Input Ownership + // - Important: legacy IsKeyPressed(ImGuiKey, bool repeat=true) _DEFAULTS_ to repeat, new IsKeyPressed() requires _EXPLICIT_ ImGuiInputFlags_Repeat flag. + // - Expected to be later promoted to public API, the prototypes are designed to replace existing ones (since owner_id can default to Any == 0) + // - Specifying a value for 'ImGuiID owner' will test that EITHER the key is NOT owned (UNLESS locked), EITHER the key is owned by 'owner'. + // Legacy functions use ImGuiKeyOwner_Any meaning that they typically ignore ownership, unless a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. + // - Binding generators may want to ignore those for now, or suffix them with Ex() until we decide if this gets moved into public API. + IMGUI_API bool IsKeyDown(ImGuiKey key, ImGuiID owner_id); + IMGUI_API bool IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); // Important: when transitioning from old to new IsKeyPressed(): old API has "bool repeat = true", so would default to repeat. New API requires explicit ImGuiInputFlags_Repeat. + IMGUI_API bool IsKeyReleased(ImGuiKey key, ImGuiID owner_id); + IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id = 0); + IMGUI_API bool IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id); + IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0); + IMGUI_API bool IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id); + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id); + + // Shortcut Testing & Routing + // - Set Shortcut() and SetNextItemShortcut() in imgui.h + // - When a policy (except for ImGuiInputFlags_RouteAlways *) is set, Shortcut() will register itself with SetShortcutRouting(), + // allowing the system to decide where to route the input among other route-aware calls. + // (* using ImGuiInputFlags_RouteAlways is roughly equivalent to calling IsKeyChordPressed(key) and bypassing route registration and check) + // - When using one of the routing option: + // - The default route is ImGuiInputFlags_RouteFocused (accept inputs if window is in focus stack. Deep-most focused window takes inputs. ActiveId takes inputs over deep-most focused window.) + // - Routes are requested given a chord (key + modifiers) and a routing policy. + // - Routes are resolved during NewFrame(): if keyboard modifiers are matching current ones: SetKeyOwner() is called + route is granted for the frame. + // - Each route may be granted to a single owner. When multiple requests are made we have policies to select the winning route (e.g. deep most window). + // - Multiple read sites may use the same owner id can all access the granted route. + // - When owner_id is 0 we use the current Focus Scope ID as a owner ID in order to identify our location. + // - You can chain two unrelated windows in the focus stack using SetWindowParentWindowForFocusRoute() + // e.g. if you have a tool window associated to a document, and you want document shortcuts to run when the tool is focused. + IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); + IMGUI_API bool SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); // owner_id needs to be explicit and cannot be 0 + IMGUI_API bool TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id); + IMGUI_API ImGuiKeyRoutingData* GetShortcutRoutingData(ImGuiKeyChord key_chord); + + // Docking + // (some functions are only declared in imgui.cpp, see Docking section) + IMGUI_API void DockContextInitialize(ImGuiContext* ctx); + IMGUI_API void DockContextShutdown(ImGuiContext* ctx); + IMGUI_API void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs); // Use root_id==0 to clear all + IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); + IMGUI_API void DockContextNewFrameUpdateUndocking(ImGuiContext* ctx); + IMGUI_API void DockContextNewFrameUpdateDocking(ImGuiContext* ctx); + IMGUI_API void DockContextEndFrame(ImGuiContext* ctx); + IMGUI_API ImGuiID DockContextGenNodeID(ImGuiContext* ctx); + IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); + IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); + IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); + IMGUI_API void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true); + IMGUI_API void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); + IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); + IMGUI_API ImGuiDockNode*DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id); + IMGUI_API void DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); + IMGUI_API bool DockNodeBeginAmendTabBar(ImGuiDockNode* node); + IMGUI_API void DockNodeEndAmendTabBar(); + inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } + inline bool DockNodeIsInHierarchyOf(ImGuiDockNode* node, ImGuiDockNode* parent) { while (node) { if (node == parent) return true; node = node->ParentNode; } return false; } + inline int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } + inline ImGuiID DockNodeGetWindowMenuButtonId(const ImGuiDockNode* node) { return ImHashStr("#COLLAPSE", 0, node->ID); } + inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } + IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); + IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); + IMGUI_API void BeginDockableDragDropSource(ImGuiWindow* window); + IMGUI_API void BeginDockableDragDropTarget(ImGuiWindow* window); + IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond); + + // Docking - Builder function needs to be generally called before the node is used/submitted. + // - The DockBuilderXXX functions are designed to _eventually_ become a public API, but it is too early to expose it and guarantee stability. + // - Do not hold on ImGuiDockNode* pointers! They may be invalidated by any split/merge/remove operation and every frame. + // - To create a DockSpace() node, make sure to set the ImGuiDockNodeFlags_DockSpace flag when calling DockBuilderAddNode(). + // You can create dockspace nodes (attached to a window) _or_ floating nodes (carry its own window) with this API. + // - DockBuilderSplitNode() create 2 child nodes within 1 node. The initial node becomes a parent node. + // - If you intend to split the node immediately after creation using DockBuilderSplitNode(), make sure + // to call DockBuilderSetNodeSize() beforehand. If you don't, the resulting split sizes may not be reliable. + // - Call DockBuilderFinish() after you are done. + IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); + IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); + inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } + IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); + IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows + IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_settings_refs = true); + IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). + IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); + IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); + IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir); // Create 2 child nodes in this parent node. + IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs); + IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs); + IMGUI_API void DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name); + IMGUI_API void DockBuilderFinish(ImGuiID node_id); + + // [EXPERIMENTAL] Focus Scope + // This is generally used to identify a unique input location (for e.g. a selection set) + // There is one per window (automatically set in Begin), but: + // - Selection patterns generally need to react (e.g. clear a selection) when landing on one item of the set. + // So in order to identify a set multiple lists in same window may each need a focus scope. + // If you imagine an hypothetical BeginSelectionGroup()/EndSelectionGroup() api, it would likely call PushFocusScope()/EndFocusScope() + // - Shortcut routing also use focus scope as a default location identifier if an owner is not provided. + // We don't use the ID Stack for this as it is common to want them separate. + IMGUI_API void PushFocusScope(ImGuiID id); + IMGUI_API void PopFocusScope(); + inline ImGuiID GetCurrentFocusScope() { ImGuiContext& g = *GImGui; return g.CurrentFocusScopeId; } // Focus scope we are outputting into, set by PushFocusScope() + + // Drag and Drop + IMGUI_API bool IsDragDropActive(); + IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); + IMGUI_API bool BeginDragDropTargetViewport(ImGuiViewport* viewport, const ImRect* p_bb = NULL); + IMGUI_API void ClearDragDrop(); + IMGUI_API bool IsDragDropPayloadBeingAccepted(); + IMGUI_API void RenderDragDropTargetRectForItem(const ImRect& bb); + IMGUI_API void RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb); + + // Typing-Select API + // (provide Windows Explorer style "select items by typing partial name" + "cycle through items by typing same letter" feature) + // (this is currently not documented nor used by main library, but should work. See "widgets_typingselect" in imgui_test_suite for usage code. Please let us know if you use this!) + IMGUI_API ImGuiTypingSelectRequest* GetTypingSelectRequest(ImGuiTypingSelectFlags flags = ImGuiTypingSelectFlags_None); + IMGUI_API int TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); + IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); + IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); + + // Box-Select API + IMGUI_API bool BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); + IMGUI_API void EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags); + + // Multi-Select API + IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); + IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); + IMGUI_API void MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected); + IMGUI_API void MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item); + inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } + inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } + + // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) + IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); + IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). + IMGUI_API void EndColumns(); // close columns + IMGUI_API void PushColumnClipRect(int column_index); + IMGUI_API void PushColumnsBackground(); + IMGUI_API void PopColumnsBackground(); + IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); + IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); + IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); + IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); + + // Tables: Candidates for public API + IMGUI_API void TableOpenContextMenu(int column_n = -1); + IMGUI_API void TableSetColumnWidth(int column_n, float width); + IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); + IMGUI_API int TableGetHoveredRow(); // Retrieve *PREVIOUS FRAME* hovered row. This difference with TableGetHoveredColumn() is the reason why this is not public yet. + IMGUI_API float TableGetHeaderRowHeight(); + IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); + IMGUI_API void TablePushBackgroundChannel(); + IMGUI_API void TablePopBackgroundChannel(); + IMGUI_API void TablePushColumnChannel(int column_n); + IMGUI_API void TablePopColumnChannel(); + IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count); + + // Tables: Internals + inline ImGuiTable* GetCurrentTable() { ImGuiContext& g = *GImGui; return g.CurrentTable; } + IMGUI_API ImGuiTable* TableFindByID(ImGuiID id); + IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); + IMGUI_API void TableBeginInitMemory(ImGuiTable* table, int columns_count); + IMGUI_API void TableBeginApplyRequests(ImGuiTable* table); + IMGUI_API void TableSetupDrawChannels(ImGuiTable* table); + IMGUI_API void TableUpdateLayout(ImGuiTable* table); + IMGUI_API void TableUpdateBorders(ImGuiTable* table); + IMGUI_API void TableUpdateColumnsWeightFromWidth(ImGuiTable* table); + IMGUI_API void TableDrawBorders(ImGuiTable* table); + IMGUI_API void TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags_for_section_to_display); + IMGUI_API bool TableBeginContextMenuPopup(ImGuiTable* table); + IMGUI_API void TableMergeDrawChannels(ImGuiTable* table); + inline ImGuiTableInstanceData* TableGetInstanceData(ImGuiTable* table, int instance_no) { if (instance_no == 0) return &table->InstanceDataFirst; return &table->InstanceDataExtra[instance_no - 1]; } + inline ImGuiID TableGetInstanceID(ImGuiTable* table, int instance_no) { return TableGetInstanceData(table, instance_no)->TableInstanceID; } + IMGUI_API void TableFixDisplayOrder(ImGuiTable* table); + IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); + IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); + IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column); + IMGUI_API void TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column); + IMGUI_API float TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column); + IMGUI_API void TableBeginRow(ImGuiTable* table); + IMGUI_API void TableEndRow(ImGuiTable* table); + IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); + IMGUI_API void TableEndCell(ImGuiTable* table); + IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable* table, int column_n); + IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n); + IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); + IMGUI_API float TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n); + IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n); + IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table); + IMGUI_API void TableRemove(ImGuiTable* table); + IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable* table); + IMGUI_API void TableGcCompactTransientBuffers(ImGuiTableTempData* table); + IMGUI_API void TableGcCompactSettings(); + + // Tables: Settings + IMGUI_API void TableLoadSettings(ImGuiTable* table); + IMGUI_API void TableSaveSettings(ImGuiTable* table); + IMGUI_API void TableResetSettings(ImGuiTable* table); + IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); + IMGUI_API void TableSettingsAddSettingsHandler(); + IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count); + IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id); + + // Tab Bars + inline ImGuiTabBar* GetCurrentTabBar() { ImGuiContext& g = *GImGui; return g.CurrentTabBar; } + IMGUI_API ImGuiTabBar* TabBarFindByID(ImGuiID id); + IMGUI_API void TabBarRemove(ImGuiTabBar* tab_bar); + IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); + IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); + IMGUI_API ImGuiTabItem* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order); + IMGUI_API ImGuiTabItem* TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar); + IMGUI_API ImGuiTabItem* TabBarGetCurrentTab(ImGuiTabBar* tab_bar); + inline int TabBarGetTabOrder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { return tab_bar->Tabs.index_from_ptr(tab); } + IMGUI_API const char* TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); + IMGUI_API void TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window); + IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); + IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); + IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); + IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name); + IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset); + IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); + IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); + IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); + IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width); + IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); + IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); + IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); + IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); + + // Render helpers + // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. + // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) + IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders = true, float rounding = 0.0f); + IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); + IMGUI_API void RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding); + IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); + IMGUI_API void RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None); // Navigation highlight +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None) { RenderNavCursor(bb, id, flags); } // Renamed in 1.91.4 +#endif + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); + + // Render helpers (those functions don't access any ImGui state!) + IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); + IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); + IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); + IMGUI_API void RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col); + IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding); + IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); + IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); + + // Widgets: Text + IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); + IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) + IMGUI_API void TextAlignedV(float align_x, float size_x, const char* fmt, va_list args); + + // Widgets + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); + IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f); + IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width); + IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value); + IMGUI_API bool CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value); + + // Widgets: Window Decorations + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); + IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node); + IMGUI_API void Scrollbar(ImGuiAxis axis); + IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags draw_rounding_flags = 0); + IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); + IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); + IMGUI_API ImGuiID GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners + IMGUI_API ImGuiID GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir); + + // Widgets low-level behaviors + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f, ImU32 bg_col = 0); + + // Widgets: Tree Nodes + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); + IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); + IMGUI_API void TreePushOverrideID(ImGuiID id); + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); + IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); + IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. + + // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. + // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). + // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " + template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); + template IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value); + + // Data type helpers + IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); + IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format); + IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2); + IMGUI_API bool DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty = NULL); + IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2); + IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); + IMGUI_API bool DataTypeIsZero(ImGuiDataType data_type, const void* p_data); + + // InputText + IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API void InputTextDeactivateHook(ImGuiID id); + IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); + inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return g.ActiveId == id && g.TempInputId == id; } + inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active + IMGUI_API void SetNextItemRefVal(ImGuiDataType data_type, void* p_data); + inline bool IsItemActiveAsInputText() { ImGuiContext& g = *GImGui; return g.ActiveId != 0 && g.ActiveId == g.LastItemData.ID && g.InputTextState.ID == g.LastItemData.ID; } // This may be useful to apply workaround that a based on distinguish whenever an item is active as a text input field. + + // Color + IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); + IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); + IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); + inline void SetNextItemColorMarker(ImU32 col) { ImGuiContext& g = *GImGui; g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasColorMarker; g.NextItemData.ColorMarker = col; } + + // Plot + IMGUI_API int PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, const ImVec2& size_arg); + + // Shade functions (write over already created vertices) + IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); + IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); + IMGUI_API void ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& pivot_in, float cos_a, float sin_a, const ImVec2& pivot_out); + + // Garbage collection + IMGUI_API void GcCompactTransientMiscBuffers(); + IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); + IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); + + // Error handling, State Recovery + IMGUI_API bool ErrorLog(const char* msg); + IMGUI_API void ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out); + IMGUI_API void ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in); + IMGUI_API void ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in); + IMGUI_API void ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); + IMGUI_API void ErrorCheckEndFrameFinalizeErrorTooltip(); + IMGUI_API bool BeginErrorTooltip(); + IMGUI_API void EndErrorTooltip(); + + // Debug Tools + IMGUI_API void DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free + IMGUI_API void DebugDrawCursorPos(ImU32 col = IM_COL32(255, 0, 0, 255)); + IMGUI_API void DebugDrawLineExtents(ImU32 col = IM_COL32(255, 0, 0, 255)); + IMGUI_API void DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255)); + IMGUI_API void DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end); + IMGUI_API void DebugLocateItem(ImGuiID target_id); // Call sparingly: only 1 at the same time! + IMGUI_API void DebugLocateItemOnHover(ImGuiID target_id); // Only call on reaction to a mouse Hover: because only 1 at the same time! + IMGUI_API void DebugLocateItemResolveWithLastItem(); + IMGUI_API void DebugBreakClearData(); + IMGUI_API bool DebugBreakButton(const char* label, const char* description_of_location); + IMGUI_API void DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location); + IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); + IMGUI_API ImU64 DebugTextureIDToU64(ImTextureID tex_id); + IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end); + IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); + IMGUI_API void DebugNodeDockNode(ImGuiDockNode* node, const char* label); + IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); + IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); + IMGUI_API void DebugNodeFont(ImFont* font); + IMGUI_API void DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask); + IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); + IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture. + IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); + IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); + IMGUI_API void DebugNodeTable(ImGuiTable* table); + IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings); + IMGUI_API void DebugNodeInputTextState(ImGuiInputTextState* state); + IMGUI_API void DebugNodeTypingSelectState(ImGuiTypingSelectState* state); + IMGUI_API void DebugNodeMultiSelectState(ImGuiMultiSelectState* state); + IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); + IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); + IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); + IMGUI_API void DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack); + IMGUI_API void DebugNodeViewport(ImGuiViewportP* viewport); + IMGUI_API void DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx); + IMGUI_API void DebugRenderKeyboardPreview(ImDrawList* draw_list); + IMGUI_API void DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb); + + // Obsolete functions +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //inline void SetItemUsingMouseWheel() { SetItemKeyOwner(ImGuiKey_MouseWheelY); } // Changed in 1.89 + //inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 + //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! + + // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): + // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' + // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' + // (New) IMGUI_VERSION_NUM >= 18413: using 'ItemAdd(..., ImGuiItemFlags_Inputable)' and 'bool tab_focused = (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))' + //inline bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id) // -> pass ImGuiItemAddFlags_Inputable flag to ItemAdd() + //inline void FocusableItemUnregister(ImGuiWindow* window) // -> unnecessary: TempInputText() uses ImGuiInputTextFlags_MergedItem +#endif + +} // namespace ImGui + + +//----------------------------------------------------------------------------- +// [SECTION] ImFontLoader +//----------------------------------------------------------------------------- + +// Hooks and storage for a given font backend. +// This structure is likely to evolve as we add support for incremental atlas updates. +// Conceptually this could be public, but API is still going to be evolve. +struct ImFontLoader +{ + const char* Name; + bool (*LoaderInit)(ImFontAtlas* atlas); + void (*LoaderShutdown)(ImFontAtlas* atlas); + bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); + void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); + bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); + + // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. + // FIXME: At this point the two other types of buffers may be managed by core to be consistent? + size_t FontBakedSrcLoaderDataSize; + + ImFontLoader() { memset(this, 0, sizeof(*this)); } +}; + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); +#endif +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92.0] The types are not actually compatible but we provide this as a compile-time error report helper. +#endif + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas internal API +//----------------------------------------------------------------------------- + +#define IMGUI_FONT_SIZE_MAX (512.0f) +#define IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE (128.0f) + +// Helpers: ImTextureRef ==/!= operators provided as convenience +// (note that _TexID and _TexData are never set simultaneously) +inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } + +// Refer to ImFontAtlasPackGetRect() to better understand how this works. +#define ImFontAtlasRectId_IndexMask_ (0x0007FFFF) // 20-bits signed: index to access builder->RectsIndex[]. +#define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. +#define ImFontAtlasRectId_GenerationShift_ (20) +inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_IndexMask_); } +inline unsigned int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (unsigned int)(id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } +inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx >= 0 && index_idx <= ImFontAtlasRectId_IndexMask_ && gen_idx <= (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } + +// Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) +// User are returned ImFontAtlasRectId values which are meant to be persistent. +// We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. +// RectsIndex[] is used both as an index into Rects[] and an index into itself. This is basically a free-list. See ImFontAtlasBuildAllocRectIndexEntry() code. +// Having this also makes it easier to e.g. sort rectangles during repack. +struct ImFontAtlasRectEntry +{ + int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + unsigned int Generation : 10; // Increased each time the entry is reused for a new rectangle. + unsigned int IsUsed : 1; +}; + +// Data available to potential texture post-processing functions +struct ImFontAtlasPostProcessData +{ + ImFontAtlas* FontAtlas; + ImFont* Font; + ImFontConfig* FontSrc; + ImFontBaked* FontBaked; + ImFontGlyph* Glyph; + + // Pixel data + void* Pixels; + ImTextureFormat Format; + int Pitch; + int Width; + int Height; +}; + +// We avoid dragging imstb_rectpack.h into public header (partly because binding generators are having issues with it) +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE { struct stbrp_node; } +typedef IMGUI_STB_NAMESPACE::stbrp_node stbrp_node_im; +#else +struct stbrp_node; +typedef stbrp_node stbrp_node_im; +#endif +struct stbrp_context_opaque { char data[80]; }; + +// Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasBuilder +{ + stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. + ImVector PackNodes; + ImVector Rects; + ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] + ImVector TempBuffer; // Misc scratch buffer + int RectsIndexFreeListStart;// First unused entry + int RectsPackedCount; // Number of packed rectangles. + int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. + int RectsDiscardedCount; + int RectsDiscardedSurface; + int FrameCount; // Current frame count + ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") + ImVec2i MaxRectBounds; // Bottom-right most used pixels + bool LockDisableResize; // Disable resizing texture + bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. + + // Cache of all ImFontBaked + ImStableVector BakedPool; + ImGuiStorage BakedMap; // BakedId --> ImFontBaked* + int BakedDiscardedCount; + + // Custom rectangle identifiers + ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. + ImFontAtlasRectId PackIdLinesTexData; + + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } +}; + +IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); +IMGUI_API void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font); +IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); +IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects + +IMGUI_API ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); +IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas); +IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas); + +IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); + +IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed +IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontRebuildOutput(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames); + +IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id); +IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); +IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x); +IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); +IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); + +IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); +IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); + +IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures); +IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); +IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); +IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); +IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); + +IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); +IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); +IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); +IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col); +IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); +IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); + +IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); +IMGUI_API const char* ImTextureDataGetStatusName(ImTextureStatus status); +IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format); + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); +#endif + +IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + +//----------------------------------------------------------------------------- +// [SECTION] Test Engine specific hooks (imgui_test_engine) +//----------------------------------------------------------------------------- + +#ifdef IMGUI_ENABLE_TEST_ENGINE +extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, ImGuiID id, const ImRect& bb, const ImGuiLastItemData* item_data); // item_data may be NULL +extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); +extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); +extern const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiID id); + +// In IMGUI_VERSION_NUM >= 18934: changed IMGUI_TEST_ENGINE_ITEM_ADD(bb,id) to IMGUI_TEST_ENGINE_ITEM_ADD(id,bb,item_data); +#define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _ID, _BB, _ITEM_DATA) // Register item bounding box +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) +#define IMGUI_TEST_ENGINE_LOG(_FMT,...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log +#else +#define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA) ((void)0) +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) ((void)g) +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui_tables.cpp b/libs/imgui/imgui_tables.cpp new file mode 100644 index 0000000..d4e57e8 --- /dev/null +++ b/libs/imgui/imgui_tables.cpp @@ -0,0 +1,4560 @@ +// dear imgui, v1.92.6 WIP +// (tables and columns code) + +/* + +Index of this file: + +// [SECTION] Commentary +// [SECTION] Header mess +// [SECTION] Tables: Main code +// [SECTION] Tables: Simple accessors +// [SECTION] Tables: Row changes +// [SECTION] Tables: Columns changes +// [SECTION] Tables: Columns width management +// [SECTION] Tables: Drawing +// [SECTION] Tables: Sorting +// [SECTION] Tables: Headers +// [SECTION] Tables: Context Menu +// [SECTION] Tables: Settings (.ini data) +// [SECTION] Tables: Garbage Collection +// [SECTION] Tables: Debugging +// [SECTION] Columns, BeginColumns, EndColumns, etc. + +*/ + +// Navigating this file: +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. + +//----------------------------------------------------------------------------- +// [SECTION] Commentary +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typical tables call flow: (root level is generally public API): +//----------------------------------------------------------------------------- +// - BeginTable() user begin into a table +// | BeginChild() - (if ScrollX/ScrollY is set) +// | TableBeginInitMemory() - first time table is used +// | TableResetSettings() - on settings reset +// | TableLoadSettings() - on settings load +// | TableBeginApplyRequests() - apply queued resizing/reordering/hiding requests +// | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) +// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width +// - TableSetupColumn() user submit columns details (optional) +// - TableSetupScrollFreeze() user submit scroll freeze information (optional) +//----------------------------------------------------------------------------- +// - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow(). +// | TableSetupDrawChannels() - setup ImDrawList channels +// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +// | TableBeginContextMenuPopup() +// | - TableDrawDefaultContextMenu() - draw right-click context menu contents +//----------------------------------------------------------------------------- +// - TableHeadersRow() or TableHeader() user submit a headers row (optional) +// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu +// - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) +// - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow()) +// | TableEndRow() - finish existing row +// | TableBeginRow() - add a new row +// - TableSetColumnIndex() / TableNextColumn() user begin into a cell +// | TableEndCell() - close existing column/cell +// | TableBeginCell() - enter into current column/cell +// - [...] user emit contents +//----------------------------------------------------------------------------- +// - EndTable() user ends the table +// | TableDrawBorders() - draw outer borders, inner vertical borders +// | TableMergeDrawChannels() - merge draw channels if clipping isn't required +// | EndChild() - (if ScrollX/ScrollY is set) +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// TABLE SIZING +//----------------------------------------------------------------------------- +// (Read carefully because this is subtle but it does make sense!) +//----------------------------------------------------------------------------- +// About 'outer_size': +// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags. +// Default value is ImVec2(0.0f, 0.0f). +// X +// - outer_size.x <= 0.0f -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge. +// - outer_size.x > 0.0f -> Set Fixed width. +// Y with ScrollX/ScrollY disabled: we output table directly in current window +// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll. +// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set) +// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set) +// Y with ScrollX/ScrollY enabled: using a child window for scrolling +// - outer_size.y < 0.0f -> Bottom-align. Not meaningful if parent window can vertically scroll. +// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window. +// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis. +//----------------------------------------------------------------------------- +// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags. +// Important to note how the two flags have slightly different behaviors! +// - ImGuiTableFlags_NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. +// - ImGuiTableFlags_NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible. +// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height. +// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable). +//----------------------------------------------------------------------------- +// About 'inner_width': +// With ScrollX disabled: +// - inner_width -> *ignored* +// With ScrollX enabled: +// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird +// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! +//----------------------------------------------------------------------------- +// Details: +// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +// of "available space" doesn't make sense. +// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +// of what the value does. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// COLUMNS SIZING POLICIES +// (Reference: ImGuiTableFlags_SizingXXX flags and ImGuiTableColumnFlags_WidthXXX flags) +//----------------------------------------------------------------------------- +// About overriding column sizing policy and width/weight with TableSetupColumn(): +// We use a default parameter of -1 for 'init_width'/'init_weight'. +// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic +// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom +// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f +// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom +// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f) +// and you can fit a 100.0f wide item in it without clipping and with padding honored. +//----------------------------------------------------------------------------- +// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag) +// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width +// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width +// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f +// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents +// Default Width and default Weight can be overridden when calling TableSetupColumn(). +//----------------------------------------------------------------------------- +// About mixing Fixed/Auto and Stretch columns together: +// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place! +// that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in. +// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents. +// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths. +//----------------------------------------------------------------------------- +// About using column width: +// If a column is manually resizable or has a width specified with TableSetupColumn(): +// - you may use GetContentRegionAvail().x to query the width available in a given column. +// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width. +// If the column is not resizable and has no width specified with TableSetupColumn(): +// - its width will be automatic and be set to the max of items submitted. +// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN). +// - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN). +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// TABLES CLIPPING/CULLING +//----------------------------------------------------------------------------- +// About clipping/culling of Rows in Tables: +// - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows. +// ImGuiListClipper is reliant on the fact that rows are of equal height. +// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper. +// - Note that auto-resizing columns don't play well with using the clipper. +// By default a table with _ScrollX but without _Resizable will have column auto-resize. +// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed. +//----------------------------------------------------------------------------- +// About clipping/culling of Columns in Tables: +// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing +// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know +// it is not going to contribute to row height. +// In many situations, you may skip submitting contents for every column but one (e.g. the first one). +// - Case A: column is not hidden by user, and at least partially in sight (most common case). +// - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output. +// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.). +// +// [A] [B] [C] +// TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() returns false, user can skip submitting items but only if the column doesn't contribute to row height. +// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output. +// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way. +// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway). +// +// - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row. +// However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer. +//----------------------------------------------------------------------------- +// About clipping/culling of whole Tables: +// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_internal.h" + +// System includes +#include // intptr_t + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wstrict-overflow" +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Tables: Main code +//----------------------------------------------------------------------------- +// - TableFixFlags() [Internal] +// - TableFindByID() [Internal] +// - BeginTable() +// - BeginTableEx() [Internal] +// - TableBeginInitMemory() [Internal] +// - TableBeginApplyRequests() [Internal] +// - TableSetupColumnFlags() [Internal] +// - TableUpdateLayout() [Internal] +// - TableUpdateBorders() [Internal] +// - EndTable() +// - TableSetupColumn() +// - TableSetupScrollFreeze() +//----------------------------------------------------------------------------- + +// Configuration +static const int TABLE_DRAW_CHANNEL_BG0 = 0; +static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1; +static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel) +static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering. +static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders. +static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. + +// Helper +inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window) +{ + // Adjust flags: set default sizing policy + if ((flags & ImGuiTableFlags_SizingMask_) == 0) + flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame; + + // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame + if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableFlags_NoKeepColumnsVisible; + + // Adjust flags: enforce borders when resizable + if (flags & ImGuiTableFlags_Resizable) + flags |= ImGuiTableFlags_BordersInnerV; + + // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on + if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) + flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY); + + // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody + if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize) + flags &= ~ImGuiTableFlags_NoBordersInBody; + + // Adjust flags: disable saved settings if there's nothing to save + if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0) + flags |= ImGuiTableFlags_NoSavedSettings; + + // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set) + if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings) + flags |= ImGuiTableFlags_NoSavedSettings; + + return flags; +} + +ImGuiTable* ImGui::TableFindByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.Tables.GetByKey(id); +} + +// Read about "TABLE SIZING" at the top of this file. +bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiID id = GetID(str_id); + return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width); +} + +bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* outer_window = GetCurrentWindow(); + if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible. + return false; + + // Sanity checks + IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS); + if (flags & ImGuiTableFlags_ScrollX) + IM_ASSERT(inner_width >= 0.0f); + + // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve. + // FIXME: coarse clipping because access to table data causes two issues: + // - instance numbers varying/unstable. may not be a direct problem for users, but could make outside access broken or confusing, e.g. TestEngine. + // - can't implement support for ImGuiChildFlags_ResizeY as we need to somehow pull the height data from somewhere. this also needs stable instance numbers. + // The side-effects of accessing table data on coarse clip would be: + // - always reserving the pooled ImGuiTable data ahead for a fully clipped table (minor IMHO). Also the 'outer_window_is_measuring_size' criteria may already be defeating this in some situations. + // - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. + const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0; + const ImVec2 avail_size = GetContentRegionAvail(); + const ImVec2 actual_outer_size = ImTrunc(CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window ? ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) : 0.0f)); + const ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size); + const bool outer_window_is_measuring_size = (outer_window->AutoFitFramesX > 0) || (outer_window->AutoFitFramesY > 0); // Doesn't apply to AlwaysAutoResize windows! + if (use_child_window && IsClippedEx(outer_rect, 0) && !outer_window_is_measuring_size) + { + ItemSize(outer_rect); + ItemAdd(outer_rect, id); + g.NextWindowData.ClearFlags(); + return false; + } + + // [DEBUG] Debug break requested by user + if (g.DebugBreakInTable == id) + IM_DEBUG_BREAK(); + + // Acquire storage for the table + ImGuiTable* table = g.Tables.GetOrAddByKey(id); + + // Acquire temporary buffers + const int table_idx = g.Tables.GetIndex(table); + if (++g.TablesTempDataStacked > g.TablesTempData.Size) + g.TablesTempData.resize(g.TablesTempDataStacked, ImGuiTableTempData()); + ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempData[g.TablesTempDataStacked - 1]; + temp_data->TableIndex = table_idx; + table->DrawSplitter = &table->TempData->DrawSplitter; + table->DrawSplitter->Clear(); + + // Fix flags + table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0; + flags = TableFixFlags(flags, outer_window); + + // Initialize + const int previous_frame_active = table->LastFrameActive; + const int instance_no = (previous_frame_active != g.FrameCount) ? 0 : table->InstanceCurrent + 1; + const ImGuiTableFlags previous_flags = table->Flags; + table->ID = id; + table->Flags = flags; + table->LastFrameActive = g.FrameCount; + table->OuterWindow = table->InnerWindow = outer_window; + table->ColumnsCount = columns_count; + table->IsLayoutLocked = false; + table->InnerWidth = inner_width; + table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent; + temp_data->UserOuterSize = outer_size; + + // Instance data (for instance 0, TableID == TableInstanceID) + ImGuiID instance_id; + table->InstanceCurrent = (ImS16)instance_no; + if (instance_no > 0) + { + IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID"); + if (table->InstanceDataExtra.Size < instance_no) + table->InstanceDataExtra.push_back(ImGuiTableInstanceData()); + instance_id = GetIDWithSeed(instance_no, GetIDWithSeed("##Instances", NULL, id)); // Push "##Instances" followed by (int)instance_no in ID stack. + } + else + { + instance_id = id; + } + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + table_instance->TableInstanceID = instance_id; + + // When not using a child window, WorkRect.Max will grow as we append contents. + if (use_child_window) + { + // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) + ImVec2 override_content_size(FLT_MAX, FLT_MAX); + if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY)) + override_content_size.y = FLT_MIN; + + // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align + // based on the right side of the child window work rect, which would require knowing ahead if we are going to + // have decoration taking horizontal spaces (typically a vertical scrollbar). + if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f) + override_content_size.x = inner_width; + + if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX) + SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f)); + + // Reset scroll if we are reactivating it + if ((previous_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) == 0) + SetNextWindowScroll(ImVec2(0.0f, 0.0f)); + + // Create scrolling region (without border and zero window padding) + ImGuiChildFlags child_child_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : ImGuiChildFlags_None; + ImGuiWindowFlags child_window_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowFlags) ? g.NextWindowData.WindowFlags : ImGuiWindowFlags_None; + if (flags & ImGuiTableFlags_ScrollX) + child_window_flags |= ImGuiWindowFlags_HorizontalScrollbar; + BeginChildEx(name, instance_id, outer_rect.GetSize(), child_child_flags, child_window_flags); + table->InnerWindow = g.CurrentWindow; + table->WorkRect = table->InnerWindow->WorkRect; + table->OuterRect = table->InnerWindow->Rect(); + table->InnerRect = table->InnerWindow->InnerRect; + IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f); + + // Allow submitting when host is measuring + if (table->InnerWindow->SkipItems && outer_window_is_measuring_size) + table->InnerWindow->SkipItems = false; + + // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned + if (instance_no == 0) + { + table->HasScrollbarYPrev = table->HasScrollbarYCurr; + table->HasScrollbarYCurr = false; + } + table->HasScrollbarYCurr |= table->InnerWindow->ScrollbarY; + } + else + { + // For non-scrolling tables, WorkRect == OuterRect == InnerRect. + // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). + table->WorkRect = table->OuterRect = table->InnerRect = outer_rect; + table->HasScrollbarYPrev = table->HasScrollbarYCurr = false; + table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table + } + + // Push a standardized ID for both child-using and not-child-using tables + PushOverrideID(id); + if (instance_no > 0) + PushOverrideID(instance_id); // FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol. + + // Backup a copy of host window members we will modify + ImGuiWindow* inner_window = table->InnerWindow; + table->HostIndentX = inner_window->DC.Indent.x; + table->HostClipRect = inner_window->ClipRect; + table->HostSkipItems = inner_window->SkipItems; + temp_data->WindowID = inner_window->ID; + temp_data->HostBackupWorkRect = inner_window->WorkRect; + temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect; + temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset; + temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize; + temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize; + temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos; + temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth; + temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; + inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + + // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) + // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + // problem only affect scrolling tables in this case we can get away with doing it without extra cost). + if (inner_window != outer_window) + { + // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, + // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + // different x/y values to BeginChild(). + if (flags & ImGuiTableFlags_BordersOuterV) + { + table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + TABLE_BORDER_SIZE, table->HostClipRect.Max.x); + if (inner_window->DecoOuterSizeX2 == 0.0f) + table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - TABLE_BORDER_SIZE, table->HostClipRect.Min.x); + } + if (flags & ImGuiTableFlags_BordersOuterH) + { + table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + TABLE_BORDER_SIZE, table->HostClipRect.Max.y); + if (inner_window->DecoOuterSizeY2 == 0.0f) + table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - TABLE_BORDER_SIZE, table->HostClipRect.Min.y); + } + } + + // Padding and Spacing + // - None ........Content..... Pad .....Content........ + // - PadOuter | Pad ..Content..... Pad .....Content.. Pad | + // - PadInner ........Content.. Pad | Pad ..Content........ + // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | + const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0; + const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true; + const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f; + const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f; + const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f; + table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border; + table->CellSpacingX2 = inner_spacing_explicit; + table->CellPaddingX = inner_padding_explicit; + + const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; + table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; + + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWithFull(table->HostClipRect); + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : table->HostClipRect.Max.y; + + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow + table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() + table->RowCellPaddingY = 0.0f; + table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any + table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; + table->IsUnfrozenRows = true; + table->DeclColumnsCount = table->AngledHeadersCount = 0; + if (previous_frame_active + 1 < g.FrameCount) + table->IsActiveIdInTable = false; + table->AngledHeadersHeight = 0.0f; + temp_data->AngledHeadersExtraWidth = 0.0f; + + // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders() + table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); + table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); + + // Make table current + g.CurrentTable = table; + inner_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX(); + outer_window->DC.CurrentTableIdx = table_idx; + if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly. + inner_window->DC.CurrentTableIdx = table_idx; + + if ((previous_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0) + table->IsResetDisplayOrderRequest = true; + + // Mark as used to avoid GC + if (table_idx >= g.TablesLastTimeActive.Size) + g.TablesLastTimeActive.resize(table_idx + 1, -1.0f); + g.TablesLastTimeActive[table_idx] = (float)g.Time; + temp_data->LastTimeActive = (float)g.Time; + table->MemoryCompacted = false; + + // Setup memory buffer (clear data if columns count changed) + ImGuiTableColumn* old_columns_to_preserve = NULL; + void* old_columns_raw_data = NULL; + const int old_columns_count = table->Columns.size(); + if (old_columns_count != 0 && old_columns_count != columns_count) + { + // Attempt to preserve width and other settings on column count/specs change (#4046) + old_columns_to_preserve = table->Columns.Data; + old_columns_raw_data = table->RawData; // Free at end of function + table->RawData = NULL; + } + if (table->RawData == NULL) + { + TableBeginInitMemory(table, columns_count); + table->IsInitializing = table->IsSettingsRequestLoad = true; + } + if (table->IsResetAllRequest) + TableResetSettings(table); + if (table->IsInitializing) + { + // Initialize + table->SettingsOffset = -1; + table->IsSortSpecsDirty = true; + table->IsSettingsDirty = true; // Records itself into .ini file even when in default state (#7934) + table->InstanceInteracted = -1; + table->ContextPopupColumn = -1; + table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1; + table->AutoFitSingleColumn = -1; + table->HoveredColumnBody = table->HoveredColumnBorder = -1; + for (int n = 0; n < columns_count; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + if (old_columns_to_preserve && n < old_columns_count) + { + *column = old_columns_to_preserve[n]; + } + else + { + float width_auto = column->WidthAuto; + *column = ImGuiTableColumn(); + column->WidthAuto = width_auto; + column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker + column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true; + column->DisplayOrder = (ImGuiTableColumnIdx)n; + } + table->DisplayOrderToIndex[n] = column->DisplayOrder; + } + } + if (old_columns_raw_data) + IM_FREE(old_columns_raw_data); + + // Load settings + if (table->IsSettingsRequestLoad) + TableLoadSettings(table); + + // Handle DPI/font resize + // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ? + if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit) + { + const float scale_factor = new_ref_scale_unit / table->RefScale; + //IMGUI_DEBUG_PRINT("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor); + for (int n = 0; n < columns_count; n++) + table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor; + } + table->RefScale = new_ref_scale_unit; + + // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. + // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. + // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. + inner_window->SkipItems = true; + + // Clear names + // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn() + if (table->ColumnsNames.Buf.Size > 0) + table->ColumnsNames.Buf.resize(0); + + // Apply queued resizing/reordering/hiding requests + TableBeginApplyRequests(table); + + return true; +} + +// For reference, the average total _allocation count_ for a table is: +// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables[]) +// + 1 (for table->RawData allocated below) +// + 1 (for table->ColumnsNames, if names are used) +// Shared allocations for the maximum number of simultaneously nested tables (generally a very small number) +// + 1 (for table->Splitter._Channels) +// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels) +// Where active_channels_count is variable but often == columns_count or == columns_count + 1, see TableSetupDrawChannels() for details. +// Unused channels don't perform their +2 allocations. +void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count) +{ + // Allocate single buffer for our arrays + const int columns_bit_array_size = (int)ImBitArrayGetStorageSizeInBytes(columns_count); + ImSpanAllocator<6> span_allocator; + span_allocator.Reserve(0, columns_count * sizeof(ImGuiTableColumn)); + span_allocator.Reserve(1, columns_count * sizeof(ImGuiTableColumnIdx)); + span_allocator.Reserve(2, columns_count * sizeof(ImGuiTableCellData), 4); + for (int n = 3; n < 6; n++) + span_allocator.Reserve(n, columns_bit_array_size); + table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes()); + memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes()); + span_allocator.SetArenaBasePtr(table->RawData); + span_allocator.GetSpan(0, &table->Columns); + span_allocator.GetSpan(1, &table->DisplayOrderToIndex); + span_allocator.GetSpan(2, &table->RowCellData); + table->EnabledMaskByDisplayOrder = (ImU32*)span_allocator.GetSpanPtrBegin(3); + table->EnabledMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(4); + table->VisibleMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(5); +} + +// Apply queued resizing/reordering/hiding requests +void ImGui::TableBeginApplyRequests(ImGuiTable* table) +{ + // Handle resizing request + // (We process this in the TableBegin() of the first instance of each table) + // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling? + if (table->InstanceCurrent == 0) + { + if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX) + TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth); + table->LastResizedColumn = table->ResizedColumn; + table->ResizedColumnNextWidth = FLT_MAX; + table->ResizedColumn = -1; + + // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy. + // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings. + if (table->AutoFitSingleColumn != -1) + { + TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto); + table->AutoFitSingleColumn = -1; + } + } + + // Handle reordering request + // Note: we don't clear ReorderColumn after handling the request. + if (table->InstanceCurrent == 0) + { + if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1) + table->ReorderColumn = -1; + table->HeldHeaderColumn = -1; + if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) + { + // We need to handle reordering across hidden columns. + // In the configuration below, moving C to the right of E will lead to: + // ... C [D] E ---> ... [D] E C (Column name/index) + // ... 2 3 4 ... 2 3 4 (Display order) + const int reorder_dir = table->ReorderColumnDir; + IM_ASSERT(reorder_dir == -1 || reorder_dir == +1); + IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); + ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; + ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn]; + IM_UNUSED(dst_column); + const int src_order = src_column->DisplayOrder; + const int dst_order = dst_column->DisplayOrder; + src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order; + for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) + table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir; + IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); + + // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; + table->ReorderColumnDir = 0; + table->IsSettingsDirty = true; + } + } + + // Handle display order reset request + if (table->IsResetDisplayOrderRequest) + { + for (int n = 0; n < table->ColumnsCount; n++) + table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; + table->IsResetDisplayOrderRequest = false; + table->IsSettingsDirty = true; + } +} + +// Adjust flags: default width mode + stretch columns are not allowed when auto extending +static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in) +{ + ImGuiTableColumnFlags flags = flags_in; + + // Sizing Policy + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) + { + const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_); + if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableColumnFlags_WidthFixed; + else + flags |= ImGuiTableColumnFlags_WidthStretch; + } + else + { + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used. + } + + // Resize + if ((table->Flags & ImGuiTableFlags_Resizable) == 0) + flags |= ImGuiTableColumnFlags_NoResize; + + // Sorting + if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending)) + flags |= ImGuiTableColumnFlags_NoSort; + + // Indentation + if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0) + flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable; + + // Alignment + //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0) + // flags |= ImGuiTableColumnFlags_AlignCenter; + //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used. + + // Preserve status flags + column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_); + + // Build an ordered list of available sort directions + column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0; + if (table->Flags & ImGuiTableFlags_Sortable) + { + int count = 0, mask = 0, list = 0; + if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; } + if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; } + column->SortDirectionsAvailList = (ImU8)list; + column->SortDirectionsAvailMask = (ImU8)mask; + column->SortDirectionsAvailCount = (ImU8)count; + ImGui::TableFixColumnSortDirection(table, column); + } +} + +// Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function. +// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. +// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. +// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? +void ImGui::TableUpdateLayout(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(table->IsLayoutLocked == false); + + const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_); + table->IsDefaultDisplayOrder = true; + table->ColumnsEnabledCount = 0; + ImBitArrayClearAllBits(table->EnabledMaskByIndex, table->ColumnsCount); + ImBitArrayClearAllBits(table->EnabledMaskByDisplayOrder, table->ColumnsCount); + table->LeftMostEnabledColumn = -1; + table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE + + // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns. + // Process columns in their visible orders as we are building the Prev/Next indices. + int count_fixed = 0; // Number of columns that have fixed sizing policies + int count_stretch = 0; // Number of columns that have stretch sizing policies + int prev_visible_column_idx = -1; + bool has_auto_fit_request = false; + bool has_resizable = false; + float stretch_sum_width_auto = 0.0f; + float fixed_max_width_auto = 0.0f; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrderToIndex[order_n]; + if (column_n != order_n) + table->IsDefaultDisplayOrder = false; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame. + // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway. + // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect. + if (table->DeclColumnsCount <= column_n) + { + TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None); + column->NameOffset = -1; + column->UserID = 0; + column->InitStretchWeightOrWidth = -1.0f; + } + + // Update Enabled state, mark settings and sort specs dirty + if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide)) + column->IsUserEnabledNextFrame = true; + if (column->IsUserEnabled != column->IsUserEnabledNextFrame) + { + column->IsUserEnabled = column->IsUserEnabledNextFrame; + table->IsSettingsDirty = true; + } + column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0; + + if (column->SortOrder != -1 && !column->IsEnabled) + table->IsSortSpecsDirty = true; + if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti)) + table->IsSortSpecsDirty = true; + + // Auto-fit unsized columns + const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f); + if (start_auto_fit) + column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames + + if (!column->IsEnabled) + { + column->IndexWithinEnabledSet = -1; + continue; + } + + // Mark as enabled and link to previous/next enabled column + column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx; + column->NextEnabledColumn = -1; + if (prev_visible_column_idx != -1) + table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n; + else + table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n; + column->IndexWithinEnabledSet = table->ColumnsEnabledCount++; + ImBitArraySetBit(table->EnabledMaskByIndex, column_n); + ImBitArraySetBit(table->EnabledMaskByDisplayOrder, column->DisplayOrder); + prev_visible_column_idx = column_n; + IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder); + + // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping) + // Combine width from regular rows + width from headers unless requested not to. + if (!column->IsPreserveWidthAuto && table->InstanceCurrent == 0) + column->WidthAuto = TableGetColumnWidthAuto(table, column); + + // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto) + const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0; + if (column_is_resizable) + has_resizable = true; + if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable) + column->WidthAuto = column->InitStretchWeightOrWidth; + + if (column->AutoFitQueue != 0x00) + has_auto_fit_request = true; + if (column->Flags & ImGuiTableColumnFlags_WidthStretch) + { + stretch_sum_width_auto += column->WidthAuto; + count_stretch++; + } + else + { + fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto); + count_fixed++; + } + } + if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate)) + table->IsSortSpecsDirty = true; + table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx; + IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0); + + // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid + // the column fitting having to wait until the first visible frame of the child container (may or not be a good thing). Also see #6510. + // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time. + if (has_auto_fit_request && table->OuterWindow != table->InnerWindow) + table->InnerWindow->SkipItems = false; + if (has_auto_fit_request) + table->IsSettingsDirty = true; + + // [Part 3] Fix column flags and record a few extra information. + float sum_width_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding. + float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns. + table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0; + if (column->Flags & ImGuiTableColumnFlags_WidthFixed) + { + // Apply same widths policy + float width_auto = column->WidthAuto; + if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable)) + width_auto = fixed_max_width_auto; + + // Apply automatic width + // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) + if (column->AutoFitQueue != 0x00) + column->WidthRequest = width_auto; + else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && column->IsRequestOutput) + column->WidthRequest = width_auto; + + // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + // large height (= first frame scrollbar display very off + clipper would skip lots of items). + // This is merely making the side-effect less extreme, but doesn't properly fixes it. + // FIXME: Move this to ->WidthGiven to avoid temporary lossyness? + // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. + if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto) + column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale? + sum_width_requests += column->WidthRequest; + } + else + { + // Initialize stretch weight + if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable) + { + if (column->InitStretchWeightOrWidth > 0.0f) + column->StretchWeight = column->InitStretchWeightOrWidth; + else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp) + column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch; + else + column->StretchWeight = 1.0f; + } + + stretch_sum_weights += column->StretchWeight; + if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder) + table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n; + if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder) + table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n; + } + column->IsPreserveWidthAuto = false; + sum_width_requests += table->CellPaddingX * 2.0f; + } + table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed; + table->ColumnsStretchSumWeights = stretch_sum_weights; + + // [Part 4] Apply final widths based on requested widths + const ImRect work_rect = table->WorkRect; + const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1); + const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synced tables with mismatching scrollbar state (#5920) + const float width_avail = ImMax(1.0f, (((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth()) - width_removed); + const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests; + float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; + table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest) + if (column->Flags & ImGuiTableColumnFlags_WidthStretch) + { + float weight_ratio = column->StretchWeight / stretch_sum_weights; + column->WidthRequest = IM_TRUNC(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f); + width_remaining_for_stretched_columns -= column->WidthRequest; + } + + // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + // See additional comments in TableSetColumnWidth(). + if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1) + column->Flags |= ImGuiTableColumnFlags_NoDirectResize_; + + // Assign final width, record width in case we will need to shrink + column->WidthGiven = ImTrunc(ImMax(column->WidthRequest, table->MinColumnWidth)); + table->ColumnsGivenWidth += column->WidthGiven; + } + + // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + // Using right-to-left distribution (more likely to match resizing cursor). + if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths)) + for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) + { + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n)) + continue; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; + if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->WidthRequest += 1.0f; + column->WidthGiven += 1.0f; + width_remaining_for_stretched_columns -= 1.0f; + } + + // Determine if table is hovered which will be used to flag columns as hovered. + // - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + // but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily + // clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem). + // - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop. + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + table_instance->HoveredRowLast = table_instance->HoveredRowNext; + table_instance->HoveredRowNext = -1; + table->HoveredColumnBody = table->HoveredColumnBorder = -1; + const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table_instance->LastOuterHeight)); + const ImGuiID backup_active_id = g.ActiveId; + g.ActiveId = 0; + const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0, ImGuiItemFlags_None); + g.ActiveId = backup_active_id; + + // Determine skewed MousePos.x to support angled headers. + float mouse_skewed_x = g.IO.MousePos.x; + if (table->AngledHeadersHeight > 0.0f) + if (g.IO.MousePos.y >= table->OuterRect.Min.y && g.IO.MousePos.y <= table->OuterRect.Min.y + table->AngledHeadersHeight) + mouse_skewed_x += ImTrunc((table->OuterRect.Min.y + table->AngledHeadersHeight - g.IO.MousePos.y) * table->AngledHeadersSlope); + + // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column + // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping. + int visible_n = 0; + bool has_at_least_one_column_requesting_output = false; + bool offset_x_frozen = (table->FreezeColumnsCount > 0); + float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1; + ImRect host_clip_rect = table->InnerClipRect; + //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2; + ImBitArrayClearAllBits(table->VisibleMaskByIndex, table->ColumnsCount); + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Initial nav layer: using FreezeRowsCount, NOT FreezeRowsRequest, so Header line changes layer when frozen + column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : (ImGuiNavLayer)table->NavLayer); + + if (offset_x_frozen && table->FreezeColumnsCount == visible_n) + { + offset_x += work_rect.Min.x - table->OuterRect.Min.x; + offset_x_frozen = false; + } + + // Clear status flags + column->Flags &= ~ImGuiTableColumnFlags_StatusMask_; + + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n)) + { + // Hidden column: clear a few fields and we are done with it for the remainder of the function. + // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. + column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x; + column->WidthGiven = 0.0f; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false; + column->IsSkipItems = true; + column->ItemWidth = 1.0f; + continue; + } + + // Lock start position + column->MinX = offset_x; + + // Lock width based on start position and minimum/maximum width for this position + column->WidthMax = TableCalcMaxColumnWidth(table, column_n); + column->WidthGiven = ImMin(column->WidthGiven, column->WidthMax); + column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth)); + column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; + + // Lock other positions + // - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging. + // - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column. + // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow. + // - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter. + const float previous_instance_work_min_x = column->WorkMinX; + column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1; + column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max + column->ItemWidth = ImTrunc(column->WidthGiven * 0.65f); + column->ClipRect.Min.x = column->MinX; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + + // Mark column as Clipped (not in sight) + // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables. + // FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window->ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY. + // Taking advantage of LastOuterHeight would yield good results there... + // FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window->DC.CursorMaxPos.x, + // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else). + // Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small. + column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x); + column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y); + const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY; + if (is_visible) + ImBitArraySetBit(table->VisibleMaskByIndex, column_n); + + // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output. + column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0; + + // Mark column as SkipItems (ignoring all items/layout) + // (table->HostSkipItems is a copy of inner_window->SkipItems before we cleared it above in Part 2) + column->IsSkipItems = !column->IsEnabled || table->HostSkipItems; + if (column->IsSkipItems) + IM_ASSERT(!is_visible); + if (column->IsRequestOutput && !column->IsSkipItems) + has_at_least_one_column_requesting_output = true; + + // Update status flags + column->Flags |= ImGuiTableColumnFlags_IsEnabled; + if (is_visible) + column->Flags |= ImGuiTableColumnFlags_IsVisible; + if (column->SortOrder != -1) + column->Flags |= ImGuiTableColumnFlags_IsSorted; + + // Detect hovered column + if (is_hovering_table && mouse_skewed_x >= column->ClipRect.Min.x && mouse_skewed_x < column->ClipRect.Max.x) + { + column->Flags |= ImGuiTableColumnFlags_IsHovered; + table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n; + } + + // Alignment + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + // many cases (to be able to honor this we might be able to store a log of cells width, per row, for + // visible rows, but nav/programmatic scroll would have visible artifacts.) + //if (column->Flags & ImGuiTableColumnFlags_AlignRight) + // column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen); + //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) + // column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f); + + // Reset content width variables + if (table->InstanceCurrent == 0) + { + column->ContentMaxXFrozen = column->WorkMinX; + column->ContentMaxXUnfrozen = column->WorkMinX; + column->ContentMaxXHeadersUsed = column->WorkMinX; + column->ContentMaxXHeadersIdeal = column->WorkMinX; + } + else + { + // As we store an absolute value to make per-cell updates faster, we need to offset values used for width computation. + const float offset_from_previous_instance = column->WorkMinX - previous_instance_work_min_x; + column->ContentMaxXFrozen += offset_from_previous_instance; + column->ContentMaxXUnfrozen += offset_from_previous_instance; + column->ContentMaxXHeadersUsed += offset_from_previous_instance; + column->ContentMaxXHeadersIdeal += offset_from_previous_instance; + } + + // Don't decrement auto-fit counters until container window got a chance to submit its items + if (table->HostSkipItems == false && table->InstanceCurrent == 0) + { + column->AutoFitQueue >>= 1; + column->CannotSkipItemsQueue >>= 1; + } + + if (visible_n < table->FreezeColumnsCount) + host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x); + + offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; + visible_n++; + } + + // In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible. + // Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar. + if (has_at_least_one_column_requesting_output == false) + { + table->Columns[table->LeftMostEnabledColumn].IsRequestOutput = true; + table->Columns[table->LeftMostEnabledColumn].IsSkipItems = false; + } + + // [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either + // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu. + const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x); + if (is_hovering_table && table->HoveredColumnBody == -1) + if (mouse_skewed_x >= unused_x1) + table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount; + if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable)) + table->Flags &= ~ImGuiTableFlags_Resizable; + + table->IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive != 0); + + // [Part 8] Lock actual OuterRect/WorkRect right-most position. + // This is done late to handle the case of fixed-columns tables not claiming more widths that they need. + // Because of this we are careful with uses of WorkRect and InnerClipRect before this point. + if (table->RightMostStretchedColumn != -1) + table->Flags &= ~ImGuiTableFlags_NoHostExtendX; + if (table->Flags & ImGuiTableFlags_NoHostExtendX) + { + table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1; + table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1); + } + table->InnerWindow->ParentWorkRect = table->WorkRect; + table->BorderX1 = table->InnerClipRect.Min.x; + table->BorderX2 = table->InnerClipRect.Max.x; + + // Setup window's WorkRect.Max.y for GetContentRegionAvail(). Other values will be updated in each TableBeginCell() call. + float window_content_max_y; + if (table->Flags & ImGuiTableFlags_NoHostExtendY) + window_content_max_y = table->OuterRect.Max.y; + else + window_content_max_y = ImMax(table->InnerWindow->ContentRegionRect.Max.y, (table->Flags & ImGuiTableFlags_ScrollY) ? 0.0f : table->OuterRect.Max.y); + table->InnerWindow->WorkRect.Max.y = ImClamp(window_content_max_y - g.Style.CellPadding.y, table->InnerWindow->WorkRect.Min.y, table->InnerWindow->WorkRect.Max.y); + + // [Part 9] Allocate draw channels and setup background cliprect + TableSetupDrawChannels(table); + + // [Part 10] Hit testing on borders + if (table->Flags & ImGuiTableFlags_Resizable) + TableUpdateBorders(table); + table_instance->LastTopHeadersRowHeight = 0.0f; + table->IsLayoutLocked = true; + table->IsUsingHeaders = false; + + // Highlight header + table->HighlightColumnHeader = -1; + if (table->IsContextPopupOpen && table->ContextPopupColumn != -1 && table->InstanceInteracted == table->InstanceCurrent) + table->HighlightColumnHeader = table->ContextPopupColumn; + else if ((table->Flags & ImGuiTableFlags_HighlightHoveredColumn) && table->HoveredColumnBody != -1 && table->HoveredColumnBody != table->ColumnsCount && table->HoveredColumnBorder == -1) + if (g.ActiveId == 0 || (table->IsActiveIdInTable || g.DragDropActive)) + table->HighlightColumnHeader = table->HoveredColumnBody; + + // [Part 11] Default context menu + // - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup(). + // - To modify or replace this: set table->DisableDefaultContextMenu = true, then call TableBeginContextMenuPopup()/.../EndPopup(). + // - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu, + // e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options. + if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table)) + { + TableDrawDefaultContextMenu(table, table->Flags); + EndPopup(); + } + + // [Part 12] Sanitize and build sort specs before we have a chance to use them for display. + // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) + if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable)) + TableSortSpecsBuild(table); + + // [Part 13] Setup inner window decoration size (for scrolling / nav tracking to properly take account of frozen rows/columns) + if (table->FreezeColumnsRequest > 0) + table->InnerWindow->DecoInnerSizeX1 = table->Columns[table->DisplayOrderToIndex[table->FreezeColumnsRequest - 1]].MaxX - table->OuterRect.Min.x; + if (table->FreezeRowsRequest > 0) + table->InnerWindow->DecoInnerSizeY1 = table_instance->LastFrozenHeight; + table_instance->LastFrozenHeight = 0.0f; + + // Initial state + ImGuiWindow* inner_window = table->InnerWindow; + if (table->Flags & ImGuiTableFlags_NoClip) + table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP); + else + inner_window->DrawList->PushClipRect(inner_window->InnerClipRect.Min, inner_window->InnerClipRect.Max, false); // FIXME: use table->InnerClipRect? +} + +// Process hit-testing on resizing borders. Actual size change will be applied in EndTable() +// - Set table->HoveredColumnBorder with a short delay/timer to reduce visual feedback noise. +void ImGui::TableUpdateBorders(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable); + + // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). + // Actual columns highlight/render will be performed in EndTable() and not be affected. + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + const float hit_half_width = ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale); + const float hit_y1 = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight; + const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table_instance->LastOuterHeight - table->AngledHeadersHeight); + const float hit_y2_head = hit_y1 + table_instance->LastTopHeadersRowHeight; + + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n)) + continue; + + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) + continue; + + // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body; + if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false) + continue; + + if (!column->IsVisibleX && table->LastResizedColumn != column_n) + continue; + + ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent); + ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit); + ItemAdd(hit_rect, column_id, NULL, ImGuiItemFlags_NoNav); + //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); + + bool hovered = false, held = false; + bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_NoNavFocus); + if (pressed && IsMouseDoubleClicked(0)) + { + TableSetColumnWidthAutoSingle(table, column_n); + ClearActiveID(); + held = false; + } + if (held) + { + if (table->LastResizedColumn == -1) + table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX; + table->ResizedColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + } + if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held) + { + table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n; + SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } + } +} + +void ImGui::EndTable() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "EndTable() call should only be done while in BeginTable() scope!"); + + // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?"); + + // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our + // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + const ImGuiTableFlags flags = table->Flags; + ImGuiWindow* inner_window = table->InnerWindow; + ImGuiWindow* outer_window = table->OuterWindow; + ImGuiTableTempData* temp_data = table->TempData; + IM_ASSERT(inner_window == g.CurrentWindow && inner_window->ID == temp_data->WindowID); + IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow); + + if (table->IsInsideRow) + TableEndRow(table); + + // Context menu in columns body + if (flags & ImGuiTableFlags_ContextMenuInBody) + if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) + TableOpenContextMenu((int)table->HoveredColumnBody); + + // Finalize table height + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; + inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; + inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; + const float inner_content_max_y = ImCeil(table->RowPosY2); // Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) + IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y); + if (inner_window != outer_window) + inner_window->DC.CursorMaxPos.y = inner_content_max_y; + else if (!(flags & ImGuiTableFlags_NoHostExtendY)) + table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height + table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y); + table_instance->LastOuterHeight = table->OuterRect.GetHeight(); + + // Setup inner scrolling range + // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y, + // but since the later is likely to be impossible to do we'd rather update both axes together. + if (table->Flags & ImGuiTableFlags_ScrollX) + { + const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x; + if (table->RightMostEnabledColumn != -1) + max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); + if (table->ResizedColumn != -1) + max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2); + table->InnerWindow->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledHeadersExtraWidth; + } + + // Pop clipping rect + if (!(flags & ImGuiTableFlags_NoClip)) + inner_window->DrawList->PopClipRect(); + inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back(); + + // Draw borders + if ((flags & ImGuiTableFlags_Borders) != 0) + TableDrawBorders(table); + +#if 0 + // Strip out dummy channel draw calls + // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out) + // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway. + // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices. + if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1) + { + ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel]; + dummy_channel->_CmdBuffer.resize(0); + dummy_channel->_IdxBuffer.resize(0); + } +#endif + + // Flatten channels and merge draw calls + ImDrawListSplitter* splitter = table->DrawSplitter; + splitter->SetCurrentChannel(inner_window->DrawList, 0); + if ((table->Flags & ImGuiTableFlags_NoClip) == 0) + TableMergeDrawChannels(table); + splitter->Merge(inner_window->DrawList); + + // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable() + float auto_fit_width_for_fixed = 0.0f; + float auto_fit_width_for_stretched = 0.0f; + float auto_fit_width_for_stretched_min = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + float column_width_request = ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize)) ? column->WidthRequest : TableGetColumnWidthAuto(table, column); + if (column->Flags & ImGuiTableColumnFlags_WidthFixed) + auto_fit_width_for_fixed += column_width_request; + else + auto_fit_width_for_stretched += column_width_request; + if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->Flags & ImGuiTableColumnFlags_NoResize) != 0) + auto_fit_width_for_stretched_min = ImMax(auto_fit_width_for_stretched_min, column_width_request / (column->StretchWeight / table->ColumnsStretchSumWeights)); + } + const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1); + table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount + auto_fit_width_for_fixed + ImMax(auto_fit_width_for_stretched, auto_fit_width_for_stretched_min); + + // Update scroll + if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window) + { + inner_window->Scroll.x = 0.0f; + } + else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent) + { + // When releasing a column being resized, scroll to keep the resulting column in sight + const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f; + ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn]; + if (column->MaxX < table->InnerClipRect.Min.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f); + else if (column->MaxX > table->InnerClipRect.Max.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f); + } + + // Apply resizing/dragging at the end of the frame + if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted) + { + ImGuiTableColumn* column = &table->Columns[table->ResizedColumn]; + const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale)); + const float new_width = ImTrunc(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f); + table->ResizedColumnNextWidth = new_width; + } + + table->IsActiveIdInTable = (g.ActiveIdIsAlive != 0 && table->IsActiveIdAliveBeforeTable == false); + + // Pop from id stack + IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, "Mismatching PushID/PopID!"); + IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, "Too many PopItemWidth!"); + if (table->InstanceCurrent > 0) + PopID(); + PopID(); + + // Restore window data that we modified + const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos; + inner_window->WorkRect = temp_data->HostBackupWorkRect; + inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect; + inner_window->SkipItems = table->HostSkipItems; + outer_window->DC.CursorPos = table->OuterRect.Min; + outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth; + outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize; + outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset; + + // Layout in outer window + // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding + // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414) + if (inner_window != outer_window) + { + short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask; + inner_window->DC.NavLayersActiveMask |= 1 << table->NavLayer; // So empty table don't appear to navigate differently. + g.CurrentTable = NULL; // To avoid error recovery recursing + EndChild(); + g.CurrentTable = table; + inner_window->DC.NavLayersActiveMask = backup_nav_layers_active_mask; + } + else + { + table->InnerWindow->DC.TreeDepth--; + ItemSize(table->OuterRect.GetSize()); + ItemAdd(table->OuterRect, 0); + } + + // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar + if (table->Flags & ImGuiTableFlags_NoHostExtendX) + { + // FIXME-TABLE: Could we remove this section? + // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents + IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0); + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth); + } + else if (temp_data->UserOuterSize.x <= 0.0f) + { + // Some references for this: #7651 + tests "table_reported_size", "table_reported_size_outer" equivalent Y block + // - Checking for ImGuiTableFlags_ScrollX/ScrollY flag makes us a frame ahead when disabling those flags. + // - FIXME-TABLE: Would make sense to pre-compute expected scrollbar visibility/sizes to generally save a frame of feedback. + const float inner_content_max_x = table->OuterRect.Min.x + table->ColumnsAutoFitWidth; // Slightly misleading name but used for code symmetry with inner_content_max_y + const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.x : 0.0f); + outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, inner_content_max_x + decoration_size - temp_data->UserOuterSize.x); + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, inner_content_max_x + decoration_size)); + } + else + { + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x); + } + if (temp_data->UserOuterSize.y <= 0.0f) + { + const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.y : 0.0f; + outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, inner_content_max_y + decoration_size - temp_data->UserOuterSize.y); + outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, inner_content_max_y + decoration_size)); + } + else + { + // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set) + outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y); + } + + // Save settings + if (table->IsSettingsDirty) + TableSaveSettings(table); + table->IsInitializing = false; + + // Clear or restore current table, if any + IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table); + IM_ASSERT(g.TablesTempDataStacked > 0); + temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL; + g.CurrentTable = temp_data && (temp_data->WindowID == outer_window->ID) ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL; + if (g.CurrentTable) + { + g.CurrentTable->TempData = temp_data; + g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter; + } + outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1; + NavUpdateCurrentWindowIsScrollPushableX(); +} + +// Called in TableSetupColumn() when initializing and in TableLoadSettings() for defaults before applying stored settings. +// 'init_mask' specify which fields to initialize. +static void TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags init_mask) +{ + ImGuiTableColumnFlags flags = column->Flags; + if (init_mask & ImGuiTableFlags_Resizable) + { + float init_width_or_weight = column->InitStretchWeightOrWidth; + column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; + column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f; + if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified + column->AutoFitQueue = 0x00; + } + if (init_mask & ImGuiTableFlags_Reorderable) + column->DisplayOrder = (ImGuiTableColumnIdx)table->Columns.index_from_ptr(column); + if (init_mask & ImGuiTableFlags_Hideable) + column->IsUserEnabled = column->IsUserEnabledNextFrame = (flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; + if (init_mask & ImGuiTableFlags_Sortable) + { + // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs. + column->SortOrder = (flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1; + column->SortDirection = (flags & ImGuiTableColumnFlags_DefaultSort) ? ((flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None; + } +} + +// See "COLUMNS SIZING POLICIES" comments at the top of this file +// If (init_width_or_weight <= 0.0f) it is ignored +void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT_USER_ERROR_RET(table->DeclColumnsCount < table->ColumnsCount, "TableSetupColumn(): called too many times!"); + IM_ASSERT_USER_ERROR_RET(table->IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!"); + IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()"); + + ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; + table->DeclColumnsCount++; + + // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. + // Give a grace to users of ImGuiTableFlags_ScrollX. + if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0) + IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0f, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column."); + + // When passing a width automatically enforce WidthFixed policy + // (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f) + if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableColumnFlags_WidthFixed; + if (flags & ImGuiTableColumnFlags_AngledHeader) + { + flags |= ImGuiTableColumnFlags_NoHeaderLabel; + table->AngledHeadersCount++; + } + + TableSetupColumnFlags(table, column, flags); + column->UserID = user_id; + flags = column->Flags; + + // Initialize defaults + column->InitStretchWeightOrWidth = init_width_or_weight; + if (table->IsInitializing) + { + ImGuiTableFlags init_flags = ~table->SettingsLoadedFlags; + if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f) + init_flags |= ImGuiTableFlags_Resizable; + TableInitColumnDefaults(table, column, init_flags); + } + + // Store name (append with zero-terminator in contiguous buffer) + // FIXME: If we recorded the number of \n in names we could compute header row height + column->NameOffset = -1; + if (label != NULL && label[0] != 0) + { + column->NameOffset = (ImS16)table->ColumnsNames.size(); + table->ColumnsNames.append(label, label + ImStrlen(label) + 1); + } +} + +// [Public] +void ImGui::TableSetupScrollFreeze(int columns, int rows) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(table->IsLayoutLocked == false && "TableSetupColumn(): need to call before first row!"); + IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); + IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit + + table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(columns, table->ColumnsCount) : 0; + table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; + table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0; + table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; + table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b + + // Ensure frozen columns are ordered in their section. We still allow multiple frozen columns to be reordered. + // FIXME-TABLE: This work for preserving 2143 into 21|43. How about 4321 turning into 21|43? (preserve relative order in each section) + for (int column_n = 0; column_n < table->FreezeColumnsRequest; column_n++) + { + int order_n = table->DisplayOrderToIndex[column_n]; + if (order_n != column_n && order_n >= table->FreezeColumnsRequest) + { + ImSwap(table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder, table->Columns[table->DisplayOrderToIndex[column_n]].DisplayOrder); + ImSwap(table->DisplayOrderToIndex[order_n], table->DisplayOrderToIndex[column_n]); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Tables: Simple accessors +//----------------------------------------------------------------------------- +// - TableGetColumnCount() +// - TableGetColumnName() +// - TableGetColumnName() [Internal] +// - TableSetColumnEnabled() +// - TableGetColumnFlags() +// - TableGetCellBgRect() [Internal] +// - TableGetColumnResizeID() [Internal] +// - TableGetHoveredColumn() [Internal] +// - TableGetHoveredRow() [Internal] +// - TableSetBgColor() +//----------------------------------------------------------------------------- + +int ImGui::TableGetColumnCount() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + return table ? table->ColumnsCount : 0; +} + +const char* ImGui::TableGetColumnName(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return NULL; + if (column_n < 0) + column_n = table->CurrentColumn; + return TableGetColumnName(table, column_n); +} + +const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n) +{ + if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount) + return ""; // NameOffset is invalid at this point + const ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->NameOffset == -1) + return ""; + return &table->ColumnsNames.Buf[column->NameOffset]; +} + +// Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view) +// Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) +// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state. +// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable(). +// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0. +// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu. +void ImGui::TableSetColumnEnabled(int column_n, bool enabled) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above + if (column_n < 0) + column_n = table->CurrentColumn; + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiTableColumn* column = &table->Columns[column_n]; + column->IsUserEnabledNextFrame = enabled; +} + +// We allow querying for an extra column in order to poll the IsHovered state of the right-most section +ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return ImGuiTableColumnFlags_None; + if (column_n < 0) + column_n = table->CurrentColumn; + if (column_n == table->ColumnsCount) + return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None; + return table->Columns[column_n].Flags; +} + +// Return the cell rectangle based on currently known height. +// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +// The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height. +// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right +// columns report a small offset so their CellBgRect can extend up to the outer border. +// FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling. +ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n) +{ + const ImGuiTableColumn* column = &table->Columns[column_n]; + float x1 = column->MinX; + float x2 = column->MaxX; + //if (column->PrevEnabledColumn == -1) + // x1 -= table->OuterPaddingX; + //if (column->NextEnabledColumn == -1) + // x2 += table->OuterPaddingX; + x1 = ImMax(x1, table->WorkRect.Min.x); + x2 = ImMin(x2, table->WorkRect.Max.x); + return ImRect(x1, table->RowPosY1, x2, table->RowPosY2); +} + +// Return the resizing ID for the right-side of the given column. +ImGuiID ImGui::TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no) +{ + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiID instance_id = TableGetInstanceID(table, instance_no); + return instance_id + 1 + column_n; // FIXME: #6140: still not ideal +} + +// Return -1 when table is not hovered. return columns_count if hovering the unused space at the right of the right-most visible column. +int ImGui::TableGetHoveredColumn() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return -1; + return (int)table->HoveredColumnBody; +} + +// Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row. +// *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value. +// This difference with is the reason why this is not public yet. +int ImGui::TableGetHoveredRow() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return -1; + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + return (int)table_instance->HoveredRowLast; +} + +void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(target != ImGuiTableBgTarget_None); + + if (color == IM_COL32_DISABLE) + color = 0; + + // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time. + switch (target) + { + case ImGuiTableBgTarget_CellBg: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + if (column_n == -1) + column_n = table->CurrentColumn; + if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n)) + return; + if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n) + table->RowCellDataCurrent++; + ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent]; + cell_data->BgColor = color; + cell_data->Column = (ImGuiTableColumnIdx)column_n; + break; + } + case ImGuiTableBgTarget_RowBg0: + case ImGuiTableBgTarget_RowBg1: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + IM_ASSERT(column_n == -1); + int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0; + table->RowBgColor[bg_idx] = color; + break; + } + default: + IM_ASSERT(0); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Row changes +//------------------------------------------------------------------------- +// - TableGetRowIndex() +// - TableNextRow() +// - TableBeginRow() [Internal] +// - TableEndRow() [Internal] +//------------------------------------------------------------------------- + +// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows +int ImGui::TableGetRowIndex() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return 0; + return table->CurrentRow; +} + +// [Public] Starts into the first cell of a new row +void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + if (table->IsInsideRow) + TableEndRow(table); + + table->LastRowFlags = table->RowFlags; + table->RowFlags = row_flags; + table->RowCellPaddingY = g.Style.CellPadding.y; + table->RowMinHeight = row_min_height; + TableBeginRow(table); + + // We honor min_row_height requested by user, but cannot guarantee per-row maximum height, + // because that would essentially require a unique clipping rectangle per-cell. + table->RowPosY2 += table->RowCellPaddingY * 2.0f; + table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height); + + // Disable output until user calls TableNextColumn() + table->InnerWindow->SkipItems = true; +} + +// [Internal] Only called by TableNextRow() +void ImGui::TableBeginRow(ImGuiTable* table) +{ + ImGuiWindow* window = table->InnerWindow; + IM_ASSERT(!table->IsInsideRow); + + // New row + table->CurrentRow++; + table->CurrentColumn = -1; + table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE; + table->RowCellDataCurrent = -1; + table->IsInsideRow = true; + + // Begin frozen rows + float next_y1 = table->RowPosY2; + if (table->CurrentRow == 0 && table->FreezeRowsCount > 0) + next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y; + + table->RowPosY1 = table->RowPosY2 = next_y1; + table->RowTextBaseline = 0.0f; + table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent + + window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + table->RowCellPaddingY); // This allows users to call SameLine() to share LineSize between columns. + window->DC.PrevLineSize = window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); // This allows users to call SameLine() to share LineSize between columns, and to call it from first column too. + window->DC.IsSameLine = window->DC.IsSetPos = false; + window->DC.CursorMaxPos.y = next_y1; + + // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging. + if (table->RowFlags & ImGuiTableRowFlags_Headers) + { + TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg)); + if (table->CurrentRow == 0) + table->IsUsingHeaders = true; + } +} + +// [Internal] Called by TableNextRow() +void ImGui::TableEndRow(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window == table->InnerWindow); + IM_ASSERT(table->IsInsideRow); + + if (table->CurrentColumn != -1) + { + TableEndCell(table); + table->CurrentColumn = -1; + } + + // Logging + if (g.LogEnabled) + LogRenderedText(NULL, "|"); + + // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. + window->DC.CursorPos.y = table->RowPosY2; + + // Row background fill + const float bg_y1 = table->RowPosY1; + const float bg_y2 = table->RowPosY2; + const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount); + const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest); + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + if ((table->RowFlags & ImGuiTableRowFlags_Headers) && (table->CurrentRow == 0 || (table->LastRowFlags & ImGuiTableRowFlags_Headers))) + table_instance->LastTopHeadersRowHeight += bg_y2 - bg_y1; + + const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y); + if (is_visible) + { + // Update data for TableGetHoveredRow() + if (table->HoveredColumnBody != -1 && g.IO.MousePos.y >= bg_y1 && g.IO.MousePos.y < bg_y2 && table_instance->HoveredRowNext < 0) + table_instance->HoveredRowNext = table->CurrentRow; + + // Decide of background color for the row + ImU32 bg_col0 = 0; + ImU32 bg_col1 = 0; + if (table->RowBgColor[0] != IM_COL32_DISABLE) + bg_col0 = table->RowBgColor[0]; + else if (table->Flags & ImGuiTableFlags_RowBg) + bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); + if (table->RowBgColor[1] != IM_COL32_DISABLE) + bg_col1 = table->RowBgColor[1]; + + // Decide of top border color + ImU32 top_border_col = 0; + const float border_size = TABLE_BORDER_SIZE; + if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH)) + top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; + + const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0; + const bool draw_strong_bottom_border = unfreeze_rows_actual; + if ((bg_col0 | bg_col1 | top_border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) + { + // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is + // always followed by a change of clipping rectangle we perform the smallest overwrite possible here. + if ((table->Flags & ImGuiTableFlags_NoClip) == 0) + window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4(); + table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0); + } + + // Draw row background + // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle + if (bg_col0 || bg_col1) + { + ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2); + row_rect.ClipWith(table->BgClipRect); + if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0); + if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1); + } + + // Draw cell background color + if (draw_cell_bg_color) + { + ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent]; + for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++) + { + // As we render the BG here we need to clip things (for layout we would not) + // FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling. + const ImGuiTableColumn* column = &table->Columns[cell_data->Column]; + ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column); + cell_bg_rect.ClipWith(table->BgClipRect); + cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x); // So that first column after frozen one gets clipped when scrolling + cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX); + if (cell_bg_rect.Min.y < cell_bg_rect.Max.y) + window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor); + } + } + + // Draw top border + if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), top_border_col, border_size); + + // Draw bottom border at the row unfreezing mark (always strong) + if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size); + } + + // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + // - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark + // end of row and get the new cursor position. + if (unfreeze_rows_request) + { + IM_ASSERT(table->FreezeRowsRequest > 0); + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->Columns[column_n].NavLayerCurrent = table->NavLayer; + const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y); + table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y; + + if (unfreeze_rows_actual) + { + IM_ASSERT(table->IsUnfrozenRows == false); + table->IsUnfrozenRows = true; + + // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, table->InnerClipRect.Max.y); + table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = table->InnerClipRect.Max.y; + table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen; + IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y); + + float row_height = table->RowPosY2 - table->RowPosY1; + table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; + table->RowPosY1 = table->RowPosY2 - row_height; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->DrawChannelCurrent = column->DrawChannelUnfrozen; + column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y; + } + + // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent); + } + } + + if (!(table->RowFlags & ImGuiTableRowFlags_Headers)) + table->RowBgColorCounter++; + table->IsInsideRow = false; +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Columns changes +//------------------------------------------------------------------------- +// - TableGetColumnIndex() +// - TableSetColumnIndex() +// - TableNextColumn() +// - TableBeginCell() [Internal] +// - TableEndCell() [Internal] +//------------------------------------------------------------------------- + +int ImGui::TableGetColumnIndex() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return 0; + return table->CurrentColumn; +} + +// [Public] Append into a specific column +bool ImGui::TableSetColumnIndex(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->CurrentColumn != column_n) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + IM_ASSERT_USER_ERROR_RETV(column_n >= 0 && column_n < table->ColumnsCount, false, "TableSetColumnIndex() invalid column index!"); + TableBeginCell(table, column_n); + } + + // Return whether the column is visible. User may choose to skip submitting items based on this return value, + // however they shouldn't skip submitting for columns that may have the tallest contribution to row height. + return table->Columns[column_n].IsRequestOutput; +} + +// [Public] Append into the next column, wrap and create a new row when already on last column +bool ImGui::TableNextColumn() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + TableBeginCell(table, table->CurrentColumn + 1); + } + else + { + TableNextRow(); + TableBeginCell(table, 0); + } + + // Return whether the column is visible. User may choose to skip submitting items based on this return value, + // however they shouldn't skip submitting for columns that may have the tallest contribution to row height. + return table->Columns[table->CurrentColumn].IsRequestOutput; +} + + +// [Internal] Called by TableSetColumnIndex()/TableNextColumn() +// This is called very frequently, so we need to be mindful of unnecessary overhead. +// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. +void ImGui::TableBeginCell(ImGuiTable* table, int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTableColumn* column = &table->Columns[column_n]; + ImGuiWindow* window = table->InnerWindow; + table->CurrentColumn = column_n; + + // Start position is roughly ~~ CellRect.Min + CellPadding + Indent + float start_x = column->WorkMinX; + if (column->Flags & ImGuiTableColumnFlags_IndentEnable) + start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. + + window->DC.CursorPos.x = start_x; + window->DC.CursorPos.y = table->RowPosY1 + table->RowCellPaddingY; + window->DC.CursorMaxPos.x = window->DC.CursorPos.x; + window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT + window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x; // PrevLine.y is preserved. This allows users to call SameLine() to share LineSize between columns. + window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; + window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent; + + // Note how WorkRect.Max.y is only set once during layout + window->WorkRect.Min.y = window->DC.CursorPos.y; + window->WorkRect.Min.x = column->WorkMinX; + window->WorkRect.Max.x = column->WorkMaxX; + window->DC.ItemWidth = column->ItemWidth; + + window->SkipItems = column->IsSkipItems; + if (column->IsSkipItems) + { + g.LastItemData.ID = 0; + g.LastItemData.StatusFlags = 0; + } + + // Also see TablePushColumnChannel() + if (table->Flags & ImGuiTableFlags_NoClip) + { + // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. + table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP); + //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP); + } + else + { + // FIXME-TABLE: Could avoid this if draw channel is dummy channel? + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); + } + + // Logging + if (g.LogEnabled && !column->IsSkipItems) + { + LogRenderedText(&window->DC.CursorPos, "|"); + g.LogLinePosY = FLT_MAX; + } +} + +// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn() +void ImGui::TableEndCell(ImGuiTable* table) +{ + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + ImGuiWindow* window = table->InnerWindow; + + if (window->DC.IsSetPos) + ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); + + // Report maximum position so we can infer content size per column. + float* p_max_pos_x; + if (table->RowFlags & ImGuiTableRowFlags_Headers) + p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call + else + p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen; + *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x); + if (column->IsEnabled) + table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->RowCellPaddingY); + column->ItemWidth = window->DC.ItemWidth; + + // Propagate text baseline for the entire row + // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. + table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Columns width management +//------------------------------------------------------------------------- +// - TableGetMaxColumnWidth() [Internal] +// - TableGetColumnWidthAuto() [Internal] +// - TableSetColumnWidth() +// - TableSetColumnWidthAutoSingle() [Internal] +// - TableSetColumnWidthAutoAll() [Internal] +// - TableUpdateColumnsWeightFromWidth() [Internal] +//------------------------------------------------------------------------- +// Note that actual columns widths are computed in TableUpdateLayout(). +//------------------------------------------------------------------------- + +// Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis. +float ImGui::TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n) +{ + const ImGuiTableColumn* column = &table->Columns[column_n]; + float max_width = FLT_MAX; + const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2; + if (table->Flags & ImGuiTableFlags_ScrollX) + { + // Frozen columns can't reach beyond visible width else scrolling will naturally break. + // (we use DisplayOrder as within a set of multiple frozen column reordering is possible) + if (column->DisplayOrder < table->FreezeColumnsRequest) + { + max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX; + max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2; + } + } + else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0) + { + // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + // sure they are all visible. Because of this we also know that all of the columns will always fit in + // table->WorkRect and therefore in table->InnerRect (because ScrollX is off) + // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match. + // See "table_width_distrib" and "table_width_keep_visible" tests + max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX; + //max_width -= table->CellSpacingX1; + max_width -= table->CellSpacingX2; + max_width -= table->CellPaddingX * 2.0f; + max_width -= table->OuterPaddingX; + } + return max_width; +} + +// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field +float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column) +{ + const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX; + const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX; + float width_auto = content_width_body; + if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) + width_auto = ImMax(width_auto, content_width_headers); + + // Non-resizable fixed columns preserve their requested width + if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f) + if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize)) + width_auto = column->InitStretchWeightOrWidth; + + return ImMax(width_auto, table->MinColumnWidth); +} + +// 'width' = inner column width, without padding +void ImGui::TableSetColumnWidth(int column_n, float width) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && table->IsLayoutLocked == false); + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiTableColumn* column_0 = &table->Columns[column_n]; + float column_0_width = width; + + // Apply constraints early + // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) + IM_ASSERT(table->MinColumnWidth > 0.0f); + const float min_width = table->MinColumnWidth; + const float max_width = ImMax(min_width, column_0->WidthMax); // Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933) + column_0_width = ImClamp(column_0_width, min_width, max_width); + if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width) + return; + + //IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width); + ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL; + + // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. + // - All fixed: easy. + // - All stretch: easy. + // - One or more fixed + one stretch: easy. + // - One or more fixed + more than one stretch: tricky. + // Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here. + + // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + // Scenarios: + // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset. + // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered. + // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. + // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 W3 resize from W1| or W2| --> ok + // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 F3 resize from W1| or W2| --> ok + // - W1 F2 W3 resize from W1| or F2| --> ok + // - F1 W2 F3 resize from W2| --> ok + // - F1 W3 F2 resize from W3| --> ok + // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. + // - W1 F2 F3 resize from F2| --> ok + // All resizes from a Wx columns are locking other columns. + + // Possible improvements: + // - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. + // - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. + + // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). + + // If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. + // This is the preferred resize path + if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed) + if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder) + { + column_0->WidthRequest = column_0_width; + table->IsSettingsDirty = true; + return; + } + + // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column) + if (column_1 == NULL) + column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL; + if (column_1 == NULL) + return; + + // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column. + // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) + float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width); + column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width; + IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f); + column_0->WidthRequest = column_0_width; + column_1->WidthRequest = column_1_width; + if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch) + TableUpdateColumnsWeightFromWidth(table); + table->IsSettingsDirty = true; +} + +// Disable clipping then auto-fit, will take 2 frames +// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) +void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n) +{ + // Single auto width uses auto-fit + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled) + return; + column->CannotSkipItemsQueue = (1 << 0); + table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n; +} + +void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table) +{ + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column + continue; + column->CannotSkipItemsQueue = (1 << 0); + column->AutoFitQueue = (1 << 1); + } +} + +void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table) +{ + IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1); + + // Measure existing quantities + float visible_weight = 0.0f; + float visible_width = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + IM_ASSERT(column->StretchWeight > 0.0f); + visible_weight += column->StretchWeight; + visible_width += column->WidthRequest; + } + IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f); + + // Apply new weights + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight; + IM_ASSERT(column->StretchWeight > 0.0f); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Drawing +//------------------------------------------------------------------------- +// - TablePushBackgroundChannel() [Internal] +// - TablePopBackgroundChannel() [Internal] +// - TableSetupDrawChannels() [Internal] +// - TableMergeDrawChannels() [Internal] +// - TableGetColumnBorderCol() [Internal] +// - TableDrawBorders() [Internal] +//------------------------------------------------------------------------- + + +// FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct +// with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect. +// This would slightly simplify caller code. + +// Bg2 is used by Selectable (and possibly other widgets) to render to the background. +// Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. +void ImGui::TablePushBackgroundChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + table->HostBackupInnerClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent); +} + +void ImGui::TablePopBackgroundChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[table->CurrentColumn].DrawChannelCurrent); +} + +// Also see TableBeginCell() +void ImGui::TablePushColumnChannel(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + if (table->Flags & ImGuiTableFlags_NoClip) + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[column_n]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); +} + +void ImGui::TablePopColumnChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + if ((table->Flags & ImGuiTableFlags_NoClip) || (table->CurrentColumn == -1)) // Calling TreePop() after TableNextRow() is supported. + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); +} + +// Allocate draw channels. Called by TableUpdateLayout() +// - We allocate them following storage order instead of display order so reordering columns won't needlessly +// increase overall dormant memory cost. +// - We isolate headers draw commands in their own channels instead of just altering clip rects. +// This is in order to facilitate merging of draw commands. +// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. +// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other +// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. +// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for +// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4). +// Draw channel allocation (before merging): +// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) +// - Clip --> 2+D+N channels +// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) +// - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) +// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. +void ImGui::TableSetupDrawChannels(ImGuiTable* table) +{ + const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; + const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount; + const int channels_for_bg = 1 + 1 * freeze_row_multiplier; + const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || (memcmp(table->VisibleMaskByIndex, table->EnabledMaskByIndex, ImBitArrayGetStorageSizeInBytes(table->ColumnsCount)) != 0)) ? +1 : 0; + const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; + table->DrawSplitter->Split(table->InnerWindow->DrawList, channels_total); + table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1); + table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN; + table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN); + + int draw_channel_current = 2; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsVisibleX && column->IsVisibleY) + { + column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current); + column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0)); + if (!(table->Flags & ImGuiTableFlags_NoClip)) + draw_channel_current++; + } + else + { + column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel; + } + column->DrawChannelCurrent = column->DrawChannelFrozen; + } + + // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default. + // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect. + // (This technically isn't part of setting up draw channels, but is reasonably related to be done here) + table->BgClipRect = table->InnerClipRect; + table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; + table->Bg2ClipRectForDrawCmd = table->HostClipRect; + IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); +} + +// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). +// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect, +// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels(). +// +// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +// this we merge their clip rect and make them contiguous in the channel list, so they can be merged +// by the call to DrawSplitter.Merge() following to the call to this function. +// We reorder draw commands by arranging them into a maximum of 4 distinct groups: +// +// 1 group: 2 groups: 2 groups: 4 groups: +// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +// +// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +// based on its position (within frozen rows/columns groups or not). +// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +// This function assume that each column are pointing to a distinct draw channel, +// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask. +// +// Column channels will not be merged into one of the 1-4 groups in the following cases: +// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds +// matches, by e.g. calling SetCursorScreenPos(). +// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +// we could do better but it's going to be rare and probably not worth the hassle. +// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. +// +// This function is particularly tricky to understand.. take a breath. +void ImGui::TableMergeDrawChannels(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImDrawListSplitter* splitter = table->DrawSplitter; + const bool has_freeze_v = (table->FreezeRowsCount > 0); + const bool has_freeze_h = (table->FreezeColumnsCount > 0); + IM_ASSERT(splitter->_Current == 0); + + // Track which groups we are going to attempt to merge, and which channels goes into each group. + struct MergeGroup + { + ImRect ClipRect; + int ChannelsCount = 0; + ImBitArrayPtr ChannelsMask = NULL; + }; + int merge_group_mask = 0x00; + MergeGroup merge_groups[4]; + + // Use a reusable temp buffer for the merge masks as they are dynamically sized. + const int max_draw_channels = (4 + table->ColumnsCount * 2); + const int size_for_masks_bitarrays_one = (int)ImBitArrayGetStorageSizeInBytes(max_draw_channels); + g.TempBuffer.reserve(size_for_masks_bitarrays_one * 5); + memset(g.TempBuffer.Data, 0, size_for_masks_bitarrays_one * 5); + for (int n = 0; n < IM_COUNTOF(merge_groups); n++) + merge_groups[n].ChannelsMask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * n)); + ImBitArrayPtr remaining_mask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * 4)); + + // 1. Scan channels and take note of those which can be merged + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n)) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + const int merge_group_sub_count = has_freeze_v ? 2 : 1; + for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++) + { + const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen; + + // Don't attempt to merge if there are multiple draw calls within the column + ImDrawChannel* src_channel = &splitter->_Channels[channel_no]; + if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0 && src_channel->_CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd() + src_channel->_CmdBuffer.pop_back(); + if (src_channel->_CmdBuffer.Size != 1) + continue; + + // Find out the width of this merge group and check if it will fit in our column + // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) + if (!(column->Flags & ImGuiTableColumnFlags_NoClip)) + { + float content_max_x; + if (!has_freeze_v) + content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze + else if (merge_group_sub_n == 0) + content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze + else + content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze + if (content_max_x > column->ClipRect.Max.x) + continue; + } + + const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2); + IM_ASSERT(channel_no < max_draw_channels); + MergeGroup* merge_group = &merge_groups[merge_group_n]; + if (merge_group->ChannelsCount == 0) + merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + ImBitArraySetBit(merge_group->ChannelsMask, channel_no); + merge_group->ChannelsCount++; + merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); + merge_group_mask |= (1 << merge_group_n); + } + + // Invalidate current draw channel + // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data) + column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1; + } + + // [DEBUG] Display merge groups +#if 0 + if (g.IO.KeyShift) + for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++) + { + MergeGroup* merge_group = &merge_groups[merge_group_n]; + if (merge_group->ChannelsCount == 0) + continue; + char buf[32]; + ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount); + ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4); + ImVec2 text_size = CalcTextSize(buf, NULL); + GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255)); + GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL); + GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255)); + } +#endif + + // 2. Rewrite channel list in our preferred order + if (merge_group_mask != 0) + { + // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels(). + const int LEADING_DRAW_CHANNELS = 2; + g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized + ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; + ImBitArraySetBitRange(remaining_mask, LEADING_DRAW_CHANNELS, splitter->_Count); + ImBitArrayClearBit(remaining_mask, table->Bg2DrawChannelUnfrozen); + IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN); + int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS); + //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect; + ImRect host_rect = table->HostClipRect; + for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++) + { + if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) + { + MergeGroup* merge_group = &merge_groups[merge_group_n]; + ImRect merge_clip_rect = merge_group->ClipRect; + + // Extend outer-most clip limits to match those of host, so draw calls can be merged even if + // outer-most columns have some outer padding offsetting them from their parent ClipRect. + // The principal cases this is dealing with are: + // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect. + if ((merge_group_n & 1) == 0 || !has_freeze_h) + merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x); + if ((merge_group_n & 2) == 0 || !has_freeze_v) + merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y); + if ((merge_group_n & 1) != 0) + merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x); + if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) + merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y); + //GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f); // [DEBUG] + //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)); + //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)); + remaining_count -= merge_group->ChannelsCount; + for (int n = 0; n < (size_for_masks_bitarrays_one >> 2); n++) + remaining_mask[n] &= ~merge_group->ChannelsMask[n]; + for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++) + { + // Copy + overwrite new clip rect + if (!IM_BITARRAY_TESTBIT(merge_group->ChannelsMask, n)) + continue; + IM_BITARRAY_CLEARBIT(merge_group->ChannelsMask, n); + merge_channels_count--; + + ImDrawChannel* channel = &splitter->_Channels[n]; + IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect))); + channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4(); + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + } + } + + // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1) + if (merge_group_n == 1 && has_freeze_v) + memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel)); + } + + // Append unmergeable channels that we didn't reorder at the end of the list + for (int n = 0; n < splitter->_Count && remaining_count != 0; n++) + { + if (!IM_BITARRAY_TESTBIT(remaining_mask, n)) + continue; + ImDrawChannel* channel = &splitter->_Channels[n]; + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + remaining_count--; + } + IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size); + memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel)); + } +} + +static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_n) +{ + const bool is_hovered = (table->HoveredColumnBorder == column_n); + const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); + const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); + if (is_resized || is_hovered) + return ImGui::GetColorU32(is_resized ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered); + if (is_frozen_separator || (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize))) + return table->BorderColorStrong; + return table->BorderColorLight; +} + +// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow) +void ImGui::TableDrawBorders(ImGuiTable* table) +{ + ImGuiWindow* inner_window = table->InnerWindow; + if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) + return; + + ImDrawList* inner_drawlist = inner_window->DrawList; + table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); + inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false); + + // Draw inner border and resizing feedback + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + const float border_size = TABLE_BORDER_SIZE; + const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f); + const float draw_y2_body = table->InnerRect.Max.y; + const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; + if (table->Flags & ImGuiTableFlags_BordersInnerV) + { + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n)) + continue; + + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + const bool is_hovered = (table->HoveredColumnBorder == column_n); + const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); + const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; + const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); + if (column->MaxX > table->InnerClipRect.Max.x && !is_resized) + continue; + + // Decide whether right-most column is visible + if (column->NextEnabledColumn == -1 && !is_resizable) + if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX)) + continue; + if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + continue; + + // Draw in outer window so right-most column won't be clipped + float draw_y2 = draw_y2_head; + if (is_frozen_separator) + draw_y2 = draw_y2_body; + else if ((table->Flags & ImGuiTableFlags_NoBordersInBodyUntilResize) != 0 && (is_hovered || is_resized)) + draw_y2 = draw_y2_body; + else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) + draw_y2 = draw_y2_body; + if (draw_y2 > draw_y1) + inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), TableGetColumnBorderCol(table, order_n, column_n), border_size); + } + } + + // Draw outer border + // FIXME: could use AddRect or explicit VLine/HLine helper? + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + const ImRect outer_border = table->OuterRect; + const ImU32 outer_col = table->BorderColorStrong; + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + { + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, 0, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterV) + { + inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size); + inner_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterH) + { + inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size); + inner_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size); + } + } + if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) + { + // Draw bottom-most row border between it is above outer border. + const float border_y = table->RowPosY2; + if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) + inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size); + } + + inner_drawlist->PopClipRect(); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Sorting +//------------------------------------------------------------------------- +// - TableGetSortSpecs() +// - TableFixColumnSortDirection() [Internal] +// - TableGetColumnNextSortDirection() [Internal] +// - TableSetColumnSortDirection() [Internal] +// - TableSortSpecsSanitize() [Internal] +// - TableSortSpecsBuild() [Internal] +//------------------------------------------------------------------------- + +// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) +// When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have +// changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, +// else you may wastefully sort your data every frame! +// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! +ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (table == NULL || !(table->Flags & ImGuiTableFlags_Sortable)) + return NULL; + + // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + TableSortSpecsBuild(table); + return &table->SortSpecs; +} + +static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n) +{ + IM_ASSERT(n < column->SortDirectionsAvailCount); + return (ImGuiSortDirection)((column->SortDirectionsAvailList >> (n << 1)) & 0x03); +} + +// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending) +void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column) +{ + if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0) + return; + column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0); + table->IsSortSpecsDirty = true; +} + +// Calculate next sort direction that would be set after clicking the column +// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. +// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. +IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2); +ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column) +{ + IM_ASSERT(column->SortDirectionsAvailCount > 0); + if (column->SortOrder == -1) + return TableGetColumnAvailSortDirection(column, 0); + for (int n = 0; n < 3; n++) + if (column->SortDirection == TableGetColumnAvailSortDirection(column, n)) + return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount); + IM_ASSERT(0); + return ImGuiSortDirection_None; +} + +// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert +// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. +void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (!(table->Flags & ImGuiTableFlags_SortMulti)) + append_to_sort_specs = false; + if (!(table->Flags & ImGuiTableFlags_SortTristate)) + IM_ASSERT(sort_direction != ImGuiSortDirection_None); + + ImGuiTableColumnIdx sort_order_max = 0; + if (append_to_sort_specs) + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder); + + ImGuiTableColumn* column = &table->Columns[column_n]; + column->SortDirection = (ImU8)sort_direction; + if (column->SortDirection == ImGuiSortDirection_None) + column->SortOrder = -1; + else if (column->SortOrder == -1 || !append_to_sort_specs) + column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0; + + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + { + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column != column && !append_to_sort_specs) + other_column->SortOrder = -1; + TableFixColumnSortDirection(table, other_column); + } + table->IsSettingsDirty = true; + table->IsSortSpecsDirty = true; +} + +void ImGui::TableSortSpecsSanitize(ImGuiTable* table) +{ + IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable); + + // Clear SortOrder from hidden column and verify that there's no gap or duplicate. + int sort_order_count = 0; + ImU64 sort_order_mask = 0x00; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder != -1 && !column->IsEnabled) + column->SortOrder = -1; + if (column->SortOrder == -1) + continue; + sort_order_count++; + sort_order_mask |= ((ImU64)1 << column->SortOrder); + IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8); + } + + const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1); + const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti); + if (need_fix_linearize || need_fix_single_sort_order) + { + ImU64 fixed_mask = 0x00; + for (int sort_n = 0; sort_n < sort_order_count; sort_n++) + { + // Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) + int column_with_smallest_sort_order = -1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1) + if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder) + column_with_smallest_sort_order = column_n; + IM_ASSERT(column_with_smallest_sort_order != -1); + fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order); + table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n; + + // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + if (need_fix_single_sort_order) + { + sort_order_count = 1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (column_n != column_with_smallest_sort_order) + table->Columns[column_n].SortOrder = -1; + break; + } + } + } + + // Fallback default sort order (if no column with the ImGuiTableColumnFlags_DefaultSort flag) + if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate)) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + sort_order_count = 1; + column->SortOrder = 0; + column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0); + break; + } + } + + table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count; +} + +void ImGui::TableSortSpecsBuild(ImGuiTable* table) +{ + bool dirty = table->IsSortSpecsDirty; + if (dirty) + { + TableSortSpecsSanitize(table); + table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount); + table->SortSpecs.SpecsDirty = true; // Mark as dirty for user + table->IsSortSpecsDirty = false; // Mark as not dirty for us + } + + // Write output + // May be able to move all SortSpecs data from table (48 bytes) to ImGuiTableTempData if we decide to write it back on every BeginTable() + ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data; + if (dirty && sort_specs != NULL) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder == -1) + continue; + IM_ASSERT(column->SortOrder < table->SortSpecsCount); + ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder]; + sort_spec->ColumnUserID = column->UserID; + sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n; + sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder; + sort_spec->SortDirection = (ImGuiSortDirection)column->SortDirection; + } + + table->SortSpecs.Specs = sort_specs; + table->SortSpecs.SpecsCount = table->SortSpecsCount; +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Headers +//------------------------------------------------------------------------- +// - TableGetHeaderRowHeight() [Internal] +// - TableGetHeaderAngledMaxLabelWidth() [Internal] +// - TableHeadersRow() +// - TableHeader() +// - TableAngledHeadersRow() +// - TableAngledHeadersRowEx() [Internal] +//------------------------------------------------------------------------- + +float ImGui::TableGetHeaderRowHeight() +{ + // Caring for a minor edge case: + // Calculate row height, for the unlikely case that some labels may be taller than others. + // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. + // In your custom header row you may omit this all together and just call TableNextRow() without a height... + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + float row_height = g.FontSize; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) + if ((table->Columns[column_n].Flags & ImGuiTableColumnFlags_NoHeaderLabel) == 0) + row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(table, column_n)).y); + return row_height + g.Style.CellPadding.y * 2.0f; +} + +float ImGui::TableGetHeaderAngledMaxLabelWidth() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + float width = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) + if (table->Columns[column_n].Flags & ImGuiTableColumnFlags_AngledHeader) + width = ImMax(width, CalcTextSize(TableGetColumnName(table, column_n), NULL, true).x); + return width + g.Style.CellPadding.y * 2.0f; // Swap padding +} + +// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). +// The intent is that advanced users willing to create customized headers would not need to use this helper +// and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets. +// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +// This code is intentionally written to not make much use of internal functions, to give you better direction +// if you need to write your own. +// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. +void ImGui::TableHeadersRow() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + + // Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make + // it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + // Open row + const float row_height = TableGetHeaderRowHeight(); + TableNextRow(ImGuiTableRowFlags_Headers, row_height); + const float row_y1 = GetCursorScreenPos().y; + if (table->HostSkipItems) // Merely an optimization, you may skip in your own code. + return; + + const int columns_count = TableGetColumnCount(); + for (int column_n = 0; column_n < columns_count; column_n++) + { + if (!TableSetColumnIndex(column_n)) + continue; + + // Push an id to allow empty/unnamed headers. This is also idiomatic as it ensure there is a consistent ID path to access columns (for e.g. automation) + const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? "" : TableGetColumnName(column_n); + PushID(column_n); + TableHeader(name); + PopID(); + } + + // Allow opening popup from the right-most section after the last column. + ImVec2 mouse_pos = ImGui::GetMousePos(); + if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) + if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height) + TableOpenContextMenu(columns_count); // Will open a non-column-specific popup. +} + +// Emit a column header (text + optional sort order) +// We cpu-clip text here so that all columns headers can be merged into a same draw call. +// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() +void ImGui::TableHeader(const char* label) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(table->CurrentColumn != -1); + const int column_n = table->CurrentColumn; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Label + if (label == NULL) + label = ""; + const char* label_end = FindRenderedTextEnd(label); + ImVec2 label_size = CalcTextSize(label, label_end, true); + ImVec2 label_pos = window->DC.CursorPos; + + // If we already got a row height, there's use that. + // FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect? + ImRect cell_r = TableGetCellBgRect(table, column_n); + float label_height = ImMax(label_size.y, table->RowMinHeight - table->RowCellPaddingY * 2.0f); + + // Calculate ideal size for sort order arrow + float w_arrow = 0.0f; + float w_sort_text = 0.0f; + bool sort_arrow = false; + char sort_order_suf[4] = ""; + const float ARROW_SCALE = 0.65f; + if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + w_arrow = ImTrunc(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x); + if (column->SortOrder != -1) + sort_arrow = true; + if (column->SortOrder > 0) + { + ImFormatString(sort_order_suf, IM_COUNTOF(sort_order_suf), "%d", column->SortOrder + 1); + w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x; + } + } + + // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considered for merging. + float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow; + column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, sort_arrow ? cell_r.Max.x : ImMin(max_pos_x, cell_r.Max.x)); + column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x); + + // Keep header highlighted when context menu is open. + ImGuiID id = window->GetID(label); + ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f)); + ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal + if (!ItemAdd(bb, id)) + return; + + //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] + //GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] + + // Using AllowOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items. + const bool highlight = (table->HighlightColumnHeader == column_n); + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowOverlap); + if (held || hovered || highlight) + { + const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + //RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn); + } + else + { + // Submit single cell bg color in the case we didn't submit a full header row + if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0) + TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn); + } + RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding); + if (held) + table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n; + window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; + + // Drag and drop to re-order columns. + // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. + if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive) + { + // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + table->ReorderColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + + // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder. + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) + if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL) + if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinEnabledSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = -1; + if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x) + if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL) + if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (next_column->IndexWithinEnabledSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = +1; + } + + // Sort order arrow + const float ellipsis_max = ImMax(cell_r.Max.x - w_arrow - w_sort_text, label_pos.x); + if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + if (column->SortOrder != -1) + { + float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text); + float y = label_pos.y; + if (column->SortOrder > 0) + { + PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f)); + RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf); + PopStyleColor(); + x += w_sort_text; + } + RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); + } + + // Handle clicking on column header to adjust Sort Order + if (pressed && table->ReorderColumn != column_n) + { + ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column); + TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift); + } + } + + // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will + // be merged into a single draw call. + //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size); + + const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); + if (text_clipped && hovered && g.ActiveId == 0) + SetItemTooltip("%.*s", (int)(label_end - label), label); + + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + if (IsMouseReleased(1) && IsItemHovered()) + TableOpenContextMenu(column_n); +} + +// Unlike TableHeadersRow() it is not expected that you can reimplement or customize this with custom widgets. +// FIXME: No hit-testing/button on the angled header. +void ImGui::TableAngledHeadersRow() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + ImGuiTableTempData* temp_data = table->TempData; + temp_data->AngledHeadersRequests.resize(0); + temp_data->AngledHeadersRequests.reserve(table->ColumnsEnabledCount); + + // Which column needs highlight? + const ImGuiID row_id = GetID("##AngledHeaders"); + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + int highlight_column_n = table->HighlightColumnHeader; + if (highlight_column_n == -1 && table->HoveredColumnBody != -1) + if (table_instance->HoveredRowLast == 0 && table->HoveredColumnBorder == -1 && (g.ActiveId == 0 || g.ActiveId == row_id || (table->IsActiveIdInTable || g.DragDropActive))) + highlight_column_n = table->HoveredColumnBody; + + // Build up request + ImU32 col_header_bg = GetColorU32(ImGuiCol_TableHeaderBg); + ImU32 col_text = GetColorU32(ImGuiCol_Text); + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + if (IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n)) + { + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + if ((column->Flags & ImGuiTableColumnFlags_AngledHeader) == 0) // Note: can't rely on ImGuiTableColumnFlags_IsVisible test here. + continue; + ImGuiTableHeaderData request = { (ImGuiTableColumnIdx)column_n, col_text, col_header_bg, (column_n == highlight_column_n) ? GetColorU32(ImGuiCol_Header) : 0 }; + temp_data->AngledHeadersRequests.push_back(request); + } + + // Render row + TableAngledHeadersRowEx(row_id, g.Style.TableAngledHeadersAngle, 0.0f, temp_data->AngledHeadersRequests.Data, temp_data->AngledHeadersRequests.Size); +} + +// Important: data must be fed left to right +void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + ImGuiWindow* window = g.CurrentWindow; + ImDrawList* draw_list = window->DrawList; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(table->CurrentRow == -1 && "Must be first row"); + + if (max_label_width == 0.0f) + max_label_width = TableGetHeaderAngledMaxLabelWidth(); + + // Angle argument expressed in (-IM_PI/2 .. +IM_PI/2) as it is easier to think about for user. + const bool flip_label = (angle < 0.0f); + angle -= IM_PI * 0.5f; + const float cos_a = ImCos(angle); + const float sin_a = ImSin(angle); + const float label_cos_a = flip_label ? ImCos(angle + IM_PI) : cos_a; + const float label_sin_a = flip_label ? ImSin(angle + IM_PI) : sin_a; + const ImVec2 unit_right = ImVec2(cos_a, sin_a); + + // Calculate our base metrics and set angled headers data _before_ the first call to TableNextRow() + // FIXME-STYLE: Would it be better for user to submit 'max_label_width' or 'row_height' ? One can be derived from the other. + const float header_height = g.FontSize + g.Style.CellPadding.x * 2.0f; + const float row_height = ImTrunc(ImFabs(ImRotate(ImVec2(max_label_width, flip_label ? +header_height : -header_height), cos_a, sin_a).y)); + table->AngledHeadersHeight = row_height; + table->AngledHeadersSlope = (sin_a != 0.0f) ? (cos_a / sin_a) : 0.0f; + const ImVec2 header_angled_vector = unit_right * (row_height / -sin_a); // vector from bottom-left to top-left, and from bottom-right to top-right + + // Declare row, override and draw our own background + TableNextRow(ImGuiTableRowFlags_Headers, row_height); + TableNextColumn(); + const ImRect row_r(table->WorkRect.Min.x, table->BgClipRect.Min.y, table->WorkRect.Max.x, table->RowPosY2); + table->DrawSplitter->SetCurrentChannel(draw_list, TABLE_DRAW_CHANNEL_BG0); + float clip_rect_min_x = table->BgClipRect.Min.x; + if (table->FreezeColumnsCount > 0) + clip_rect_min_x = ImMax(clip_rect_min_x, table->Columns[table->FreezeColumnsCount - 1].MaxX); + TableSetBgColor(ImGuiTableBgTarget_RowBg0, 0); // Cancel + PushClipRect(table->BgClipRect.Min, table->BgClipRect.Max, false); // Span all columns + draw_list->AddRectFilled(ImVec2(table->BgClipRect.Min.x, row_r.Min.y), ImVec2(table->BgClipRect.Max.x, row_r.Max.y), GetColorU32(ImGuiCol_TableHeaderBg, 0.25f)); // FIXME-STYLE: Change row background with an arbitrary color. + PushClipRect(ImVec2(clip_rect_min_x, table->BgClipRect.Min.y), table->BgClipRect.Max, true); // Span all columns + + ButtonBehavior(row_r, row_id, NULL, NULL); + KeepAliveID(row_id); + + const float ascent_scaled = g.FontBaked->Ascent * g.FontBakedScale; // FIXME: Standardize those scaling factors better + const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f); + const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component + const ImVec2 align = g.Style.TableAngledHeadersTextAlign; + + // Draw background and labels in first pass, then all borders. + float max_x = -FLT_MAX; + for (int pass = 0; pass < 2; pass++) + for (int order_n = 0; order_n < data_count; order_n++) + { + const ImGuiTableHeaderData* request = &data[order_n]; + const int column_n = request->Index; + ImGuiTableColumn* column = &table->Columns[column_n]; + + ImVec2 bg_shape[4]; + bg_shape[0] = ImVec2(column->MaxX, row_r.Max.y); + bg_shape[1] = ImVec2(column->MinX, row_r.Max.y); + bg_shape[2] = bg_shape[1] + header_angled_vector; + bg_shape[3] = bg_shape[0] + header_angled_vector; + if (pass == 0) + { + // Draw shape + draw_list->AddQuadFilled(bg_shape[0], bg_shape[1], bg_shape[2], bg_shape[3], request->BgColor0); + draw_list->AddQuadFilled(bg_shape[0], bg_shape[1], bg_shape[2], bg_shape[3], request->BgColor1); // Optional highlight + max_x = ImMax(max_x, bg_shape[3].x); + + // Draw label + // - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset. + // - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated. + const char* label_name = TableGetColumnName(table, column_n); + const char* label_name_end = FindRenderedTextEnd(label_name); + const float line_off_step_x = (g.FontSize / -sin_a); + const int label_lines = ImTextCountLines(label_name, label_name_end); + + // Left<>Right alignment + float line_off_curr_x = flip_label ? (label_lines - 1) * line_off_step_x : 0.0f; + float line_off_for_align_x = ImFloor(ImMax((((column->MaxX - column->MinX) - padding.x * 2.0f) - (label_lines * line_off_step_x)), 0.0f) * align.x); + line_off_curr_x += line_off_for_align_x - line_off_for_ascent_x; + + // Register header width + column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX + ImCeil(label_lines * line_off_step_x - line_off_for_align_x); + + while (label_name < label_name_end) + { + const char* label_name_eol = strchr(label_name, '\n'); + if (label_name_eol == NULL) + label_name_eol = label_name_end; + + // FIXME: Individual line clipping for right-most column is broken for negative angles. + ImVec2 label_size = CalcTextSize(label_name, label_name_eol); + float clip_width = max_label_width - padding.y; // Using padding.y*2.0f would be symmetrical but hide more text. + float clip_height = ImMin(label_size.y, column->ClipRect.Max.x - column->WorkMinX - line_off_curr_x); + ImRect clip_r(window->ClipRect.Min, window->ClipRect.Min + ImVec2(clip_width, clip_height)); + int vtx_idx_begin = draw_list->_VtxCurrentIdx; + PushStyleColor(ImGuiCol_Text, request->TextColor); + RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size); + PopStyleColor(); + int vtx_idx_end = draw_list->_VtxCurrentIdx; + + // Up<>Down alignment + const float available_space = ImMax(clip_width - label_size.x + ImAbs(padding.x * cos_a) * 2.0f - ImAbs(padding.y * sin_a) * 2.0f, 0.0f); + const float vertical_offset = available_space * align.y * (flip_label ? -1.0f : 1.0f); + + // Rotate and offset label + ImVec2 pivot_in = ImVec2(window->ClipRect.Min.x - vertical_offset, window->ClipRect.Min.y + label_size.y); + ImVec2 pivot_out = ImVec2(column->WorkMinX, row_r.Max.y); + line_off_curr_x += flip_label ? -line_off_step_x : line_off_step_x; + pivot_out += unit_right * padding.y; + if (flip_label) + pivot_out += unit_right * (clip_width - ImMax(0.0f, clip_width - label_size.x)); + pivot_out.x += flip_label ? line_off_curr_x + line_off_step_x : line_off_curr_x; + ShadeVertsTransformPos(draw_list, vtx_idx_begin, vtx_idx_end, pivot_in, label_cos_a, label_sin_a, pivot_out); // Rotate and offset + //if (g.IO.KeyShift) { ImDrawList* fg_dl = GetForegroundDrawList(); vtx_idx_begin = fg_dl->_VtxCurrentIdx; fg_dl->AddRect(clip_r.Min, clip_r.Max, IM_COL32(0, 255, 0, 255), 0.0f, 0, 1.0f); ShadeVertsTransformPos(fg_dl, vtx_idx_begin, fg_dl->_VtxCurrentIdx, pivot_in, label_cos_a, label_sin_a, pivot_out); } + + label_name = label_name_eol + 1; + } + } + if (pass == 1) + { + // Draw border + draw_list->AddLine(bg_shape[0], bg_shape[3], TableGetColumnBorderCol(table, order_n, column_n)); + } + } + PopClipRect(); + PopClipRect(); + table->TempData->AngledHeadersExtraWidth = ImMax(0.0f, max_x - table->Columns[table->RightMostEnabledColumn].MaxX); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Context Menu +//------------------------------------------------------------------------- +// - TableOpenContextMenu() [Internal] +// - TableBeginContextMenuPopup() [Internal] +// - TableDrawDefaultContextMenu() [Internal] +//------------------------------------------------------------------------- + +// Use -1 to open menu not specific to a given column. +void ImGui::TableOpenContextMenu(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency) + column_n = table->CurrentColumn; + if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn() + column_n = -1; + IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount); + if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + table->IsContextPopupOpen = true; + table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + OpenPopupEx(context_menu_id, ImGuiPopupFlags_None); + } +} + +bool ImGui::TableBeginContextMenuPopup(ImGuiTable* table) +{ + if (!table->IsContextPopupOpen || table->InstanceCurrent != table->InstanceInteracted) + return false; + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings)) + return true; + table->IsContextPopupOpen = false; + return false; +} + +// Output context menu into current window (generally a popup) +// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +// Sections to display are pulled from 'flags_for_section_to_display', which is typically == table->Flags. +// - ImGuiTableFlags_Resizable -> display Sizing menu items +// - ImGuiTableFlags_Reorderable -> display "Reset Order" +////- ImGuiTableFlags_Sortable -> display sorting options (disabled) +// - ImGuiTableFlags_Hideable -> display columns visibility menu items +// It means if you have a custom context menus you can call this section and omit some sections, and add your own. +void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags_for_section_to_display) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + bool want_separator = false; + const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1; + ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL; + + // Sizing + if (flags_for_section_to_display & ImGuiTableFlags_Resizable) + { + if (column != NULL) + { + const bool can_resize = !(column->Flags & ImGuiTableColumnFlags_NoResize) && column->IsEnabled; + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableSizeOne), NULL, false, can_resize)) // "###SizeOne" + TableSetColumnWidthAutoSingle(table, column_n); + } + + const char* size_all_desc; + if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame) + size_all_desc = LocalizeGetMsg(ImGuiLocKey_TableSizeAllFit); // "###SizeAll" All fixed + else + size_all_desc = LocalizeGetMsg(ImGuiLocKey_TableSizeAllDefault); // "###SizeAll" All stretch or mixed + if (MenuItem(size_all_desc, NULL)) + TableSetColumnWidthAutoAll(table); + want_separator = true; + } + + // Ordering + if (flags_for_section_to_display & ImGuiTableFlags_Reorderable) + { + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetOrder), NULL, false, !table->IsDefaultDisplayOrder)) + table->IsResetDisplayOrderRequest = true; + want_separator = true; + } + + // Reset all (should work but seems unnecessary/noisy to expose?) + //if (MenuItem("Reset all")) + // table->IsResetAllRequest = true; + + // Sorting + // (modify TableOpenContextMenu() to add _Sortable flag if enabling this) +#if 0 + if ((flags_for_section_to_display & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0) + { + if (want_separator) + Separator(); + want_separator = true; + + bool append_to_sort_specs = g.IO.KeyShift; + if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs); + if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs); + } +#endif + + // Hiding / Visibility + if (flags_for_section_to_display & ImGuiTableFlags_Hideable) + { + if (want_separator) + Separator(); + want_separator = true; + + PushItemFlag(ImGuiItemFlags_AutoClosePopups, false); + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + { + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column->Flags & ImGuiTableColumnFlags_Disabled) + continue; + + const char* name = TableGetColumnName(table, other_column_n); + if (name == NULL || name[0] == 0) + name = ""; + + // Make sure we can't hide the last active column + bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; + if (other_column->IsUserEnabled && table->ColumnsEnabledCount <= 1) + menu_item_active = false; + if (MenuItem(name, NULL, other_column->IsUserEnabled, menu_item_active)) + other_column->IsUserEnabledNextFrame = !other_column->IsUserEnabled; + } + PopItemFlag(); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Settings (.ini data) +//------------------------------------------------------------------------- +// FIXME: The binding/finding/creating flow are too confusing. +//------------------------------------------------------------------------- +// - TableSettingsInit() [Internal] +// - TableSettingsCalcChunkSize() [Internal] +// - TableSettingsCreate() [Internal] +// - TableSettingsFindByID() [Internal] +// - TableGetBoundSettings() [Internal] +// - TableResetSettings() +// - TableSaveSettings() [Internal] +// - TableLoadSettings() [Internal] +// - TableSettingsHandler_ClearAll() [Internal] +// - TableSettingsHandler_ApplyAll() [Internal] +// - TableSettingsHandler_ReadOpen() [Internal] +// - TableSettingsHandler_ReadLine() [Internal] +// - TableSettingsHandler_WriteAll() [Internal] +// - TableSettingsInstallHandler() [Internal] +//------------------------------------------------------------------------- +// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +//------------------------------------------------------------------------- + +// Clear and initialize empty settings instance +static void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max) +{ + IM_PLACEMENT_NEW(settings) ImGuiTableSettings(); + ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings(); + for (int n = 0; n < columns_count_max; n++, settings_column++) + IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings(); + settings->ID = id; + settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count; + settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max; + settings->WantApply = true; +} + +static size_t TableSettingsCalcChunkSize(int columns_count) +{ + return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings); +} + +ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count) +{ + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count)); + TableSettingsInit(settings, id, columns_count, columns_count); + return settings; +} + +// Find existing settings +ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id) +{ + // FIXME-OPT: Might want to store a lookup map for this? + ImGuiContext& g = *GImGui; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID == id) + return settings; + return NULL; +} + +// Get settings for a given table, NULL if none +ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table) +{ + if (table->SettingsOffset != -1) + { + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + IM_ASSERT(settings->ID == table->ID); + if (settings->ColumnsCountMax >= table->ColumnsCount) + return settings; // OK + settings->ID = 0; // Invalidate storage, we won't fit because of a count change + } + return NULL; +} + +// Restore initial state of table (with or without saved settings) +void ImGui::TableResetSettings(ImGuiTable* table) +{ + table->IsInitializing = table->IsSettingsDirty = true; + table->IsResetAllRequest = false; + table->IsSettingsRequestLoad = false; // Don't reload from ini + table->SettingsLoadedFlags = ImGuiTableFlags_None; // Mark as nothing loaded so our initialized data becomes authoritative +} + +void ImGui::TableSaveSettings(ImGuiTable* table) +{ + table->IsSettingsDirty = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind or create settings data + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = TableGetBoundSettings(table); + if (settings == NULL) + { + settings = TableSettingsCreate(table->ID, table->ColumnsCount); + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount; + + // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings + IM_ASSERT(settings->ID == table->ID); + IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount); + ImGuiTableColumn* column = table->Columns.Data; + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + + bool save_ref_scale = false; + settings->SaveFlags = ImGuiTableFlags_None; + for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) + { + const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest; + column_settings->WidthOrWeight = width_or_weight; + column_settings->Index = (ImGuiTableColumnIdx)n; + column_settings->DisplayOrder = column->DisplayOrder; + column_settings->SortOrder = column->SortOrder; + column_settings->SortDirection = column->SortDirection; + column_settings->IsEnabled = column->IsUserEnabled; + column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; + if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0) + save_ref_scale = true; + + // We skip saving some data in the .ini file when they are unnecessary to restore our state. + // Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f. + // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. + if (width_or_weight != column->InitStretchWeightOrWidth) + settings->SaveFlags |= ImGuiTableFlags_Resizable; + if (column->DisplayOrder != n) + settings->SaveFlags |= ImGuiTableFlags_Reorderable; + if (column->SortOrder != -1) + settings->SaveFlags |= ImGuiTableFlags_Sortable; + if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) + settings->SaveFlags |= ImGuiTableFlags_Hideable; + } + settings->SaveFlags &= table->Flags; + settings->RefScale = save_ref_scale ? table->RefScale : 0.0f; + + MarkIniSettingsDirty(); +} + +void ImGui::TableLoadSettings(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + table->IsSettingsRequestLoad = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind settings + ImGuiTableSettings* settings; + if (table->SettingsOffset == -1) + { + settings = TableSettingsFindByID(table->ID); + if (settings == NULL) + return; + if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return... + table->IsSettingsDirty = true; + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + else + { + settings = TableGetBoundSettings(table); + } + + table->SettingsLoadedFlags = settings->SaveFlags; + table->RefScale = settings->RefScale; + + // Initialize default columns settings + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + TableInitColumnDefaults(table, column, ~0); + column->AutoFitQueue = 0x00; + } + + // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++) + { + int column_n = column_settings->Index; + if (column_n < 0 || column_n >= table->ColumnsCount) + continue; + + ImGuiTableColumn* column = &table->Columns[column_n]; + if (settings->SaveFlags & ImGuiTableFlags_Resizable) + { + if (column_settings->IsStretch) + column->StretchWeight = column_settings->WidthOrWeight; + else + column->WidthRequest = column_settings->WidthOrWeight; + } + if (settings->SaveFlags & ImGuiTableFlags_Reorderable) + column->DisplayOrder = column_settings->DisplayOrder; + if ((settings->SaveFlags & ImGuiTableFlags_Hideable) && column_settings->IsEnabled != -1) + column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled == 1; + column->SortOrder = column_settings->SortOrder; + column->SortDirection = column_settings->SortDirection; + } + + // Fix display order and build index + if (settings->SaveFlags & ImGuiTableFlags_Reorderable) + TableFixDisplayOrder(table); + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; +} + +struct ImGuiTableFixDisplayOrderColumnData +{ + ImGuiTableColumnIdx Idx; + ImGuiTable* Table; // This is unfortunate but we don't have userdata in qsort api. +}; + +// Sort by DisplayOrder and then Index +static int IMGUI_CDECL TableFixDisplayOrderComparer(const void* lhs, const void* rhs) +{ + const ImGuiTable* table = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Table; + const ImGuiTableColumnIdx lhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Idx; + const ImGuiTableColumnIdx rhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)rhs)->Idx; + const int order_delta = (table->Columns[lhs_idx].DisplayOrder - table->Columns[rhs_idx].DisplayOrder); + return (order_delta > 0) ? +1 : (order_delta < 0) ? -1 : (lhs_idx > rhs_idx) ? +1 : -1; +} + +// Fix invalid display order data: compact values (0,1,3 -> 0,1,2); preserve relative order (0,3,1 -> 0,2,1); deduplicate (0,4,1,1 -> 0,3,1,2) +void ImGui::TableFixDisplayOrder(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper. + ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)(void*)g.TempBuffer.Data; + for (int n = 0; n < table->ColumnsCount; n++) + { + fdo_columns[n].Idx = (ImGuiTableColumnIdx)n; + fdo_columns[n].Table = table; + } + ImQsort(fdo_columns, (size_t)table->ColumnsCount, sizeof(ImGuiTableFixDisplayOrderColumnData), TableFixDisplayOrderComparer); + for (int n = 0; n < table->ColumnsCount; n++) + table->Columns[fdo_columns[n].Idx].DisplayOrder = (ImGuiTableColumnIdx)n; +} + +static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetMapSize(); i++) + if (ImGuiTable* table = g.Tables.TryGetMapData(i)) + table->SettingsOffset = -1; + g.SettingsTables.clear(); +} + +// Apply to existing windows (if any) +static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetMapSize(); i++) + if (ImGuiTable* table = g.Tables.TryGetMapData(i)) + { + table->IsSettingsRequestLoad = true; + table->SettingsOffset = -1; + } +} + +static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiID id = 0; + int columns_count = 0; + if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2) + return NULL; + + if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id)) + { + if (settings->ColumnsCountMax >= columns_count) + { + TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle + return settings; + } + settings->ID = 0; // Invalidate storage, we won't fit because of a count change + } + return ImGui::TableSettingsCreate(id, columns_count); +} + +static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; + float f = 0.0f; + int column_n = 0, r = 0, n = 0; + + if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; } + + if (sscanf(line, "Column %d%n", &column_n, &r) == 1) + { + if (column_n < 0 || column_n >= settings->ColumnsCount) + return; + line = ImStrSkipBlank(line + r); + char c = 0; + ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; + column->Index = (ImGuiTableColumnIdx)column_n; + if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } + if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } + } +} + +static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + ImGuiContext& g = *ctx; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + { + if (settings->ID == 0) // Skip ditched settings + continue; + + // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + // (e.g. Order was unchanged) + const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0; + const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0; + const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0; + const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0; + // We need to save the [Table] entry even if all the bools are false, since this records a table with "default settings". + + buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve + buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount); + if (settings->RefScale != 0.0f) + buf->appendf("RefScale=%g\n", settings->RefScale); + ImGuiTableColumnSettings* column = settings->GetColumnSettings(); + for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++) + { + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + bool save_column = column->UserID != 0 || save_size || save_visible || save_order || (save_sort && column->SortOrder != -1); + if (!save_column) + continue; + buf->appendf("Column %-2d", column_n); + if (column->UserID != 0) { buf->appendf(" UserID=%08X", column->UserID); } + if (save_size && column->IsStretch) { buf->appendf(" Weight=%.4f", column->WidthOrWeight); } + if (save_size && !column->IsStretch) { buf->appendf(" Width=%d", (int)column->WidthOrWeight); } + if (save_visible) { buf->appendf(" Visible=%d", column->IsEnabled); } + if (save_order) { buf->appendf(" Order=%d", column->DisplayOrder); } + if (save_sort && column->SortOrder != -1) { buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); } + buf->append("\n"); + } + buf->append("\n"); + } +} + +void ImGui::TableSettingsAddSettingsHandler() +{ + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Table"; + ini_handler.TypeHash = ImHashStr("Table"); + ini_handler.ClearAllFn = TableSettingsHandler_ClearAll; + ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = TableSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = TableSettingsHandler_WriteAll; + AddSettingsHandler(&ini_handler); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Garbage Collection +//------------------------------------------------------------------------- +// - TableRemove() [Internal] +// - TableGcCompactTransientBuffers() [Internal] +// - TableGcCompactSettings() [Internal] +//------------------------------------------------------------------------- + +// Remove Table data (currently only used by TestEngine) +void ImGui::TableRemove(ImGuiTable* table) +{ + //IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table->ID); + ImGuiContext& g = *GImGui; + int table_idx = g.Tables.GetIndex(table); + //memset(table->RawData.Data, 0, table->RawData.size_in_bytes()); + //memset(table, 0, sizeof(ImGuiTable)); + g.Tables.Remove(table->ID, table); + g.TablesLastTimeActive[table_idx] = -1.0f; +} + +// Free up/compact internal Table buffers for when it gets unused +void ImGui::TableGcCompactTransientBuffers(ImGuiTable* table) +{ + //IMGUI_DEBUG_PRINT("TableGcCompactTransientBuffers() id=0x%08X\n", table->ID); + ImGuiContext& g = *GImGui; + IM_ASSERT(table->MemoryCompacted == false); + table->SortSpecs.Specs = NULL; + table->SortSpecsMulti.clear(); + table->IsSortSpecsDirty = true; // FIXME: In theory shouldn't have to leak into user performing a sort on resume. + table->ColumnsNames.clear(); + table->MemoryCompacted = true; + for (int n = 0; n < table->ColumnsCount; n++) + table->Columns[n].NameOffset = -1; + g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f; +} + +void ImGui::TableGcCompactTransientBuffers(ImGuiTableTempData* temp_data) +{ + temp_data->DrawSplitter.ClearFreeMemory(); + temp_data->LastTimeActive = -1.0f; +} + +// Compact and remove unused settings data (currently only used by TestEngine) +void ImGui::TableGcCompactSettings() +{ + ImGuiContext& g = *GImGui; + int required_memory = 0; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID != 0) + required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount); + if (required_memory == g.SettingsTables.Buf.Size) + return; + ImChunkStream new_chunk_stream; + new_chunk_stream.Buf.reserve(required_memory); + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID != 0) + memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount)); + g.SettingsTables.swap(new_chunk_stream); +} + + +//------------------------------------------------------------------------- +// [SECTION] Tables: Debugging +//------------------------------------------------------------------------- +// - DebugNodeTable() [Internal] +//------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + +static const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy) +{ + sizing_policy &= ImGuiTableFlags_SizingMask_; + if (sizing_policy == ImGuiTableFlags_SizingFixedFit) { return "FixedFit"; } + if (sizing_policy == ImGuiTableFlags_SizingFixedSame) { return "FixedSame"; } + if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return "StretchProp"; } + if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return "StretchSame"; } + return "N/A"; +} + +void ImGui::DebugNodeTable(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + const bool is_active = (table->LastFrameActive >= g.FrameCount - 2); // Note that fully clipped early out scrolling tables will appear as inactive here. + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode(table, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (IsItemHovered()) + GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); + if (IsItemVisible() && table->HoveredColumnBody != -1) + GetForegroundDrawList(table->OuterWindow)->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + if (!open) + return; + if (table->InstanceCurrent > 0) + Text("** %d instances of same table! Some data below will refer to last instance.", table->InstanceCurrent + 1); + if (g.IO.ConfigDebugIsDebuggerPresent) + { + if (DebugBreakButton("**DebugBreak**", "in BeginTable()")) + g.DebugBreakInTable = table->ID; + SameLine(); + } + + bool clear_settings = SmallButton("Clear settings"); + BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags)); + BulletText("ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : ""); + BulletText("CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX); + BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder); + BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn); + for (int n = 0; n < table->InstanceCurrent + 1; n++) + { + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, n); + BulletText("Instance %d: HoveredRow: %d, LastOuterHeight: %.2f", n, table_instance->HoveredRowLast, table_instance->LastOuterHeight); + } + //BulletText("BgDrawChannels: %d/%d", 0, table->BgDrawChannelUnfrozen); + float sum_weights = 0.0f; + for (int n = 0; n < table->ColumnsCount; n++) + if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch) + sum_weights += table->Columns[n].StretchWeight; + for (int n = 0; n < table->ColumnsCount; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + const char* name = TableGetColumnName(table, n); + char buf[512]; + ImFormatString(buf, IM_COUNTOF(buf), + "Column %d order %d '%s': offset %+.2f to %+.2f%s\n" + "Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n" + "WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n" + "MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\n" + "ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\n" + "Sort: %d%s, UserID: 0x%08X, Flags: 0x%04X: %s%s%s..", + n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? " (Frozen)" : "", + column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen, + column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f, + column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x, + column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX, + column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? " (Asc)" : (column->SortDirection == ImGuiSortDirection_Descending) ? " (Des)" : "", column->UserID, column->Flags, + (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", + (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", + (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); + Bullet(); + Selectable(buf); + if (IsItemHovered()) + { + ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y); + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255)); + } + } + if (ImGuiTableSettings* settings = TableGetBoundSettings(table)) + DebugNodeTableSettings(settings); + if (clear_settings) + table->IsResetAllRequest = true; + TreePop(); +} + +void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings) +{ + if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount)) + return; + BulletText("SaveFlags: 0x%08X", settings->SaveFlags); + BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax); + for (int n = 0; n < settings->ColumnsCount; n++) + { + ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; + ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None; + BulletText("Column %d Order %d SortOrder %d %s Vis %d %s %7.3f UserID 0x%08X", + n, column_settings->DisplayOrder, column_settings->SortOrder, + (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", + column_settings->IsEnabled, column_settings->IsStretch ? "Weight" : "Width ", column_settings->WidthOrWeight, column_settings->UserID); + } + TreePop(); +} + +#else // #ifndef IMGUI_DISABLE_DEBUG_TOOLS + +void ImGui::DebugNodeTable(ImGuiTable*) {} +void ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {} + +#endif + + +//------------------------------------------------------------------------- +// [SECTION] Columns, BeginColumns, EndColumns, etc. +// (This is a legacy API, prefer using BeginTable/EndTable!) +//------------------------------------------------------------------------- +// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.) +//------------------------------------------------------------------------- +// - SetWindowClipRectBeforeSetChannel() [Internal] +// - GetColumnIndex() +// - GetColumnsCount() +// - GetColumnOffset() +// - GetColumnWidth() +// - SetColumnOffset() +// - SetColumnWidth() +// - PushColumnClipRect() [Internal] +// - PushColumnsBackground() [Internal] +// - PopColumnsBackground() [Internal] +// - FindOrCreateColumns() [Internal] +// - GetColumnsID() [Internal] +// - BeginColumns() +// - NextColumn() +// - EndColumns() +// - Columns() +//------------------------------------------------------------------------- + +// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +// they would meddle many times with the underlying ImDrawCmd. +// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +// the subsequent single call to SetCurrentChannel() does it things once. +void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) +{ + ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); + window->ClipRect = clip_rect; + window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; + window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; +} + +float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm) +{ + return offset_norm * (columns->OffMaxX - columns->OffMinX); +} + +float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset) +{ + return offset / (columns->OffMaxX - columns->OffMinX); +} + +static const float COLUMNS_HIT_RECT_HALF_THICKNESS = 4.0f; + +static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. + IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + ImTrunc(COLUMNS_HIT_RECT_HALF_THICKNESS * g.CurrentDpiScale) - window->Pos.x; + x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); + if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths)) + x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); + + return x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return 0.0f; + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const float t = columns->Columns[column_index].OffsetNorm; + const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); + return x_offset; +} + +static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false) +{ + if (column_index < 0) + column_index = columns->Current; + + float offset_norm; + if (before_resize) + offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; + else + offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; + return ImGui::GetColumnOffsetFromNorm(columns, offset_norm); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return GetContentRegionAvail().x; + + if (column_index < 0) + column_index = columns->Current; + return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1); + const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; + + if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow)) + offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); + + if (preserve_width) + SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); +} + +void ImGui::SetColumnWidth(int column_index, float width) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); +} + +void ImGui::PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (column_index < 0) + column_index = columns->Current; + + ImGuiOldColumnData* column = &columns->Columns[column_index]; + PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); +} + +// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) +void ImGui::PushColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + columns->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, 0); +} + +void ImGui::PopColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); +} + +ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) +{ + // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. + for (int n = 0; n < window->ColumnsStorage.Size; n++) + if (window->ColumnsStorage[n].ID == id) + return &window->ColumnsStorage[n]; + + window->ColumnsStorage.push_back(ImGuiOldColumns()); + ImGuiOldColumns* columns = &window->ColumnsStorage.back(); + columns->ID = id; + return columns; +} + +ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) +{ + ImGuiWindow* window = GetCurrentWindow(); + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (str_id ? 0 : columns_count)); + ImGuiID id = window->GetID(str_id ? str_id : "columns"); + PopID(); + + return id; +} + +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(columns_count >= 1); + IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported + + // Acquire storage for the columns set + ImGuiID id = GetColumnsID(str_id, columns_count); + ImGuiOldColumns* columns = FindOrCreateColumns(window, id); + IM_ASSERT(columns->ID == id); + columns->Current = 0; + columns->Count = columns_count; + columns->Flags = flags; + window->DC.CurrentColumns = columns; + window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX(); + + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostInitialClipRect = window->ClipRect; + columns->HostBackupParentWorkRect = window->ParentWorkRect; + window->ParentWorkRect = window->WorkRect; + + // Set state for first column + // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect + const float column_padding = g.Style.ItemSpacing.x; + const float half_clip_extend_x = ImTrunc(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); + const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f); + const float max_2 = window->WorkRect.Max.x + half_clip_extend_x; + columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f); + columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + + // Clear data if columns count changed + if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) + columns->Columns.resize(0); + + // Initialize default widths + columns->IsFirstFrame = (columns->Columns.Size == 0); + if (columns->Columns.Size == 0) + { + columns->Columns.reserve(columns_count + 1); + for (int n = 0; n < columns_count + 1; n++) + { + ImGuiOldColumnData column; + column.OffsetNorm = n / (float)columns_count; + columns->Columns.push_back(column); + } + } + + for (int n = 0; n < columns_count; n++) + { + // Compute clipping rectangle + ImGuiOldColumnData* column = &columns->Columns[n]; + float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); + float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); + column->ClipRect.ClipWithFull(window->ClipRect); + } + + if (columns->Count > 1) + { + columns->Splitter.Split(window->DrawList, 1 + columns->Count); + columns->Splitter.SetCurrentChannel(window->DrawList, 1); + PushColumnClipRect(0); + } + + // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; + window->WorkRect.Max.y = window->ContentRegionRect.Max.y; +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.CurrentColumns == NULL) + return; + + ImGuiContext& g = *GImGui; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + + if (columns->Count == 1) + { + window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + IM_ASSERT(columns->Current == 0); + return; + } + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + + PopItemWidth(); + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + ImGuiOldColumnData* column = &columns->Columns[columns->Current]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); + + const float column_padding = g.Style.ItemSpacing.x; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + if (columns->Current > 0) + { + // Columns 1+ ignore IndentX (by canceling it out) + // FIXME-COLUMNS: Unnecessary, could be locked? + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; + } + else + { + // New row/line: column 0 honor IndentX. + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + window->DC.IsSameLine = false; + columns->LineMinY = columns->LineMaxY; + } + window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->DC.CursorPos.y = columns->LineMinY; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = 0.0f; + + // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; +} + +void ImGui::EndColumns() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + PopItemWidth(); + if (columns->Count > 1) + { + PopClipRect(); + columns->Splitter.Merge(window->DrawList); + } + + const ImGuiOldColumnFlags flags = columns->Flags; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = columns->LineMaxY; + if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent + + // Draw columns borders and handle resize + // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy + bool is_being_resized = false; + if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems) + { + // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. + const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); + const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); + int dragging_column = -1; + for (int n = 1; n < columns->Count; n++) + { + ImGuiOldColumnData* column = &columns->Columns[n]; + float x = window->Pos.x + GetColumnOffset(n); + const ImGuiID column_id = columns->ID + ImGuiID(n); + const float column_hit_hw = ImTrunc(COLUMNS_HIT_RECT_HALF_THICKNESS * g.CurrentDpiScale); + const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); + if (!ItemAdd(column_hit_rect, column_id, NULL, ImGuiItemFlags_NoNav)) + continue; + + bool hovered = false, held = false; + if (!(flags & ImGuiOldColumnFlags_NoResize)) + { + ButtonBehavior(column_hit_rect, column_id, &hovered, &held); + if (hovered || held) + SetMouseCursor(ImGuiMouseCursor_ResizeEW); + if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize)) + dragging_column = n; + } + + // Draw column + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + const float xi = IM_TRUNC(x); + window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); + } + + // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. + if (dragging_column != -1) + { + if (!columns->IsBeingResized) + for (int n = 0; n < columns->Count + 1; n++) + columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; + columns->IsBeingResized = is_being_resized = true; + float x = GetDraggedColumnOffset(columns, dragging_column); + SetColumnOffset(dragging_column, x); + } + } + columns->IsBeingResized = is_being_resized; + + window->WorkRect = window->ParentWorkRect; + window->ParentWorkRect = columns->HostBackupParentWorkRect; + window->DC.CurrentColumns = NULL; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + NavUpdateCurrentWindowIsScrollPushableX(); +} + +void ImGui::Columns(int columns_count, const char* id, bool borders) +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + ImGuiOldColumnFlags flags = (borders ? 0 : ImGuiOldColumnFlags_NoBorder); + //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) + return; + + if (columns != NULL) + EndColumns(); + + if (columns_count != 1) + BeginColumns(id, columns_count, flags); +} + +//------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imgui_widgets.cpp b/libs/imgui/imgui_widgets.cpp new file mode 100644 index 0000000..baf5a73 --- /dev/null +++ b/libs/imgui/imgui_widgets.cpp @@ -0,0 +1,10940 @@ +// dear imgui, v1.92.6 WIP +// (widgets code) + +/* + +Index of this file: + +// [SECTION] Forward Declarations +// [SECTION] Widgets: Text, etc. +// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +// [SECTION] Widgets: ComboBox +// [SECTION] Data Type and Data Formatting Helpers +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +// [SECTION] Widgets: InputText, InputTextMultiline +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +// [SECTION] Widgets: Selectable +// [SECTION] Widgets: Typing-Select support +// [SECTION] Widgets: Box-Select support +// [SECTION] Widgets: Multi-Select support +// [SECTION] Widgets: Multi-Select helpers +// [SECTION] Widgets: ListBox +// [SECTION] Widgets: PlotLines, PlotHistogram +// [SECTION] Widgets: Value helpers +// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. +// [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +// [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_internal.h" + +// System includes +#include // intptr_t + +//------------------------------------------------------------------------- +// Warnings +//------------------------------------------------------------------------- + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result +#endif + +//------------------------------------------------------------------------- +// Data +//------------------------------------------------------------------------- + +// Widgets +static const float DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f; // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior. +static const float DRAG_MOUSE_THRESHOLD_FACTOR = 0.50f; // Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags. + +// Those MIN/MAX values are not define because we need to point to them +static const signed char IM_S8_MIN = -128; +static const signed char IM_S8_MAX = 127; +static const unsigned char IM_U8_MIN = 0; +static const unsigned char IM_U8_MAX = 0xFF; +static const signed short IM_S16_MIN = -32768; +static const signed short IM_S16_MAX = 32767; +static const unsigned short IM_U16_MIN = 0; +static const unsigned short IM_U16_MAX = 0xFFFF; +static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); +static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) +static const ImU32 IM_U32_MIN = 0; +static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) +#ifdef LLONG_MIN +static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); +static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); +#else +static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; +static const ImS64 IM_S64_MAX = 9223372036854775807LL; +#endif +static const ImU64 IM_U64_MIN = 0; +#ifdef ULLONG_MAX +static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); +#else +static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); +#endif + +//------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//------------------------------------------------------------------------- + +// For InputTextEx() +static bool InputTextFilterCharacter(ImGuiContext* ctx, ImGuiInputTextState* state, unsigned int* p_char, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); +static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0); + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Text, etc. +//------------------------------------------------------------------------- +// - TextEx() [Internal] +// - TextUnformatted() +// - Text() +// - TextV() +// - TextColored() +// - TextColoredV() +// - TextDisabled() +// - TextDisabledV() +// - TextWrapped() +// - TextWrappedV() +// - LabelText() +// - LabelTextV() +// - BulletText() +// - BulletTextV() +//------------------------------------------------------------------------- + +void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + // Accept null ranges + if (text == text_end) + text = text_end = ""; + + // Calculate length + const char* text_begin = text; + if (text_end == NULL) + text_end = text + ImStrlen(text); // FIXME-OPT + + const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + const float wrap_pos_x = window->DC.TextWrapPos; + const bool wrap_enabled = (wrap_pos_x >= 0.0f); + if (text_end - text <= 2000 || wrap_enabled) + { + // Common case + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size, 0.0f); + if (!ItemAdd(bb, 0)) + return; + + // Render (we don't hide text after ## in this end-user function) + RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + } + else + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. + // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. + const char* line = text; + const float line_height = GetTextLineHeight(); + ImVec2 text_size(0, 0); + + // Lines to skip (can't skip when logging text) + ImVec2 pos = text_pos; + if (!g.LogEnabled) + { + int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped < lines_skippable) + { + const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + if (IsClippedEx(line_rect, 0)) + break; + + const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + RenderText(pos, line, line_end, false); + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + text_size.y = (pos - text_pos).y; + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size, 0.0f); + ItemAdd(bb, 0); + } +} + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const char* text, *text_end; + ImFormatStringToTempBufferV(&text, &text_end, fmt, args); + TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, col); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + const bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set + if (need_backup) + PushTextWrapPos(0.0f); + TextV(fmt, args); + if (need_backup) + PopTextWrapPos(); +} + +void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextAlignedV(align_x, size_x, fmt, args); + va_end(args); +} + +// align_x: 0.0f = left, 0.5f = center, 1.0f = right. +// size_x : 0.0f = shortcut for GetContentRegionAvail().x +// FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) +void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const char* text, *text_end; + ImFormatStringToTempBufferV(&text, &text_end, fmt, args); + const ImVec2 text_size = CalcTextSize(text, text_end); + size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x; + + ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y); + ImVec2 size(ImMin(size_x, text_size.x), text_size.y); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x); + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x); + if (align_x > 0.0f && text_size.x < size_x) + pos.x += ImTrunc((size_x - text_size.x) * align_x); + RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); + + const ImVec2 backup_max_pos = window->DC.CursorMaxPos; + ItemSize(size); + ItemAdd(ImRect(pos, pos + size), 0); + window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up. + + if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) + SetTooltip("%.*s", (int)(text_end - text), text); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float w = CalcItemWidth(); + + const char* value_text_begin, *value_text_end; + ImFormatStringToTempBufferV(&value_text_begin, &value_text_end, fmt, args); + const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImVec2 pos = window->DC.CursorPos; + const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2)); + const ImRect total_bb(pos, pos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, 0)) + return; + + // Render + RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin, *text_end; + ImFormatStringToTempBufferV(&text_begin, &text_end, fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y); // Empty text doesn't add padding + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrLineTextBaseOffset; + ItemSize(total_size, 0.0f); + const ImRect bb(pos, pos + total_size); + if (!ItemAdd(bb, 0)) + return; + + // Render + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col); + RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Main +//------------------------------------------------------------------------- +// - ButtonBehavior() [Internal] +// - Button() +// - SmallButton() +// - InvisibleButton() +// - ArrowButton() +// - CloseButton() [Internal] +// - CollapseButton() [Internal] +// - GetWindowScrollbarID() [Internal] +// - GetWindowScrollbarRect() [Internal] +// - Scrollbar() [Internal] +// - ScrollbarEx() [Internal] +// - Image() +// - ImageButton() +// - Checkbox() +// - CheckboxFlagsT() [Internal] +// - CheckboxFlags() +// - RadioButton() +// - ProgressBar() +// - Bullet() +// - Hyperlink() +//------------------------------------------------------------------------- + +// The ButtonBehavior() function is key to many interactions and used by many/most widgets. +// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_), +// this code is a little complex. +// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior. +// See the series of events below and the corresponding state reported by dear imgui: +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse is outside bb) - - - - - - +// Frame N+1 (mouse moves inside bb) - true - - - - +// Frame N+2 (mouse button is down) - true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+4 (mouse moves outside bb) - - true - - - +// Frame N+5 (mouse moves inside bb) - true true - - - +// Frame N+6 (mouse button is released) true true - - true - +// Frame N+7 (mouse button is released) - true - - - - +// Frame N+8 (mouse moves outside bb) - - - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) true true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) - true - - - true +// Frame N+3 (mouse button is down) - true - - - - +// Frame N+6 (mouse button is released) true true - - - - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse button is down) - true - - - true +// Frame N+1 (mouse button is down) - true - - - - +// Frame N+2 (mouse button is released) - true - - - - +// Frame N+3 (mouse button is released) - true - - - - +// Frame N+4 (mouse button is down) true true true true - true +// Frame N+5 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// Note that some combinations are supported, +// - PressedOnDragDropHold can generally be associated with any flag. +// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported. +//------------------------------------------------------------------------------------------------------------------------------------------------ +// The behavior of the return-value changes when ImGuiItemFlags_ButtonRepeat is set: +// Repeat+ Repeat+ Repeat+ Repeat+ +// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +//------------------------------------------------------------------------------------------------------------------------------------------------- +// Frame N+0 (mouse button is down) - true - true +// ... - - - - +// Frame N + RepeatDelay true true - true +// ... - - - - +// Frame N + RepeatDelay + RepeatRate*N true true - true +//------------------------------------------------------------------------------------------------------------------------------------------------- + +// - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc. +// And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);' +// For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading. +// - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature. +// One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior() +// with same ID and different MouseButton (see #8030). You can fix it by: +// (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. +// or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Default behavior inherited from item flags + // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that. + ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags); + if (flags & ImGuiButtonFlags_AllowOverlap) + item_flags |= ImGuiItemFlags_AllowOverlap; + if (item_flags & ImGuiItemFlags_NoFocus) + flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus; + + // Default only reacts to left mouse button + if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0) + flags |= ImGuiButtonFlags_MouseButtonLeft; + + // Default behavior requires click + release inside bounding box + if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0) + flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_; + + ImGuiWindow* backup_hovered_window = g.HoveredWindow; + const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree; + if (flatten_hovered_children) + g.HoveredWindow = window; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + // Alternate registration spot, for when caller didn't use ItemAdd() + if (g.LastItemData.ID != id) + IMGUI_TEST_ENGINE_ITEM_ADD(id, bb, NULL); +#endif + + bool pressed = false; + bool hovered = ItemHoverable(bb, id, item_flags); + + // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.) + // where holding the button pressed for a long time while drag a payload item triggers the button. + if (g.DragDropActive) + { + if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + { + hovered = true; + SetHoveredID(id); + if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER) + { + pressed = true; + g.DragDropHoldJustPressedId = id; + FocusWindow(window); + } + } + if (g.DragDropAcceptIdPrev == id && (g.DragDropAcceptFlagsPrev & ImGuiDragDropFlags_AcceptDrawAsHovered)) + hovered = true; + } + + if (flatten_hovered_children) + g.HoveredWindow = backup_hovered_window; + + // Mouse handling + const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id; + if (hovered) + { + IM_ASSERT(id != 0); // Lazily check inside rare path. + + // Poll mouse buttons + // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. + // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. + int mouse_button_clicked = -1; + int mouse_button_released = -1; + for (int button = 0; button < 3; button++) + if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here. + { + if (IsMouseClicked(button, ImGuiInputFlags_None, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; } + if (IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; } + } + + // Process initial action + const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt); + if (mods_ok) + { + if (mouse_button_clicked != -1 && g.ActiveId != id) + { + if (!(flags & ImGuiButtonFlags_NoSetKeyOwner)) + SetKeyOwner(MouseButtonToKey(mouse_button_clicked), id); + if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere)) + { + SetActiveID(id, window); + g.ActiveIdMouseButton = (ImS8)mouse_button_clicked; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + { + SetFocusID(id, window); + FocusWindow(window); + } + else if (!(flags & ImGuiButtonFlags_NoFocus)) + { + FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child + } + } + if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2)) + { + pressed = true; + if (flags & ImGuiButtonFlags_NoHoldingActiveId) + ClearActiveID(); + else + SetActiveID(id, window); // Hold on ID + g.ActiveIdMouseButton = (ImS8)mouse_button_clicked; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + { + SetFocusID(id, window); + FocusWindow(window); + } + else if (!(flags & ImGuiButtonFlags_NoFocus)) + { + FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child + } + } + } + if (flags & ImGuiButtonFlags_PressedOnRelease) + { + if (mouse_button_released != -1) + { + const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior + if (!has_repeated_at_least_once) + pressed = true; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); // FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. + ClearActiveID(); + } + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat)) + if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id)) + pressed = true; + } + + if (pressed && g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = false; + } + + // Keyboard/Gamepad navigation handling + // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. + if ((item_flags & ImGuiItemFlags_Disabled) == 0) + { + if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav) + if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus)) + hovered = true; + if (g.NavActivateDownId == id) + { + bool nav_activated_by_code = (g.NavActivateId == id); + bool nav_activated_by_inputs = (g.NavActivatePressedId == id); + if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat)) + { + // Avoid pressing multiple keys from triggering excessive amount of repeat events + const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space); + const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter); + const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate); + const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration); + nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; + } + if (nav_activated_by_code || nav_activated_by_inputs) + { + // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. + pressed = true; + SetActiveID(id, window); + g.ActiveIdSource = g.NavInputSource; + if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)) + SetFocusID(id, window); + if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut) + g.ActiveIdFromShortcut = true; + } + } + } + + // Process while held + bool held = false; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + + const int mouse_button = g.ActiveIdMouseButton; + if (mouse_button == -1) + { + // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304). + ClearActiveID(); + } + else if (IsMouseDown(mouse_button, test_owner_id)) + { + held = true; + } + else + { + bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0; + bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; + if ((release_in || release_anywhere) && !g.DragDropActive) + { + // Report as pressed when releasing the mouse (this is the most common path) + bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2; + bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps + bool is_button_avail_or_owned = TestKeyOwner(MouseButtonToKey(mouse_button), test_owner_id); + if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned) + pressed = true; + } + ClearActiveID(); + } + if (!(flags & ImGuiButtonFlags_NoNavFocus) && g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = false; + } + else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) + { + // When activated using Nav, we hold on the ActiveID until activation button is released + if (g.NavActivateDownId == id) + held = true; // hovered == true not true as we are already likely hovered on direct activation. + else + ClearActiveID(); + } + if (pressed) + g.ActiveIdHasBeenPressedBefore = true; + } + + // Activation highlight (this may be a remote activation) + if (g.NavHighlightActivatedId == id && (item_flags & ImGuiItemFlags_Disabled) == 0) + hovered = true; + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ItemSize(size, style.FramePadding.y); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavCursor(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + + if (g.LogEnabled) + LogSetNextTextDecoration("[", "]"); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, ImGuiButtonFlags_None); +} + +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; + return pressed; +} + +// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. +// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Ensure zero-size fits to contents + ImVec2 size = CalcItemSize(ImVec2(size_arg.x != 0.0f ? size_arg.x : -FLT_MIN, size_arg.y != 0.0f ? size_arg.y : -FLT_MIN), 0.0f, 0.0f); + + const ImGuiID id = window->GetID(str_id); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(size); + if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + RenderNavCursor(bb, id); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiID id = window->GetID(str_id); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + const float default_size = GetFrameHeight(); + ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderNavCursor(bb, id); + RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding); + RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) +{ + float sz = GetFrameHeight(); + return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None); +} + +// Button to close a window +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) + // This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? + const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize)); + ImRect bb_interact = bb; + const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea(); + if (area_to_visible_ratio < 1.5f) + bb_interact.Expand(ImTrunc(bb_interact.GetSize() * -0.25f)); + + // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window. + // (this isn't the common behavior of buttons, but it doesn't affect the user because navigation tends to keep items visible in scrolling layer). + bool is_clipped = !ItemAdd(bb_interact, id); + + bool hovered, held; + bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held); + if (is_clipped) + return pressed; + + // Render + ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); + if (hovered) + window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); + RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); + const ImU32 cross_col = GetColorU32(ImGuiCol_Text); + const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); + const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + const float cross_thickness = 1.0f; // FIXME-DPI + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness); + + return pressed; +} + +// The Collapse button also functions as a Dock Menu button. +bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize)); + bool is_clipped = !ItemAdd(bb, id); + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + if (is_clipped) + return pressed; + + // Render + //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed); + ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + if (hovered || held) + window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); + RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); + + if (dock_node) + RenderArrowDockMenu(window->DrawList, bb.Min, g.FontSize, text_col); + else + RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); + + // Switch to moving the window after mouse is moved beyond the initial drag threshold + if (IsItemActive() && IsMouseDragging(0)) + StartMouseMovingWindowOrNode(window, dock_node, true); // Undock from window/collapse menu button + + return pressed; +} + +ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis) +{ + return window->GetID(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY"); +} + +// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set. +ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + const ImRect outer_rect = window->Rect(); + const ImRect inner_rect = window->InnerRect; + const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar) + IM_ASSERT(scrollbar_size >= 0.0f); + const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f); + const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 0.0f; + if (axis == ImGuiAxis_X) + return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size); + else + return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y + border_top, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size); +} + +void ImGui::Scrollbar(ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = GetWindowScrollbarID(window, axis); + + // Calculate scrollbar bounding box + ImRect bb = GetWindowScrollbarRect(window, axis); + ImRect host_rect = (window->DockIsActive ? window->DockNode->HostWindow : window)->Rect(); + ImDrawFlags rounding_corners = CalcRoundingFlagsForRectInRect(bb, host_rect, g.Style.WindowBorderSize); + float size_visible = window->InnerRect.Max[axis] - window->InnerRect.Min[axis]; + float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f; + ImS64 scroll = (ImS64)window->Scroll[axis]; + ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_visible, (ImS64)size_contents, rounding_corners); + window->Scroll[axis] = (float)scroll; +} + +// Vertical/Horizontal scrollbar +// The entire piece of code below is rather confusing because: +// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +// Still, the code should probably be made simpler.. +bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags draw_rounding_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + const float bb_frame_width = bb_frame.GetWidth(); + const float bb_frame_height = bb_frame.GetHeight(); + if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f) + return false; + + // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab) + float alpha = 1.0f; + if ((axis == ImGuiAxis_Y) && bb_frame_height < bb_frame_width) + alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0f, 1.0f)); + if (alpha <= 0.0f) + return false; + + const ImGuiStyle& style = g.Style; + const bool allow_interaction = (alpha >= 1.0f); + + ImRect bb = bb_frame; + float padding = IM_TRUNC(ImMin(style.ScrollbarPadding, ImMin(bb_frame_width, bb_frame_height) * 0.5f)); + bb.Expand(-padding); + + // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) + const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight(); + if (scrollbar_size_v < 1.0f) + return false; + + // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + // But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. + const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1); + const float grab_h_minsize = ImMin(bb.GetSize()[axis], style.GrabMinSize); + const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), grab_h_minsize, scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; + + // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). + bool held = false; + bool hovered = false; + ItemAdd(bb_frame, id, NULL, ImGuiItemFlags_NoNav); + ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); + + const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_visible_v); + float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space + if (held && allow_interaction && grab_h_norm < 1.0f) + { + const float scrollbar_pos_v = bb.Min[axis]; + const float mouse_pos_v = g.IO.MousePos[axis]; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + + const int held_dir = (clicked_v_norm < grab_v_norm) ? -1 : (clicked_v_norm > grab_v_norm + grab_h_norm) ? +1 : 0; + if (g.ActiveIdIsJustActivated) + { + // On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab + const bool scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false || g.IO.KeyShift || held_dir == 0); + g.ScrollbarSeekMode = scroll_to_clicked_location ? 0 : (short)held_dir; + g.ScrollbarClickDeltaToGrabCenter = (held_dir == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f; + } + + // Apply scroll (p_scroll_v will generally point on one member of window->Scroll) + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position + if (g.ScrollbarSeekMode == 0) + { + // Absolute seeking + const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm)); + *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max); + } + else + { + // Page by page + if (IsMouseClicked(ImGuiMouseButton_Left, ImGuiInputFlags_Repeat) && held_dir == g.ScrollbarSeekMode) + { + float page_dir = (g.ScrollbarSeekMode > 0.0f) ? +1.0f : -1.0f; + *p_scroll_v = ImClamp(*p_scroll_v + (ImS64)(page_dir * size_visible_v), (ImS64)0, scroll_max); + } + } + + // Update values for rendering + scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + + // Update distance to grab now that we have seek'ed and saturated + //if (seek_absolute) + // g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; + } + + // Render + const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg); + const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); + window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags); + ImRect grab_rect; + if (axis == ImGuiAxis_X) + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y); + else + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels); + window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); + + return held; +} + +// - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples +// - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. +void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImVec2 padding(g.Style.ImageBorderSize, g.Style.ImageBorderSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + return; + + // Render + float rounding = g.Style.ImageRounding; + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col), rounding); + if (rounding > 0.0f) + window->DrawList->AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col), rounding); + else + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + if (g.Style.ImageBorderSize > 0.0f) + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), rounding, ImDrawFlags_None, g.Style.ImageBorderSize); +} + +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) +{ + ImageWithBg(tex_ref, image_size, uv0, uv1); +} + +// 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiContext& g = *GImGui; + PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f + PushStyleColor(ImGuiCol_Border, border_col); + ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); + PopStyleColor(); + PopStyleVar(); +} +#endif + +bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImVec2 padding = g.Style.FramePadding; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f); + ItemSize(bb); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavCursor(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); + float image_rounding = ImMax(g.Style.FrameRounding - ImMax(padding.x, padding.y), g.Style.ImageRounding); + if (image_rounding > 0.0f) + window->DrawList->AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col), image_rounding); + else + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + + return pressed; +} + +// - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button. +// - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design? +bool ImGui::ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col); +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// Legacy API obsoleted in 1.89. Two differences with new ImageButton() +// - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID) +// - new ImageButton() requires an explicit 'const char* str_id' +// - old ImageButton() had frame_padding' override argument. +// - new ImageButton() always use style.FramePadding. +/* +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + // Default to using texture ID as ID. User can still push string/integer prefixes. + PushID((ImTextureID)(intptr_t)user_texture_id); + if (frame_padding >= 0) + PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding)); + bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col); + if (frame_padding >= 0) + PopStyleVar(); + PopID(); + return ret; +} +*/ +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); + const bool is_visible = ItemAdd(total_bb, id); + const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; + if (!is_visible) + if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support + { + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); + return false; + } + + // Range-Selection/Multi-selection support (header) + bool checked = *v; + if (is_multi_select) + MultiSelectItemHeader(id, &checked, NULL); + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + + // Range-Selection/Multi-selection support (footer) + if (is_multi_select) + MultiSelectItemFooter(id, &checked, &pressed); + else if (pressed) + checked = !checked; + + if (*v != checked) + { + *v = checked; + pressed = true; // return value + MarkItemEdited(id); + } + + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0; + if (is_visible) + { + RenderNavCursor(total_bb, id); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); + if (mixed_value) + { + // Undocumented tristate/mixed/indeterminate checkbox (#2644) + // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) + ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f))); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); + } + else if (*v) + { + const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); + RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); + } + } + const ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + if (g.LogEnabled) + LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]"); + if (is_visible && label_size.x > 0.0f) + RenderText(label_pos, label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); + return pressed; +} + +template +bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value) +{ + bool all_on = (*flags & flags_value) == flags_value; + bool any_on = (*flags & flags_value) != 0; + bool pressed; + if (!all_on && any_on) + { + ImGuiContext& g = *GImGui; + g.NextItemData.ItemFlags |= ImGuiItemFlags_MixedValue; + pressed = Checkbox(label, &all_on); + } + else + { + pressed = Checkbox(label, &all_on); + + } + if (pressed) + { + if (all_on) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = IM_ROUND(center.x); + center.y = IM_ROUND(center.y); + const float radius = (square_sz - 1.0f) * 0.5f; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + MarkItemEdited(id); + + RenderNavCursor(total_bb, id); + const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius); + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), num_segment); + if (active) + { + const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark)); + } + + if (style.FrameBorderSize > 0.0f) + { + window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), num_segment, style.FrameBorderSize); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), num_segment, style.FrameBorderSize); + } + + ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + if (g.LogEnabled) + LogRenderedText(&label_pos, active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(label_pos, label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +// FIXME: This would work nicely if it was a public template, e.g. 'template RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it.. +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = RadioButton(label, *v == v_button); + if (pressed) + *v = v_button; + return pressed; +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f); + ImRect bb(pos, pos + size); + ItemSize(size, style.FramePadding.y); + if (!ItemAdd(bb, 0)) + return; + + // Fraction < 0.0f will display an indeterminate progress bar animation + // The value must be animated along with time, so e.g. passing '-1.0f * ImGui::GetTime()' as fraction works. + const bool is_indeterminate = (fraction < 0.0f); + if (!is_indeterminate) + fraction = ImSaturate(fraction); + + // Out of courtesy we accept a NaN fraction without crashing + float fill_n0 = 0.0f; + float fill_n1 = (fraction == fraction) ? fraction : 0.0f; + + if (is_indeterminate) + { + const float fill_width_n = 0.2f; + fill_n0 = ImFmod(-fraction, 1.0f) * (1.0f + fill_width_n) - fill_width_n; + fill_n1 = ImSaturate(fill_n0 + fill_width_n); + fill_n0 = ImSaturate(fill_n0); + } + + // Render + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); + float fill_x0 = ImLerp(bb.Min.x, bb.Max.x, fill_n0); + float fill_x1 = ImLerp(bb.Min.x, bb.Max.x, fill_n1); + if (fill_x0 < fill_x1) + RenderRectFilledInRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_x0, fill_x1, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + // Don't display text for indeterminate bars by default + char overlay_buf[32]; + if (!is_indeterminate || overlay != NULL) + { + if (!overlay) + { + ImFormatString(overlay_buf, IM_COUNTOF(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + { + float text_x = is_indeterminate ? (bb.Min.x + bb.Max.x - overlay_size.x) * 0.5f : fill_x1 + style.ItemSpacing.x; + RenderTextClipped(ImVec2(ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb); + } + } +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + { + SameLine(0, style.FramePadding.x * 2); + return; + } + + // Render and stay on same line + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col); + SameLine(0, style.FramePadding.x * 2.0f); +} + +// This is provided as a convenience for being an often requested feature. +// FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system. +// Because of this we currently don't provide many styling options for this widget +// (e.g. hovered/active colors are automatically inferred from a single color). +bool ImGui::TextLink(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(label); + const char* label_end = FindRenderedTextEnd(label); + + ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 size = CalcTextSize(label, label_end, true); + ImRect bb(pos, pos + size); + ItemSize(size, 0.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderNavCursor(bb, id); + + if (hovered) + SetMouseCursor(ImGuiMouseCursor_Hand); + + ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink]; + ImVec4 line_colf = text_colf; + { + // FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets, + // as we are currently experimenting/planning a different styling system. + float h, s, v; + ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z, h, s, v); + if (held || hovered) + { + v = ImSaturate(v + (held ? 0.4f : 0.3f)); + h = ImFmod(h + 0.02f, 1.0f); + } + ColorConvertHSVtoRGB(h, s, v, text_colf.x, text_colf.y, text_colf.z); + v = ImSaturate(v - 0.20f); + ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); + } + + float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); + window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI + + PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); + RenderText(bb.Min, label, label_end); + PopStyleColor(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::TextLinkOpenURL(const char* label, const char* url) +{ + ImGuiContext& g = *GImGui; + if (url == NULL) + url = label; + bool pressed = TextLink(label); + if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL) + g.PlatformIO.Platform_OpenInShellFn(&g, url); + SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label + if (BeginPopupContextItem()) + { + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink))) + SetClipboardText(url); + EndPopup(); + } + return pressed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Low-level Layout helpers +//------------------------------------------------------------------------- +// - Spacing() +// - Dummy() +// - NewLine() +// - AlignTextToFramePadding() +// - SeparatorEx() [Internal] +// - Separator() +// - SplitterBehavior() [Internal] +// - ShrinkWidths() [Internal] +//------------------------------------------------------------------------- + +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ItemSize(ImVec2(0, 0)); +} + +void ImGui::Dummy(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(size); + ItemAdd(bb, 0); +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.IsSameLine = false; + if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0, 0)); + else + ItemSize(ImVec2(0.0f, g.FontSize)); + window->DC.LayoutType = backup_layout_type; +} + +void ImGui::AlignTextToFramePadding() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); +} + +// Horizontal/vertical separating line +// FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues. +// Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are. +void ImGui::SeparatorEx(ImGuiSeparatorFlags flags, float thickness) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected + IM_ASSERT(thickness > 0.0f); + + if (flags & ImGuiSeparatorFlags_Vertical) + { + // Vertical separator, for menu bars (use current line height). + float y1 = window->DC.CursorPos.y; + float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y; + const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness, y2)); + ItemSize(ImVec2(thickness, 0.0f)); + if (!ItemAdd(bb, 0)) + return; + + // Draw + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogText(" |"); + } + else if (flags & ImGuiSeparatorFlags_Horizontal) + { + // Horizontal Separator + float x1 = window->DC.CursorPos.x; + float x2 = window->WorkRect.Max.x; + + // Preserve legacy behavior inside Columns() + // Before Tables API happened, we relied on Separator() to span all columns of a Columns() set. + // We currently don't need to provide the same feature for tables because tables naturally have border features. + ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; + if (columns) + { + x1 = window->Pos.x + window->DC.Indent.x; // Used to be Pos.x before 2023/10/03 + x2 = window->Pos.x + window->Size.x; + PushColumnsBackground(); + } + + // We don't provide our width to the layout so that it doesn't get feed back into AutoFit + // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell) + const float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change. + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness)); + ItemSize(ImVec2(0.0f, thickness_for_layout)); + + if (ItemAdd(bb, 0)) + { + // Draw + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogRenderedText(&bb.Min, "--------------------------------\n"); + + } + if (columns) + { + PopColumnsBackground(); + columns->LineMinY = window->DC.CursorPos.y; + } + } +} + +void ImGui::Separator() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + // Those flags should eventually be configurable by the user + // FIXME: We cannot g.Style.SeparatorTextBorderSize for thickness as it relates to SeparatorText() which is a decorated separator, not defaulting to 1.0f. + ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; + + // Only applies to legacy Columns() api as they relied on Separator() a lot. + if (window->DC.CurrentColumns) + flags |= ImGuiSeparatorFlags_SpanAllColumns; + + SeparatorEx(flags, 1.0f); +} + +void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStyle& style = g.Style; + + const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImVec2 pos = window->DC.CursorPos; + const ImVec2 padding = style.SeparatorTextPadding; + + const float separator_thickness = style.SeparatorTextBorderSize; + const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness)); + const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y)); + const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)); + ItemSize(min_size, text_baseline_y); + if (!ItemAdd(bb, id)) + return; + + const float sep1_x1 = pos.x; + const float sep2_x2 = bb.Max.x; + const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.99999f); + + const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f); + const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN + + // This allows using SameLine() to position something in the 'extra_w' + window->DC.CursorPosPrevLine.x = label_pos.x + label_size.x; + + const ImU32 separator_col = GetColorU32(ImGuiCol_Separator); + if (label_size.x > 0.0f) + { + const float sep1_x2 = label_pos.x - style.ItemSpacing.x; + const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x; + if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f) + window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep1_x2, seps_y), separator_col, separator_thickness); + if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f) + window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness); + if (g.LogEnabled) + LogSetNextTextDecoration("---", NULL); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size); + } + else + { + if (g.LogEnabled) + LogText("---"); + if (separator_thickness > 0.0f) + window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness); + } +} + +void ImGui::SeparatorText(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want: + // - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight) + // - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string) + // - because of this we probably can't turn 'const char* label' into 'const char* fmt, ...' + // Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item, + // and then we can turn this into a format function. + SeparatorTextEx(0, label, FindRenderedTextEnd(label), 0.0f); +} + +// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. +bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay, ImU32 bg_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (!ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav)) + return false; + + // FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags_AllowOverlap here is + // to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item. + // Nowadays we would instead want to use SetNextItemAllowOverlap() before the item. + ImGuiButtonFlags button_flags = ImGuiButtonFlags_FlattenChildren; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + button_flags |= ImGuiButtonFlags_AllowOverlap; +#endif + + bool hovered, held; + ImRect bb_interact = bb; + bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f)); + ButtonBehavior(bb_interact, id, &hovered, &held, button_flags); + if (hovered) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb + + if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay)) + SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + + ImRect bb_render = bb; + if (held) + { + float mouse_delta = (g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min)[axis]; + + // Minimum pane size + float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); + float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); + if (mouse_delta < -size_1_maximum_delta) + mouse_delta = -size_1_maximum_delta; + if (mouse_delta > size_2_maximum_delta) + mouse_delta = size_2_maximum_delta; + + // Apply resize + if (mouse_delta != 0.0f) + { + *size1 = ImMax(*size1 + mouse_delta, min_size1); + *size2 = ImMax(*size2 - mouse_delta, min_size2); + bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta)); + MarkItemEdited(id); + } + } + + // Render at new position + if (bg_col & IM_COL32_A_MASK) + window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0f); + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f); + + return held; +} + +static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) +{ + const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs; + const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs; + if (int d = (int)(b->Width - a->Width)) + return d; + return b->Index - a->Index; +} + +// Shrink excess width from a set of item, by removing width from the larger items first. +// Set items Width to -1.0f to disable shrinking this item. +void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min) +{ + if (count == 1) + { + if (items[0].Width >= 0.0f) + items[0].Width = ImMax(items[0].Width - width_excess, width_min); + return; + } + ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last. + int count_same_width = 1; + while (width_excess > 0.001f && count_same_width < count) + { + while (count_same_width < count && items[0].Width <= items[count_same_width].Width) + count_same_width++; + float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + max_width_to_remove_per_item = ImMin(items[0].Width - width_min, max_width_to_remove_per_item); + if (max_width_to_remove_per_item <= 0.0f) + break; + float base_width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); + for (int item_n = 0; item_n < count_same_width; item_n++) + { + float width_to_remove_for_this_item = ImMin(base_width_to_remove_per_item, items[item_n].Width - width_min); + items[item_n].Width -= width_to_remove_for_this_item; + width_excess -= width_to_remove_for_this_item; + } + } + + // Round width and redistribute remainder + // Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. + width_excess = 0.0f; + for (int n = 0; n < count; n++) + { + float width_rounded = ImTrunc(items[n].Width); + width_excess += items[n].Width - width_rounded; + items[n].Width = width_rounded; + } + while (width_excess > 0.0f) + for (int n = 0; n < count && width_excess > 0.0f; n++) + { + float width_to_add = ImMin(items[n].InitialWidth - items[n].Width, 1.0f); + items[n].Width += width_to_add; + width_excess -= width_to_add; + } +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ComboBox +//------------------------------------------------------------------------- +// - CalcMaxPopupHeightFromItemCount() [Internal] +// - BeginCombo() +// - BeginComboPopup() [Internal] +// - EndCombo() +// - BeginComboPreview() [Internal] +// - EndComboPreview() [Internal] +// - Combo() +//------------------------------------------------------------------------- + +static float CalcMaxPopupHeightFromItemCount(int items_count) +{ + ImGuiContext& g = *GImGui; + if (items_count <= 0) + return FLT_MAX; + return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); +} + +bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.HasFlags; + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together + if (flags & ImGuiComboFlags_WidthFitPreview) + IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0); + + const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && (preview_value != NULL)) ? CalcTextSize(preview_value, NULL, true).x : 0.0f; + const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : ((flags & ImGuiComboFlags_WidthFitPreview) ? (arrow_size + preview_width + style.FramePadding.x * 2.0f) : CalcItemWidth()); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &bb)) + return false; + + // Open on click + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const ImGuiID popup_id = ImHashStr("##ComboPopup", 0, id); + bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None); + if (pressed && !popup_open) + { + OpenPopupEx(popup_id, ImGuiPopupFlags_None); + popup_open = true; + } + + // Render shape + const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size); + RenderNavCursor(bb, id); + if (!(flags & ImGuiComboFlags_NoPreview)) + window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft); + if (!(flags & ImGuiComboFlags_NoArrowButton)) + { + ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight); + if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x) + RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); + } + RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding); + + // Custom preview + if (flags & ImGuiComboFlags_CustomPreview) + { + g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y); + IM_ASSERT(preview_value == NULL || preview_value[0] == 0); + preview_value = NULL; + } + + // Render preview and label + if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) + { + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL); + } + if (label_size.x > 0) + RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label); + + if (!popup_open) + return false; + + g.NextWindowData.HasFlags = backup_next_window_data_flags; + return BeginComboPopup(popup_id, bb, flags); +} + +bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); + return false; + } + + // Set popup size + float w = bb.GetWidth(); + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint) + { + g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); + } + else + { + if ((flags & ImGuiComboFlags_HeightMask_) == 0) + flags |= ImGuiComboFlags_HeightRegular; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one + int popup_max_height_in_items = -1; + if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8; + else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; + else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; + ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX); + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size + constraint_min.x = w; + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f) + constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items); + SetNextWindowSizeConstraints(constraint_min, constraint_max); + } + + // This is essentially a specialized version of BeginPopupEx() + char name[16]; + ImFormatString(name, IM_COUNTOF(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth + + // Set position given a custom constraint (peak into expected window size so we can position it) + // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? + // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()? + if (ImGuiWindow* popup_window = FindWindowByName(name)) + if (popup_window->WasActive) + { + // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. + ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window); + popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = "Below, Toward Left", Down = "Below, Toward Right (default)" + ImRect r_outer = GetPopupAllowedExtentRect(popup_window); + ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox); + SetNextWindowPos(pos); + } + + // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx() + ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove; + PushStyleVarX(ImGuiStyleVar_WindowPadding, g.Style.FramePadding.x); // Horizontally align ourselves with the framed text + bool ret = Begin(name, NULL, window_flags); + PopStyleVar(); + if (!ret) + { + EndPopup(); + if (!g.IO.ConfigDebugBeginReturnValueOnce && !g.IO.ConfigDebugBeginReturnValueLoop) // Begin may only return false with those debug tools activated. + IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above + return false; + } + g.BeginComboDepth++; + return true; +} + +void ImGui::EndCombo() +{ + ImGuiContext& g = *GImGui; + g.BeginComboDepth--; + char name[16]; + ImFormatString(name, IM_COUNTOF(name), "##Combo_%02d", g.BeginComboDepth); // FIXME: Move those to helpers? + if (strcmp(g.CurrentWindow->Name, name) != 0) + IM_ASSERT_USER_ERROR_RET(0, "Calling EndCombo() in wrong window!"); + EndPopup(); +} + +// Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements +// (Experimental, see GitHub issues: #1658, #4168) +bool ImGui::BeginComboPreview() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiComboPreviewData* preview_data = &g.ComboPreviewData; + + if (window->SkipItems || !(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)) + return false; + IM_ASSERT(g.LastItemData.Rect.Min.x == preview_data->PreviewRect.Min.x && g.LastItemData.Rect.Min.y == preview_data->PreviewRect.Min.y); // Didn't call after BeginCombo/EndCombo block or forgot to pass ImGuiComboFlags_CustomPreview flag? + if (!window->ClipRect.Overlaps(preview_data->PreviewRect)) // Narrower test (optional) + return false; + + // FIXME: This could be contained in a PushWorkRect() api + preview_data->BackupCursorPos = window->DC.CursorPos; + preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos; + preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine; + preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; + preview_data->BackupLayout = window->DC.LayoutType; + window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.IsSameLine = false; + PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true); + + return true; +} + +void ImGui::EndComboPreview() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiComboPreviewData* preview_data = &g.ComboPreviewData; + + // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future + ImDrawList* draw_list = window->DrawList; + if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y) + if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command + { + draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect; + draw_list->_TryMergeDrawCmds(); + } + PopClipRect(); + window->DC.CursorPos = preview_data->BackupCursorPos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos); + window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine; + window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset; + window->DC.LayoutType = preview_data->BackupLayout; + window->DC.IsSameLine = false; + preview_data->PreviewRect = ImRect(); +} + +// Getter for the old Combo() API: const char*[] +static const char* Items_ArrayGetter(void* data, int idx) +{ + const char* const* items = (const char* const*)data; + return items[idx]; +} + +// Getter for the old Combo() API: "item1\0item2\0item3\0" +static const char* Items_SingleStringGetter(void* data, int idx) +{ + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += ImStrlen(p) + 1; + items_count++; + } + return *p ? p : NULL; +} + +// Old API, prefer using BeginCombo() nowadays if you can. +bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items) +{ + ImGuiContext& g = *GImGui; + + // Call the getter to obtain the preview string which is a parameter to BeginCombo() + const char* preview_value = NULL; + if (*current_item >= 0 && *current_item < items_count) + preview_value = getter(user_data, *current_item); + + // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. + if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)) + SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + + if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) + return false; + + // Display items + bool value_changed = false; + ImGuiListClipper clipper; + clipper.Begin(items_count); + clipper.IncludeItemByIndex(*current_item); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const char* item_text = getter(user_data, i); + if (item_text == NULL) + item_text = "*Unknown item*"; + + PushID(i); + const bool item_selected = (i == *current_item); + if (Selectable(item_text, item_selected) && *current_item != i) + { + value_changed = true; + *current_item = i; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + + EndCombo(); + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) +{ + const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); + return value_changed; +} + +// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0" +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + while (*p) + { + p += ImStrlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + return value_changed; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +struct ImGuiGetNameFromIndexOldToNewCallbackData { void* UserData; bool (*OldCallback)(void*, int, const char**); }; +static const char* ImGuiGetNameFromIndexOldToNewCallback(void* user_data, int idx) +{ + ImGuiGetNameFromIndexOldToNewCallbackData* data = (ImGuiGetNameFromIndexOldToNewCallbackData*)user_data; + const char* s = NULL; + data->OldCallback(data->UserData, idx, &s); + return s; +} + +bool ImGui::ListBox(const char* label, int* current_item, bool (*old_getter)(void*, int, const char**), void* user_data, int items_count, int height_in_items) +{ + ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter }; + return ListBox(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, height_in_items); +} +bool ImGui::Combo(const char* label, int* current_item, bool (*old_getter)(void*, int, const char**), void* user_data, int items_count, int popup_max_height_in_items) +{ + ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter }; + return Combo(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, popup_max_height_in_items); +} + +#endif + +//------------------------------------------------------------------------- +// [SECTION] Data Type and Data Formatting Helpers [Internal] +//------------------------------------------------------------------------- +// - DataTypeGetInfo() +// - DataTypeFormatString() +// - DataTypeApplyOp() +// - DataTypeApplyFromText() +// - DataTypeCompare() +// - DataTypeClamp() +// - GetMinimumStepAtDecimalPrecision +// - RoundScalarWithFormat<>() +//------------------------------------------------------------------------- + +static const ImU32 GDefaultRgbaColorMarkers[4] = +{ + IM_COL32(240,20,20,255), IM_COL32(20,240,20,255), IM_COL32(20,20,240,255), IM_COL32(140,140,140,255) +}; + +static const ImGuiDataTypeInfo GDataTypeInfo[] = +{ + { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8 + { sizeof(unsigned char), "U8", "%u", "%u" }, + { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16 + { sizeof(unsigned short), "U16", "%u", "%u" }, + { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32 + { sizeof(unsigned int), "U32", "%u", "%u" }, +#ifdef _MSC_VER + { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%I64u","%I64u" }, +#else + { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%llu", "%llu" }, +#endif + { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) + { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double + { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool + { 0, "char*","%s", "%s" }, // ImGuiDataType_String +}; +IM_STATIC_ASSERT(IM_COUNTOF(GDataTypeInfo) == ImGuiDataType_COUNT); + +const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type) +{ + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + return &GDataTypeInfo[data_type]; +} + +int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format) +{ + // Signedness doesn't matter when pushing integer arguments + if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) + return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data); + if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) + return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data); + if (data_type == ImGuiDataType_Float) + return ImFormatString(buf, buf_size, format, *(const float*)p_data); + if (data_type == ImGuiDataType_Double) + return ImFormatString(buf, buf_size, format, *(const double*)p_data); + if (data_type == ImGuiDataType_S8) + return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data); + if (data_type == ImGuiDataType_U8) + return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data); + if (data_type == ImGuiDataType_S16) + return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data); + if (data_type == ImGuiDataType_U16) + return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data); + IM_ASSERT(0); + return 0; +} + +void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2) +{ + IM_ASSERT(op == '+' || op == '-'); + switch (data_type) + { + case ImGuiDataType_S8: + if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } + if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } + return; + case ImGuiDataType_U8: + if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } + if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } + return; + case ImGuiDataType_S16: + if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } + if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } + return; + case ImGuiDataType_U16: + if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } + if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } + return; + case ImGuiDataType_S32: + if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } + if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } + return; + case ImGuiDataType_U32: + if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } + if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } + return; + case ImGuiDataType_S64: + if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } + if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } + return; + case ImGuiDataType_U64: + if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } + if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } + return; + case ImGuiDataType_Float: + if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; } + if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; } + return; + case ImGuiDataType_Double: + if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } + if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; } + return; + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); +} + +// User can input math operators (e.g. +100) to edit a numerical values. +// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. +bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty) +{ + // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. + const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); + ImGuiDataTypeStorage data_backup; + memcpy(&data_backup, p_data, type_info->Size); + + while (ImCharIsBlankA(*buf)) + buf++; + if (!buf[0]) + { + if (p_data_when_empty != NULL) + { + memcpy(p_data, p_data_when_empty, type_info->Size); + return memcmp(&data_backup, p_data, type_info->Size) != 0; + } + return false; + } + + // Sanitize format + // - For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf + // - In theory could treat empty format as using default, but this would only cover rare/bizarre case of using InputScalar() + integer + format string without %. + char format_sanitized[32]; + if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) + format = type_info->ScanFmt; + else + format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_COUNTOF(format_sanitized)); + + // Small types need a 32-bit buffer to receive the result from scanf() + int v32 = 0; + if (sscanf(buf, format, type_info->Size >= 4 ? p_data : &v32) < 1) + return false; + if (type_info->Size < 4) + { + if (data_type == ImGuiDataType_S8) + *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX); + else if (data_type == ImGuiDataType_U8) + *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX); + else if (data_type == ImGuiDataType_S16) + *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX); + else if (data_type == ImGuiDataType_U16) + *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX); + else + IM_ASSERT(0); + } + + return memcmp(&data_backup, p_data, type_info->Size) != 0; +} + +template +static int DataTypeCompareT(const T* lhs, const T* rhs) +{ + if (*lhs < *rhs) return -1; + if (*lhs > *rhs) return +1; + return 0; +} + +int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeCompareT((const ImS8* )arg_1, (const ImS8* )arg_2); + case ImGuiDataType_U8: return DataTypeCompareT((const ImU8* )arg_1, (const ImU8* )arg_2); + case ImGuiDataType_S16: return DataTypeCompareT((const ImS16* )arg_1, (const ImS16* )arg_2); + case ImGuiDataType_U16: return DataTypeCompareT((const ImU16* )arg_1, (const ImU16* )arg_2); + case ImGuiDataType_S32: return DataTypeCompareT((const ImS32* )arg_1, (const ImS32* )arg_2); + case ImGuiDataType_U32: return DataTypeCompareT((const ImU32* )arg_1, (const ImU32* )arg_2); + case ImGuiDataType_S64: return DataTypeCompareT((const ImS64* )arg_1, (const ImS64* )arg_2); + case ImGuiDataType_U64: return DataTypeCompareT((const ImU64* )arg_1, (const ImU64* )arg_2); + case ImGuiDataType_Float: return DataTypeCompareT((const float* )arg_1, (const float* )arg_2); + case ImGuiDataType_Double: return DataTypeCompareT((const double*)arg_1, (const double*)arg_2); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return 0; +} + +template +static bool DataTypeClampT(T* v, const T* v_min, const T* v_max) +{ + // Clamp, both sides are optional, return true if modified + if (v_min && *v < *v_min) { *v = *v_min; return true; } + if (v_max && *v > *v_max) { *v = *v_max; return true; } + return false; +} + +bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeClampT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return DataTypeClampT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return DataTypeClampT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return DataTypeClampT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return DataTypeClampT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return DataTypeClampT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return DataTypeClampT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return DataTypeClampT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return DataTypeClampT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return DataTypeClampT((double*)p_data, (const double*)p_min, (const double*)p_max); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +bool ImGui::DataTypeIsZero(ImGuiDataType data_type, const void* p_data) +{ + ImGuiContext& g = *GImGui; + return DataTypeCompare(data_type, p_data, &g.DataTypeZeroValue) == 0; +} + +static float GetMinimumStepAtDecimalPrecision(int decimal_precision) +{ + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + if (decimal_precision < 0) + return FLT_MIN; + return (decimal_precision < IM_COUNTOF(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); +} + +template +TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v) +{ + IM_UNUSED(data_type); + IM_ASSERT(data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const char* fmt_start = ImParseFormatFindStart(format); + if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string + return v; + + // Sanitize format + char fmt_sanitized[32]; + ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_COUNTOF(fmt_sanitized)); + fmt_start = fmt_sanitized; + + // Format value with our rounding, and read back + char v_str[64]; + ImFormatString(v_str, IM_COUNTOF(v_str), fmt_start, v); + const char* p = v_str; + while (*p == ' ') + p++; + v = (TYPE)ImAtof(p); + + return v; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +//------------------------------------------------------------------------- +// - DragBehaviorT<>() [Internal] +// - DragBehavior() [Internal] +// - DragScalar() +// - DragScalarN() +// - DragFloat() +// - DragFloat2() +// - DragFloat3() +// - DragFloat4() +// - DragFloatRange2() +// - DragInt() +// - DragInt2() +// - DragInt3() +// - DragInt4() +// - DragIntRange2() +//------------------------------------------------------------------------- + +// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) +template +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_bounded = (v_min < v_max) || ((v_min == v_max) && (v_min != 0.0f || (flags & ImGuiSliderFlags_ClampZeroRange))); + const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + + // Default tweak speed + if (v_speed == 0.0f && is_bounded && (v_max - v_min < FLT_MAX)) + v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); + + // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings + float adjust_delta = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR)) + { + adjust_delta = g.IO.MouseDelta[axis]; + if (g.IO.KeyAlt && !(flags & ImGuiSliderFlags_NoSpeedTweaks)) + adjust_delta *= 1.0f / 100.0f; + if (g.IO.KeyShift && !(flags & ImGuiSliderFlags_NoSpeedTweaks)) + adjust_delta *= 10.0f; + } + else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) + { + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0; + const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow); + const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast); + const float tweak_factor = (flags & ImGuiSliderFlags_NoSpeedTweaks) ? 1.0f : tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f; + adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor; + v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); + } + adjust_delta *= v_speed; + + // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. + if (axis == ImGuiAxis_Y) + adjust_delta = -adjust_delta; + + // For logarithmic use our range is effectively 0..1 so scale the delta into that range + if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0 + adjust_delta /= (float)(v_max - v_min); + + // Clear current value on activation + // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. + const bool is_just_activated = g.ActiveIdIsJustActivated; + const bool is_already_past_limits_and_pushing_outward = is_bounded && !is_wrapped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + if (is_just_activated || is_already_past_limits_and_pushing_outward) + { + g.DragCurrentAccum = 0.0f; + g.DragCurrentAccumDirty = false; + } + else if (adjust_delta != 0.0f) + { + g.DragCurrentAccum += adjust_delta; + g.DragCurrentAccumDirty = true; + } + + if (!g.DragCurrentAccumDirty) + return false; + + TYPE v_cur = *v; + FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; + + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + + // Convert to parametric space, apply delta, convert back + float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float v_new_parametric = v_old_parametric + g.DragCurrentAccum; + v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + v_old_ref_for_accum_remainder = v_old_parametric; + } + else + { + v_cur += (SIGNEDTYPE)g.DragCurrentAccum; + } + + // Round to user desired precision based on format string + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_cur = RoundScalarWithFormatT(format, data_type, v_cur); + + // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. + g.DragCurrentAccumDirty = false; + if (is_logarithmic) + { + // Convert to parametric space, apply delta, convert back + float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); + } + else + { + g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); + } + + // Lose zero sign for float/double + if (v_cur == (TYPE)-0) + v_cur = (TYPE)0; + + if (*v != v_cur && is_bounded) + { + if (is_wrapped) + { + // Wrap values + if (v_cur < v_min) + v_cur += v_max - v_min + (is_floating_point ? 0 : 1); + if (v_cur > v_max) + v_cur -= v_max - v_min + (is_floating_point ? 0 : 1); + } + else + { + // Clamp values + handle overflow/wrap-around for integer types. + if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point)) + v_cur = v_min; + if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point)) + v_cur = v_max; + } + } + + // Apply result + if (*v == v_cur) + return false; + *v = v_cur; + return true; +} + +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + { + // Those are the things we can do easily outside the DragBehaviorT<> template, saves code generation. + if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) + ClearActiveID(); + else if ((g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + ClearActiveID(); + } + if (g.ActiveId != id) + return false; + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) + return false; + + switch (data_type) + { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags); + case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags); + case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags); + case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags); + case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, flags); + case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, flags); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + + const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags); + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); + if (!temp_input_is_active) + { + // Tabbing or Ctrl+Click on Drag turns it into an InputText + const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); + const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id)); + const bool make_active = (clicked || double_clicked || g.NavActivateId == id); + if (make_active && (clicked || double_clicked)) + SetKeyOwner(ImGuiKey_MouseLeft, id); + if (make_active && temp_input_allowed) + if ((clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) + temp_input_is_active = true; + + // (Optional) simple click (without moving) turns Drag into an InputText + if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active) + if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR)) + { + g.NavActivateId = id; + g.NavActivateFlags = ImGuiActivateFlags_PreferInput; + temp_input_is_active = true; + } + + // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert) + if (make_active) + memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size); + + if (make_active && !temp_input_is_active) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + } + } + + if (temp_input_is_active) + { + // Only clamp Ctrl+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) + bool clamp_enabled = false; + if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL)) + { + const int clamp_range_dir = (p_min != NULL && p_max != NULL) ? DataTypeCompare(data_type, p_min, p_max) : 0; // -1 when *p_min < *p_max, == 0 when *p_min == *p_max + if (p_min == NULL || p_max == NULL || clamp_range_dir < 0) + clamp_enabled = true; + else if (clamp_range_dir == 0) + clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true; + } + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavCursor(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); + if (color_marker != 0 && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(frame_bb, GetColorU32(color_marker), style.FrameRounding); + RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); + + // Drag behavior + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags); + if (value_changed) + MarkItemEdited(id); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + return value_changed; +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + if (flags & ImGuiSliderFlags_ColorMarkers) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[i]); + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); + PopID(); + PopItemWidth(); + p_data = (void*)((char*)p_data + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2, CalcItemWidth()); + + float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; + float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + float max_max = (v_min >= v_max) ? FLT_MAX : v_max; + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextEx(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2, CalcItemWidth()); + + int min_min = (v_min >= v_max) ? INT_MIN : v_min; + int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); + bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + int max_max = (v_min >= v_max) ? INT_MAX : v_max; + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); + value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextEx(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +//------------------------------------------------------------------------- +// - ScaleRatioFromValueT<> [Internal] +// - ScaleValueFromRatioT<> [Internal] +// - SliderBehaviorT<>() [Internal] +// - SliderBehavior() [Internal] +// - SliderScalar() +// - SliderScalarN() +// - SliderFloat() +// - SliderFloat2() +// - SliderFloat3() +// - SliderFloat4() +// - SliderAngle() +// - SliderInt() +// - SliderInt2() +// - SliderInt3() +// - SliderInt4() +// - VSliderScalar() +// - VSliderFloat() +// - VSliderInt() +//------------------------------------------------------------------------- + +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) +template +float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) +{ + if (v_min == v_max) + return 0.0f; + IM_UNUSED(data_type); + + const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); + if (is_logarithmic) + { + bool flipped = v_max < v_min; + + if (flipped) // Handle the case where the range is backwards + ImSwap(v_min, v_max); + + // Fudge min/max to avoid getting close to log(0) + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float result; + if (v_clamped <= v_min_fudged) + result = 0.0f; // Workaround for values that are in-range but below our fudge + else if (v_clamped >= v_max_fudged) + result = 1.0f; // Workaround for values that are in-range but above our fudge + else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions + { + float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (v == 0.0f) + result = zero_point_center; // Special case for exactly zero + else if (v < 0.0f) + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L; + else + result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R)); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); + else + result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged)); + + return flipped ? (1.0f - result) : result; + } + else + { + // Linear slider + return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min)); + } +} + +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT) +template +TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) +{ + // We special-case the extents because otherwise our logarithmic fudging can lead to "mathematically correct" + // but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value. Also generally simpler. + if (t <= 0.0f || v_min == v_max) + return v_min; + if (t >= 1.0f) + return v_max; + + TYPE result = (TYPE)0; + if (is_logarithmic) + { + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + const bool flipped = v_max < v_min; // Check if range is "backwards" + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R) + result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (t_with_flip < zero_point_center) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L)))); + else + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); + else + result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); + } + else + { + // Linear slider + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + if (is_floating_point) + { + result = ImLerp(v_min, v_max, t); + } + else if (t < 1.0) + { + // - For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + // - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. + FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t; + result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5))); + } + } + + return result; +} + +// FIXME: Try to move more of the code into shared SliderBehavior() +template +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + const float v_range_f = (float)(v_min < v_max ? v_max - v_min : v_min - v_max); // We don't need high precision for what we do with it. + + // Calculate bounds + const float grab_padding = 2.0f; // FIXME: Should be part of style. + const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; + float grab_sz = style.GrabMinSize; + if (!is_floating_point && v_range_f >= 0.0f) // v_range_f < 0 may happen on integer overflows + grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit + grab_sz = ImMin(grab_sz, slider_sz); + const float slider_usable_sz = slider_sz - grab_sz; + const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; + + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); + } + + // Process interacting with the slider + bool value_changed = false; + if (g.ActiveId == id) + { + bool set_new_value = false; + float clicked_t = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (!g.IO.MouseDown[0]) + { + ClearActiveID(); + } + else + { + const float mouse_abs_pos = g.IO.MousePos[axis]; + if (g.ActiveIdIsJustActivated) + { + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if (axis == ImGuiAxis_Y) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + const bool clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5f - 1.0f) && (mouse_abs_pos <= grab_pos + grab_sz * 0.5f + 1.0f); // No harm being extra generous here. + g.SliderGrabClickOffset = (clicked_around_grab && is_floating_point) ? mouse_abs_pos - grab_pos : 0.0f; + } + if (slider_usable_sz > 0.0f) + clicked_t = ImSaturate((mouse_abs_pos - g.SliderGrabClickOffset - slider_usable_pos_min) / slider_usable_sz); + if (axis == ImGuiAxis_Y) + clicked_t = 1.0f - clicked_t; + set_new_value = true; + } + } + else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) + { + if (g.ActiveIdIsJustActivated) + { + g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation + g.SliderCurrentAccumDirty = false; + } + + float input_delta = (axis == ImGuiAxis_X) ? GetNavTweakPressedAmount(axis) : -GetNavTweakPressedAmount(axis); + if (input_delta != 0.0f) + { + const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow); + const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast); + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0; + if (decimal_precision > 0) + { + input_delta /= 100.0f; // Keyboard/Gamepad tweak speeds in % of slider bounds + if (tweak_slow) + input_delta /= 10.0f; + } + else + { + if ((v_range_f >= -100.0f && v_range_f <= 100.0f && v_range_f != 0.0f) || tweak_slow) + input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Keyboard/Gamepad tweak speeds in integer steps + else + input_delta /= 100.0f; + } + if (tweak_fast) + input_delta *= 10.0f; + + g.SliderCurrentAccum += input_delta; + g.SliderCurrentAccumDirty = true; + } + + float delta = g.SliderCurrentAccum; + if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + { + ClearActiveID(); + } + else if (g.SliderCurrentAccumDirty) + { + clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits + { + set_new_value = false; + g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate + } + else + { + set_new_value = true; + float old_clicked_t = clicked_t; + clicked_t = ImSaturate(clicked_t + delta); + + // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + if (delta > 0) + g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); + else + g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta); + } + + g.SliderCurrentAccumDirty = false; + } + } + + if (set_new_value) + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) + set_new_value = false; + + if (set_new_value) + { + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + // Round to user desired precision based on format string + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + + // Apply result + if (*v != v_new) + { + *v = v_new; + value_changed = true; + } + } + } + + if (slider_sz < 1.0f) + { + *out_grab_bb = ImRect(bb.Min, bb.Min); + } + else + { + // Output grab position so it can be displayed by the caller + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if (axis == ImGuiAxis_Y) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + if (axis == ImGuiAxis_X) + *out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding); + else + *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f); + } + + return value_changed; +} + +// For 32-bit and larger types, slider bounds are limited to half the natural type range. +// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + IM_ASSERT((flags & ImGuiSliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX() + + switch (data_type) + { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: + IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_U32: + IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_S64: + IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_U64: + IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_Float: + IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_Double: + IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + + const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags); + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); + if (!temp_input_is_active) + { + // Tabbing or Ctrl+Click on Slider turns it into an input box + const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); + const bool make_active = (clicked || g.NavActivateId == id); + if (make_active && clicked) + SetKeyOwner(ImGuiKey_MouseLeft, id); + if (make_active && temp_input_allowed) + if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) + temp_input_is_active = true; + + // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert) + if (make_active) + memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size); + + if (make_active && !temp_input_is_active) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + } + } + + if (temp_input_is_active) + { + // Only clamp Ctrl+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) + const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavCursor(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); + if (color_marker != 0 && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(frame_bb, GetColorU32(color_marker), style.FrameRounding); + RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + if (grab_bb.Max.x > grab_bb.Min.x) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + if (flags & ImGuiSliderFlags_ColorMarkers) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[i]); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); + PopID(); + PopItemWidth(); + v = (void*)((char*)v + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) +{ + if (format == NULL) + format = "%.0f deg"; + float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags); + if (value_changed) + *v_rad = v_deg * (2 * IM_PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); +} + +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(frame_bb, id)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + + const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags); + const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); + if (clicked || g.NavActivateId == id) + { + if (clicked) + SetKeyOwner(ImGuiKey_MouseLeft, id); + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavCursor(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + if (grab_bb.Max.y > grab_bb.Min.y) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + // For the vertical slider we allow centered text to overlap the frame padding + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +//------------------------------------------------------------------------- +// - ImParseFormatFindStart() [Internal] +// - ImParseFormatFindEnd() [Internal] +// - ImParseFormatTrimDecorations() [Internal] +// - ImParseFormatSanitizeForPrinting() [Internal] +// - ImParseFormatSanitizeForScanning() [Internal] +// - ImParseFormatPrecision() [Internal] +// - TempInputTextScalar() [Internal] +// - InputScalar() +// - InputScalarN() +// - InputFloat() +// - InputFloat2() +// - InputFloat3() +// - InputFloat4() +// - InputInt() +// - InputInt2() +// - InputInt3() +// - InputInt4() +// - InputDouble() +//------------------------------------------------------------------------- + +// We don't use strchr() because our strings are usually very short and often start with '%' +const char* ImParseFormatFindStart(const char* fmt) +{ + while (char c = fmt[0]) + { + if (c == '%' && fmt[1] != '%') + return fmt; + else if (c == '%') + fmt++; + fmt++; + } + return fmt; +} + +const char* ImParseFormatFindEnd(const char* fmt) +{ + // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. + if (fmt[0] != '%') + return fmt; + const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A')); + const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a')); + for (char c; (c = *fmt) != 0; fmt++) + { + if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0) + return fmt + 1; + if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0) + return fmt + 1; + } + return fmt; +} + +// Extract the format out of a format string with leading or trailing decorations +// fmt = "blah blah" -> return "" +// fmt = "%.3f" -> return fmt +// fmt = "hello %.3f" -> return fmt + 6 +// fmt = "%.3f hello" -> return buf written with "%.3f" +const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size) +{ + const char* fmt_start = ImParseFormatFindStart(fmt); + if (fmt_start[0] != '%') + return ""; + const char* fmt_end = ImParseFormatFindEnd(fmt_start); + if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data. + return fmt_start; + ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size)); + return buf; +} + +// Sanitize format +// - Zero terminate so extra characters after format (e.g. "%f123") don't confuse atof/atoi +// - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi. +void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size) +{ + const char* fmt_end = ImParseFormatFindEnd(fmt_in); + IM_UNUSED(fmt_out_size); + IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you! + while (fmt_in < fmt_end) + { + char c = *fmt_in++; + if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. + *(fmt_out++) = c; + } + *fmt_out = 0; // Zero-terminate +} + +// - For scanning we need to remove all width and precision fields and flags "%+3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d" +const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size) +{ + const char* fmt_end = ImParseFormatFindEnd(fmt_in); + const char* fmt_out_begin = fmt_out; + IM_UNUSED(fmt_out_size); + IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you! + bool has_type = false; + while (fmt_in < fmt_end) + { + char c = *fmt_in++; + if (!has_type && ((c >= '0' && c <= '9') || c == '.' || c == '+' || c == '#')) + continue; + has_type |= ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); // Stop skipping digits + if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. + *(fmt_out++) = c; + } + *fmt_out = 0; // Zero-terminate + return fmt_out_begin; +} + +template +static const char* ImAtoi(const char* src, TYPE* output) +{ + int negative = 0; + if (*src == '-') { negative = 1; src++; } + if (*src == '+') { src++; } + TYPE v = 0; + while (*src >= '0' && *src <= '9') + v = (v * 10) + (*src++ - '0'); + *output = negative ? -v : v; + return src; +} + +// Parse display precision back from the display format string +// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. +int ImParseFormatPrecision(const char* fmt, int default_precision) +{ + fmt = ImParseFormatFindStart(fmt); + if (fmt[0] != '%') + return default_precision; + fmt++; + while (*fmt >= '0' && *fmt <= '9') + fmt++; + int precision = INT_MAX; + if (*fmt == '.') + { + fmt = ImAtoi(fmt + 1, &precision); + if (precision < 0 || precision > 99) + precision = default_precision; + } + if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation + precision = -1; + if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX) + precision = -1; + return (precision == INT_MAX) ? default_precision : precision; +} + +// Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) +// FIXME: Facilitate using this in variety of other situations. +// FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but +// the expected relationship between TempInputXXX functions and LastItemData is a little fishy. +bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags) +{ + // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. + // We clear ActiveID on the first frame to allow the InputText() taking it back. + ImGuiContext& g = *GImGui; + const bool init = (g.TempInputId != id); + if (init) + ClearActiveID(); + + g.CurrentWindow->DC.CursorPos = bb.Min; + g.LastItemData.ItemFlags |= ImGuiItemFlags_AllowDuplicateId; + bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem); + if (init) + { + // First frame we started displaying the InputText widget, we expect it to take the active id. + IM_ASSERT(g.ActiveId == id); + g.TempInputId = g.ActiveId; + } + return value_changed; +} + +// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set! +// This is intended: this way we allow Ctrl+Click manual input to set a value out of bounds, for maximum flexibility. +// However this may not be ideal for all uses, as some user code may break on out of bound values. +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) +{ + // FIXME: May need to clarify display behavior if format doesn't contain %. + // "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405 + ImGuiContext& g = *GImGui; + const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); + char fmt_buf[32]; + char data_buf[32]; + format = ImParseFormatTrimDecorations(format, fmt_buf, IM_COUNTOF(fmt_buf)); + if (format[0] == 0) + format = type_info->PrintFmt; + DataTypeFormatString(data_buf, IM_COUNTOF(data_buf), data_type, p_data, format); + ImStrTrimBlanks(data_buf); + + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint; + g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData. + bool value_changed = false; + if (TempInputText(bb, id, label, data_buf, IM_COUNTOF(data_buf), flags)) + { + // Backup old value + size_t data_type_size = type_info->Size; + ImGuiDataTypeStorage data_backup; + memcpy(&data_backup, p_data, data_type_size); + + // Apply new value (or operations) then clamp + DataTypeApplyFromText(data_buf, data_type, p_data, format, NULL); + if (p_clamp_min || p_clamp_max) + { + if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0) + ImSwap(p_clamp_min, p_clamp_max); + DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); + } + + // Only mark as edited if new value is different + g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited; + value_changed = memcmp(&data_backup, p_data, data_type_size) != 0; + if (value_changed) + MarkItemEdited(id); + } + return value_changed; +} + +void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data) +{ + ImGuiContext& g = *GImGui; + g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasRefVal; + memcpy(&g.NextItemData.RefVal, p_data, DataTypeGetInfo(data_type)->Size); +} + +// Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional. +// Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + IM_ASSERT((flags & ImGuiInputTextFlags_EnterReturnsTrue) == 0); // Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()! + + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + + void* p_data_default = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue; + + char buf[64]; + if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0) + buf[0] = 0; + else + DataTypeFormatString(buf, IM_COUNTOF(buf), data_type, p_data, format); + + // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited. + // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. + g.NextItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; + flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint; + + bool value_changed = false; + if (p_step == NULL) + { + if (InputText(label, buf, IM_COUNTOF(buf), flags)) + value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL); + } + else + { + const float button_size = GetFrameHeight(); + + BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() + PushID(label); + SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); + if (InputText("", buf, IM_COUNTOF(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL); + IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable); + + // Step buttons + const ImVec2 backup_frame_padding = style.FramePadding; + style.FramePadding.x = style.FramePadding.y; + if (flags & ImGuiInputTextFlags_ReadOnly) + BeginDisabled(); + PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", ImVec2(button_size, button_size))) + { + DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", ImVec2(button_size, button_size))) + { + DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step); + value_changed = true; + } + PopItemFlag(); + if (flags & ImGuiInputTextFlags_ReadOnly) + EndDisabled(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + style.FramePadding = backup_frame_padding; + + PopID(); + EndGroup(); + } + + g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited; + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags); + PopID(); + PopItemWidth(); + p_data = (void*)((char*)p_data + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0.0f, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) +{ + return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags); +} + +bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags); +} + +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags); +} + +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags); +} + +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags); +} + +bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) +{ + return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint +//------------------------------------------------------------------------- +// - imstb_textedit.h include +// - InputText() +// - InputTextWithHint() +// - InputTextMultiline() +// - InputTextEx() [Internal] +// - DebugNodeInputTextState() [Internal] +//------------------------------------------------------------------------- + +namespace ImStb +{ +#include "imstb_textedit.h" +} + +// If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint. + return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); +} + +static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) +{ + ImGuiContext& g = *ctx; + ImGuiInputTextState* obj = &g.InputTextState; + IM_ASSERT(text_end_display >= text_begin && text_end_display <= text_end); + return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj->WrapWidth, text_begin, text_end_display, text_end, out_remaining, out_offset, flags); +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +// With our UTF-8 use of stb_textedit: +// - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine. +// - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW). +// - ...but we don't use that feature. +namespace ImStb +{ +static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; } +static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx >= 0 && idx <= obj->TextLen); return obj->TextSrc[idx]; } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; } +static char STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) +{ + const char* text = obj->TextSrc; + const char* text_remaining = NULL; + const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepBlanks); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (text + line_start_idx)); +} + +#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL +#define IMSTB_TEXTEDIT_GETPREVCHARINDEX IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL + +static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx) +{ + if (idx >= obj->TextLen) + return obj->TextLen + 1; + unsigned int c; + return idx + ImTextCharFromUtf8(&c, obj->TextSrc + idx, obj->TextSrc + obj->TextLen); +} + +static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx) +{ + if (idx <= 0) + return -1; + const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, obj->TextSrc + idx); + return (int)(p - obj->TextSrc); +} + +static bool ImCharIsSeparatorW(unsigned int c) +{ + static const unsigned int separator_list[] = + { + ',', 0x3001, '.', 0x3002, ';', 0xFF1B, '(', 0xFF08, ')', 0xFF09, '{', 0xFF5B, '}', 0xFF5D, + '[', 0x300C, ']', 0x300D, '|', 0xFF5C, '!', 0xFF01, '\\', 0xFFE5, '/', 0x30FB, 0xFF0F, + '\n', '\r', + }; + for (unsigned int separator : separator_list) + if (c == separator) + return true; + return false; +} + +static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) +{ + // When ImGuiInputTextFlags_Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators. + if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0) + return 0; + + const char* curr_p = obj->TextSrc + idx; + const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p); + unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextSrc + obj->TextLen); + unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextSrc + obj->TextLen); + + bool prev_white = ImCharIsBlankW(prev_c); + bool prev_separ = ImCharIsSeparatorW(prev_c); + bool curr_white = ImCharIsBlankW(curr_c); + bool curr_separ = ImCharIsSeparatorW(curr_c); + return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ); +} +static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx) +{ + if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0) + return 0; + + const char* curr_p = obj->TextSrc + idx; + const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p); + unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextSrc + obj->TextLen); + unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextSrc + obj->TextLen); + + bool prev_white = ImCharIsBlankW(prev_c); + bool prev_separ = ImCharIsSeparatorW(prev_c); + bool curr_white = ImCharIsBlankW(curr_c); + bool curr_separ = ImCharIsSeparatorW(curr_c); + return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ); +} +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx) +{ + idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx); + while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) + idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx); + return idx < 0 ? 0 : idx; +} +static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx) +{ + int len = obj->TextLen; + idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx); + while (idx < len && !is_word_boundary_from_left(obj, idx)) + idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx); + return idx > len ? len : idx; +} +static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx) +{ + idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx); + int len = obj->TextLen; + while (idx < len && !is_word_boundary_from_right(obj, idx)) + idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx); + return idx > len ? len : idx; +} +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx) { ImGuiContext& g = *obj->Ctx; if (g.IO.ConfigMacOSXBehaviors) return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx); else return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx); } +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + +// Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping. +static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor) +{ + if (state->single_line) + return 0; + + if (obj->WrapWidth > 0.0f) + { + ImGuiContext& g = *obj->Ctx; + const char* p_cursor = obj->TextSrc + cursor; + const char* p_bol = ImStrbol(p_cursor, obj->TextSrc); + const char* p = p_bol; + const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough + while (p >= p_bol) + { + const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); + if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below) + return (int)(p_bol - obj->TextSrc); + if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) + return (int)(p_bol - obj->TextSrc); + if (p_eol >= p_cursor) + return (int)(p - obj->TextSrc); + p = (*p_eol == '\n') ? p_eol + 1 : p_eol; + } + } + + // Regular handler, same as stb_textedit_move_line_start() + while (cursor > 0) + { + int prev_cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, cursor); + if (STB_TEXTEDIT_GETCHAR(obj, prev_cursor) == STB_TEXTEDIT_NEWLINE) + break; + cursor = prev_cursor; + } + return cursor; +} + +static int STB_TEXTEDIT_MOVELINEEND_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor) +{ + int n = STB_TEXTEDIT_STRINGLEN(obj); + if (state->single_line) + return n; + + if (obj->WrapWidth > 0.0f) + { + ImGuiContext& g = *obj->Ctx; + const char* p_cursor = obj->TextSrc + cursor; + const char* p = ImStrbol(p_cursor, obj->TextSrc); + const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough + while (p < text_end) + { + const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); + cursor = (int)(p_eol - obj->TextSrc); + if (p_eol == p_cursor && obj->LastMoveDirectionLR != ImGuiDir_Left) // If we are already on a visible end-of-line, switch to regular handle + break; + if (p_eol > p_cursor) + return cursor; + p = (*p_eol == '\n') ? p_eol + 1 : p_eol; + } + } + // Regular handler, same as stb_textedit_move_line_end() + while (cursor < n && STB_TEXTEDIT_GETCHAR(obj, cursor) != STB_TEXTEDIT_NEWLINE) + cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, cursor); + return cursor; +} + +#define STB_TEXTEDIT_MOVELINESTART STB_TEXTEDIT_MOVELINESTART_IMPL +#define STB_TEXTEDIT_MOVELINEEND STB_TEXTEDIT_MOVELINEEND_IMPL + +static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n) +{ + // Offset remaining text (+ copy zero terminator) + IM_ASSERT(obj->TextSrc == obj->TextA.Data); + char* dst = obj->TextA.Data + pos; + char* src = obj->TextA.Data + pos + n; + memmove(dst, src, obj->TextLen - n - pos + 1); + obj->Edited = true; + obj->TextLen -= n; +} + +static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len) +{ + const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0; + const int text_len = obj->TextLen; + IM_ASSERT(pos <= text_len); + + // We support partial insertion (with a mod in stb_textedit.h) + const int avail = obj->BufCapacity - 1 - obj->TextLen; + if (!is_resizable && new_text_len > avail) + new_text_len = (int)(ImTextFindValidUtf8CodepointEnd(new_text, new_text + new_text_len, new_text + avail) - new_text); // Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. + if (new_text_len == 0) + return 0; + + // Grow internal buffer if needed + IM_ASSERT(obj->TextSrc == obj->TextA.Data); + if (text_len + new_text_len + 1 > obj->TextA.Size && is_resizable) + { + obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1); + obj->TextSrc = obj->TextA.Data; + } + + char* text = obj->TextA.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos)); + memcpy(text + pos, new_text, (size_t)new_text_len); + + obj->Edited = true; + obj->TextLen += new_text_len; + obj->TextA[obj->TextLen] = '\0'; + + return new_text_len; +} + +// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) +#define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left +#define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right +#define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up +#define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down +#define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line +#define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line +#define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text +#define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text +#define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor +#define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor +#define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo +#define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo +#define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word +#define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page +#define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page +#define STB_TEXTEDIT_K_SHIFT 0x400000 + +#define IMSTB_TEXTEDIT_IMPLEMENTATION +#define IMSTB_TEXTEDIT_memmove memmove +#include "imstb_textedit.h" + +// stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling +// the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) +static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) +{ + stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len); + ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen); + state->cursor = state->select_start = state->select_end = 0; + if (text_len <= 0) + return; + int text_len_inserted = ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len); + if (text_len_inserted > 0) + { + state->cursor = state->select_start = state->select_end = text_len; + state->has_preferred_x = 0; + return; + } + IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace() +} + +} // namespace ImStb + +// We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators. +ImGuiInputTextState::ImGuiInputTextState() +{ + memset(this, 0, sizeof(*this)); + Stb = IM_NEW(ImStbTexteditState); + memset(Stb, 0, sizeof(*Stb)); +} + +ImGuiInputTextState::~ImGuiInputTextState() +{ + IM_DELETE(Stb); +} + +void ImGuiInputTextState::OnKeyPressed(int key) +{ + stb_textedit_key(this, Stb, key); + CursorFollow = true; + CursorAnimReset(); + const int key_u = (key & ~STB_TEXTEDIT_K_SHIFT); + if (key_u == STB_TEXTEDIT_K_LEFT || key_u == STB_TEXTEDIT_K_LINESTART || key_u == STB_TEXTEDIT_K_TEXTSTART || key_u == STB_TEXTEDIT_K_BACKSPACE || key_u == STB_TEXTEDIT_K_WORDLEFT) + LastMoveDirectionLR = ImGuiDir_Left; + else if (key_u == STB_TEXTEDIT_K_RIGHT || key_u == STB_TEXTEDIT_K_LINEEND || key_u == STB_TEXTEDIT_K_TEXTEND || key_u == STB_TEXTEDIT_K_DELETE || key_u == STB_TEXTEDIT_K_WORDRIGHT) + LastMoveDirectionLR = ImGuiDir_Right; +} + +void ImGuiInputTextState::OnCharPressed(unsigned int c) +{ + // Convert the key to a UTF8 byte sequence. + // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great. + char utf8[5]; + ImTextCharToUtf8(utf8, c); + stb_textedit_text(this, Stb, utf8, (int)ImStrlen(utf8)); + CursorFollow = true; + CursorAnimReset(); +} + +// Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header. +void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking +void ImGuiInputTextState::CursorClamp() { Stb->cursor = ImMin(Stb->cursor, TextLen); Stb->select_start = ImMin(Stb->select_start, TextLen); Stb->select_end = ImMin(Stb->select_end, TextLen); } +bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; } +void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; } +int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; } +int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; } +int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; } +void ImGuiInputTextState::SetSelection(int start, int end) { Stb->select_start = start; Stb->cursor = Stb->select_end = end; } +float ImGuiInputTextState::GetPreferredOffsetX() const { return Stb->has_preferred_x ? Stb->preferred_x : -1; } +void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; } +void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } +void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; } +void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { WantReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; } + +ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() +{ + memset(this, 0, sizeof(*this)); +} + +// Public API to manipulate UTF-8 text from within a callback. +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. +// Historically they existed because STB_TEXTEDIT_INSERTCHARS() etc. worked on our ImWchar +// buffer, but nowadays they both work on UTF-8 data. Should aim to merge both. +void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) +{ + IM_ASSERT(pos + bytes_count <= BufTextLen); + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + memmove(dst, src, BufTextLen - bytes_count - pos + 1); + + if (CursorPos >= pos + bytes_count) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; +} + +void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + // Accept null ranges + if (new_text == new_text_end) + return; + + ImGuiContext& g = *Ctx; + ImGuiInputTextState* obj = &g.InputTextState; + IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID); + const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; + const bool is_readonly = (Flags & ImGuiInputTextFlags_ReadOnly) != 0; + int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); + + // We support partial insertion (with a mod in stb_textedit.h) + const int avail = BufSize - 1 - BufTextLen; + if (!is_resizable && new_text_len > avail) + new_text_len = (int)(ImTextFindValidUtf8CodepointEnd(new_text, new_text + new_text_len, new_text + avail) - new_text); // Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. + if (new_text_len == 0) + return; + + // Grow internal buffer if needed + if (new_text_len + BufTextLen + 1 > obj->TextA.Size && is_resizable && !is_readonly) + { + IM_ASSERT(Buf == obj->TextA.Data); + int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; + obj->TextA.resize(new_buf_size + 1); + obj->TextSrc = obj->TextA.Data; + Buf = obj->TextA.Data; + BufSize = obj->BufCapacity = new_buf_size; + } + + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; + + BufDirty = true; + BufTextLen += new_text_len; + if (CursorPos >= pos) + CursorPos += new_text_len; + CursorPos = ImClamp(CursorPos, 0, BufTextLen); + SelectionStart = SelectionEnd = CursorPos; +} + +void ImGui::PushPasswordFont() +{ + ImGuiContext& g = *GImGui; + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); + ImFontGlyph* glyph = g.FontBaked->FindGlyph('*'); + g.InputTextPasswordFontBackupFlags = g.Font->Flags; + backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex; + backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX; + backup->IndexLookup.swap(g.FontBaked->IndexLookup); + backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX); + g.Font->Flags |= ImFontFlags_NoLoadGlyphs; + g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph); + g.FontBaked->FallbackAdvanceX = glyph->AdvanceX; +} + +void ImGui::PopPasswordFont() +{ + ImGuiContext& g = *GImGui; + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + g.Font->Flags = g.InputTextPasswordFontBackupFlags; + g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex; + g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX; + g.FontBaked->IndexLookup.swap(backup->IndexLookup); + g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX); + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); +} + +// Return false to discard a character. +static bool InputTextFilterCharacter(ImGuiContext* ctx, ImGuiInputTextState* state, unsigned int* p_char, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard) +{ + unsigned int c = *p_char; + ImGuiInputTextFlags flags = state->Flags; + + // Filter non-printable (NB: isprint is unreliable! see #2467) + bool apply_named_filters = true; + if (c < 0x20) + { + bool pass = false; + pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code) + if (c == '\n' && input_source_is_clipboard && (flags & ImGuiInputTextFlags_Multiline) == 0) // In single line mode, replace \n with a space + { + c = *p_char = ' '; + pass = true; + } + pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; + pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0; + if (!pass) + return false; + apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted. + } + + if (input_source_is_clipboard == false) + { + // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817) + if (c == 127) + return false; + + // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME) + if (c >= 0xE000 && c <= 0xF8FF) + return false; + } + + // Filter Unicode ranges we are not handling in this build + if (c > IM_UNICODE_CODEPOINT_MAX) + return false; + + // Generic named filters + if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint))) + { + // The libc allows overriding locale, with e.g. 'setlocale(LC_NUMERIC, "de_DE.UTF-8");' which affect the output/input of printf/scanf to use e.g. ',' instead of '.'. + // The standard mandate that programs starts in the "C" locale where the decimal point is '.'. + // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point. + // Change the default decimal_point with: + // ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point; + // Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions. + ImGuiContext& g = *ctx; + const unsigned c_decimal_point = (unsigned int)g.PlatformIO.Platform_LocaleDecimalPoint; + if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint)) + if (c == '.' || c == ',') + c = c_decimal_point; + + // Full-width -> half-width conversion for numeric fields: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block) + // While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may + // scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font. + if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal)) + if (c >= 0xFF01 && c <= 0xFF5E) + c = c - 0xFF01 + 0x21; + + // Allow 0-9 . - + * / + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + return false; + + // Allow 0-9 . - + * / e E + if (flags & ImGuiInputTextFlags_CharsScientific) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) + return false; + + // Allow 0-9 a-F A-F + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + return false; + + // Turn a-z into A-Z + if (flags & ImGuiInputTextFlags_CharsUppercase) + if (c >= 'a' && c <= 'z') + c += (unsigned int)('A' - 'a'); + + if (flags & ImGuiInputTextFlags_CharsNoBlank) + if (ImCharIsBlankW(c)) + return false; + + *p_char = c; + } + + // Custom callback filter + if (flags & ImGuiInputTextFlags_CallbackCharFilter) + { + ImGuiContext& g = *GImGui; + ImGuiInputTextCallbackData callback_data; + callback_data.Ctx = &g; + callback_data.ID = state->ID; + callback_data.Flags = flags; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventChar = (ImWchar)c; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); + callback_data.UserData = user_data; + if (callback(&callback_data) != 0) + return false; + *p_char = callback_data.EventChar; + if (!callback_data.EventChar) + return false; + } + + return true; +} + +// Find the shortest single replacement we can make to get from old_buf to new_buf +// Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately. +// FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly. +static void InputTextReconcileUndoState(ImGuiInputTextState* state, const char* old_buf, int old_length, const char* new_buf, int new_length) +{ + const int shorter_length = ImMin(old_length, new_length); + int first_diff; + for (first_diff = 0; first_diff < shorter_length; first_diff++) + if (old_buf[first_diff] != new_buf[first_diff]) + break; + if (first_diff == old_length && first_diff == new_length) + return; + + int old_last_diff = old_length - 1; + int new_last_diff = new_length - 1; + for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--) + if (old_buf[old_last_diff] != new_buf[new_last_diff]) + break; + + const int insert_len = new_last_diff - first_diff + 1; + const int delete_len = old_last_diff - first_diff + 1; + if (insert_len > 0 || delete_len > 0) + if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len)) + for (int i = 0; i < delete_len; i++) + p[i] = old_buf[first_diff + i]; +} + +// As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables) +// we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714) +// It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick, +// but that more likely be attractive when we do have _NoLiveEdit flag available. +void ImGui::InputTextDeactivateHook(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiInputTextState* state = &g.InputTextState; + if (id == 0 || state->ID != id) + return; + g.InputTextDeactivatedState.ID = state->ID; + if (state->Flags & ImGuiInputTextFlags_ReadOnly) + { + g.InputTextDeactivatedState.TextA.resize(0); // In theory this data won't be used, but clear to be neat. + } + else + { + IM_ASSERT(state->TextA.Data != 0); + IM_ASSERT(state->TextA[state->TextLen] == 0); + g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1); + memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1); + } +} + +static int* ImLowerBound(int* in_begin, int* in_end, int v) +{ + int* in_p = in_begin; + for (size_t count = (size_t)(in_end - in_p); count > 0; ) + { + size_t count2 = count >> 1; + int* mid = in_p + count2; + if (*mid < v) + { + in_p = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return in_p; +} + +// FIXME-WORDWRAP: Bundle some of this into ImGuiTextIndex and/or extract as a different tool? +// 'max_output_buffer_size' happens to be a meaningful optimization to avoid writing the full line_index when not necessarily needed (e.g. very large buffer, scrolled up, inactive) +static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size, const char** out_buf_end) +{ + ImGuiContext& g = *GImGui; + int size = 0; + const char* s; + if (flags & ImGuiInputTextFlags_WordWrap) + { + for (s = buf; s < buf_end; s = (*s == '\n') ? s + 1 : s) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, buf_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + } + } + else if (buf_end != NULL) + { + for (s = buf; s < buf_end; s = s ? s + 1 : buf_end) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + s = (const char*)ImMemchr(s, '\n', buf_end - s); + } + } + else + { + const char* s_eol; + for (s = buf; ; s = s_eol + 1) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + if ((s_eol = strchr(s, '\n')) != NULL) + continue; + s += strlen(s); + break; + } + } + if (out_buf_end != NULL) + *out_buf_end = buf_end = s; + if (size == 0) + { + line_index->Offsets.push_back(0); + size++; + } + if (buf_end > buf && buf_end[-1] == '\n' && size <= max_output_buffer_size) + { + line_index->Offsets.push_back((int)(buf_end - buf)); + size++; + } + return size; +} + +static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextState* state, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, int cursor_n) +{ + const char* cursor_ptr = buf + cursor_n; + int* it_begin = line_index->Offsets.begin(); + int* it_end = line_index->Offsets.end(); + const int* it = ImLowerBound(it_begin, it_end, cursor_n); + if (it > it_begin) + if (it == it_end || *it != cursor_n || (state != NULL && state->WrapWidth > 0.0f && state->LastMoveDirectionLR == ImGuiDir_Right && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0)) + it--; + + const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it); + const char* line_start = line_index->get_line_begin(buf, line_no); + ImVec2 offset; + offset.x = InputTextCalcTextSize(&g, line_start, cursor_ptr, buf_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x; + offset.y = (line_no + 1) * g.FontSize; + return offset; +} + +// Edit a string of text +// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match +// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. +// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. +// - If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! +bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT(buf != NULL && buf_size >= 0); + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming + IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode. + IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode. + + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const bool RENDER_SELECTION_WHEN_INACTIVE = false; + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + + if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar) + BeginGroup(); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line + const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size); + + ImGuiWindow* draw_window = window; + ImVec2 inner_size = frame_size; + ImGuiLastItemData item_data_backup; + if (is_multiline) + { + ImVec2 backup_pos = window->DC.CursorPos; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable)) + { + EndGroup(); + return false; + } + item_data_backup = g.LastItemData; + window->DC.CursorPos = backup_pos; + + // Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. + if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && !(g.NavActivateFlags & ImGuiActivateFlags_FromFocusApi) && (flags & ImGuiInputTextFlags_AllowTabInput)) + g.NavActivateId = 0; + + // Prevent NavActivate reactivating in BeginChild() when we are already active. + const ImGuiID backup_activate_id = g.NavActivateId; + if (g.ActiveId == id) // Prevent reactivation + g.NavActivateId = 0; + + // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug. + PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); + PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); + g.NavActivateId = backup_activate_id; + PopStyleVar(3); + PopStyleColor(); + if (!child_visible) + { + EndChild(); + EndGroup(); + return false; + } + draw_window = g.CurrentWindow; // Child window + draw_window->DC.NavLayersActiveMaskNext |= (1 << draw_window->DC.NavLayerCurrent); // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. + draw_window->DC.CursorPos += style.FramePadding; + inner_size.x -= draw_window->ScrollbarSizes.x; + } + else + { + // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd) + ItemSize(total_bb, style.FramePadding.y); + if (!(flags & ImGuiInputTextFlags_MergedItem)) + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable)) + return false; + } + + // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417) + bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover); + if (hovered) + SetMouseCursor(ImGuiMouseCursor_TextInput); + if (hovered && g.NavHighlightItemUnderNav) + hovered = false; + + // We are only allowed to access the state if we are already the active widget. + ImGuiInputTextState* state = GetInputTextState(id); + + if (g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) + flags |= ImGuiInputTextFlags_ReadOnly; + const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; + const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; + if (is_resizable) + IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! + + // Word-wrapping: enforcing a fixed width not altered by vertical scrollbar makes things easier, notably to track cursor reliably and avoid one-frame glitches. + // Instead of using ImGuiWindowFlags_AlwaysVerticalScrollbar we account for that space if the scrollbar is not visible. + const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0; + float wrap_width = 0.0f; + if (is_wordwrap) + wrap_width = ImMax(1.0f, GetContentRegionAvail().x + (draw_window->ScrollbarY ? 0.0f : -g.Style.ScrollbarSize)); + + const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard))); + + const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y); + const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y); + bool clear_active_id = false; + bool select_all = false; + + float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; + + const bool init_reload_from_user_buf = (state != NULL && state->WantReloadUserBuf); + const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state. + const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav); + const bool init_state = (init_make_active || user_scroll_active); + if (init_reload_from_user_buf) + { + int new_len = (int)ImStrlen(buf); + IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); + state->WantReloadUserBuf = false; + InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len); + state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string. + state->TextLen = new_len; + memcpy(state->TextA.Data, buf, state->TextLen + 1); + state->Stb->select_start = state->ReloadSelectionStart; + state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd; // will be clamped to bounds below + } + else if ((init_state && g.ActiveId != id) || init_changed_specs) + { + // Access state even if we don't own it yet. + state = &g.InputTextState; + state->CursorAnimReset(); + + // Backup state of deactivating item so they'll have a chance to do a write to output buffer on the same frame they report IsItemDeactivatedAfterEdit (#4714) + InputTextDeactivateHook(state->ID); + + // Take a copy of the initial buffer value. + // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode) + const int buf_len = (int)ImStrlen(buf); + IM_ASSERT(((buf_len + 1 <= buf_size) || (buf_len == 0 && buf_size == 0)) && "Is your input buffer properly zero-terminated?"); + state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. + memcpy(state->TextToRevertTo.Data, buf, buf_len + 1); + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate? + bool recycle_state = (state->ID == id && !init_changed_specs); + if (recycle_state && (state->TextLen != buf_len || (state->TextA.Data == NULL || strncmp(state->TextA.Data, buf, buf_len) != 0))) + recycle_state = false; + + // Start edition + state->ID = id; + state->TextLen = buf_len; + if (!is_readonly) + { + state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string. + memcpy(state->TextA.Data, buf, state->TextLen + 1); + } + + // Find initial scroll position for right alignment + state->Scroll = ImVec2(0.0f, 0.0f); + if (flags & ImGuiInputTextFlags_ElideLeft) + state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f); + + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + if (!recycle_state) + stb_textedit_initialize_state(state->Stb, !is_multiline); + + if (!is_multiline) + { + if (flags & ImGuiInputTextFlags_AutoSelectAll) + select_all = true; + if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState))) + select_all = true; + if (user_clicked && io.KeyCtrl) + select_all = true; + } + + if (flags & ImGuiInputTextFlags_AlwaysOverwrite) + state->Stb->insert_mode = 1; // stb field name is indeed incorrect (see #2863) + } + + const bool is_osx = io.ConfigMacOSXBehaviors; + if (g.ActiveId != id && init_make_active) + { + IM_ASSERT(state && state->ID == id); + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + if (input_requested_by_nav) + SetNavCursorVisibleAfterMove(); + } + if (g.ActiveId == id) + { + // Declare some inputs, the other are registered and polled via Shortcut() routing system. + // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts. + const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End }; + for (ImGuiKey key : always_owned_keys) + SetKeyOwner(key, id); + if (user_clicked) + SetKeyOwner(ImGuiKey_MouseLeft, id); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory)) + { + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + SetKeyOwner(ImGuiKey_UpArrow, id); + SetKeyOwner(ImGuiKey_DownArrow, id); + } + if (is_multiline) + { + SetKeyOwner(ImGuiKey_PageUp, id); + SetKeyOwner(ImGuiKey_PageDown, id); + } + // FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu + if (is_osx) + SetKeyOwner(ImGuiMod_Alt, id); + + // Expose scroll in a manner that is agnostic to us using a child window + if (is_multiline && state != NULL) + state->Scroll.y = draw_window->Scroll.y; + + // Read-only mode always ever read from source buffer. Refresh TextLen when active. + if (is_readonly && state != NULL) + state->TextLen = (int)ImStrlen(buf); + if (state != NULL) + state->CursorClamp(); + //if (is_readonly && state != NULL) + // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation. + } + if (state != NULL) + state->TextSrc = is_readonly ? buf : state->TextA.Data; + + // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function) + if (g.ActiveId == id && state == NULL) + ClearActiveID(); + + // Release focus when we click outside + if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 + clear_active_id = true; + + // Lock the decision of whether we are going to take the path displaying the cursor or selection + bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); + bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + bool value_changed = false; + bool validated = false; + + // Select the buffer to render. + const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state; + bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); + + // Password pushes a temporary font with only a fallback glyph + if (is_password && !is_displaying_hint) + PushPasswordFont(); + + // Word-wrapping: attempt to keep cursor in view while resizing frame/parent + // FIXME-WORDWRAP: It would be better to preserve same relative offset. + if (is_wordwrap && state != NULL && state->ID == id && state->WrapWidth != wrap_width) + { + state->CursorCenterY = true; + state->WrapWidth = wrap_width; + render_cursor = true; + } + + // Process mouse inputs and character inputs + if (g.ActiveId == id) + { + IM_ASSERT(state != NULL); + state->Edited = false; + state->BufCapacity = buf_size; + state->Flags = flags; + state->WrapWidth = wrap_width; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + + // Edit in progress + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->Scroll.x; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f)); + + if (select_all) + { + state->SelectAll(); + state->SelectedAllMouseLock = true; + } + else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift) + { + stb_textedit_click(state, state->Stb, mouse_x, mouse_y); + const int multiclick_count = (io.MouseClickedCount[0] - 2); + if ((multiclick_count % 2) == 0) + { + // Double-click: Select word + // We always use the "Mac" word advance for double-click select vs Ctrl+Right which use the platform dependent variant: + // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS) + const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n'; + if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + if (!STB_TEXT_HAS_SELECTION(state->Stb)) + ImStb::stb_textedit_prep_selection_at_cursor(state->Stb); + state->Stb->cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb->cursor); + state->Stb->select_end = state->Stb->cursor; + ImStb::stb_textedit_clamp(state, state->Stb); + } + else + { + // Triple-click: Select line + const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n'; + state->WrapWidth = 0.0f; // Temporarily disable wrapping so we use real line start. + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART); + state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT); + state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT); + state->WrapWidth = wrap_width; + if (!is_eol && is_multiline) + { + ImSwap(state->Stb->select_start, state->Stb->select_end); + state->Stb->cursor = state->Stb->select_end; + } + state->CursorFollow = false; + } + state->CursorAnimReset(); + } + else if (io.MouseClicked[0] && !state->SelectedAllMouseLock) + { + if (hovered) + { + if (io.KeyShift) + stb_textedit_drag(state, state->Stb, mouse_x, mouse_y); + else + stb_textedit_click(state, state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); + } + } + else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + stb_textedit_drag(state, state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); + state->CursorFollow = true; + } + if (state->SelectedAllMouseLock && !io.MouseDown[0]) + state->SelectedAllMouseLock = false; + + // We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) + // (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) + if ((flags & ImGuiInputTextFlags_AllowTabInput) && !is_readonly) + { + if (Shortcut(ImGuiKey_Tab, ImGuiInputFlags_Repeat, id)) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) + state->OnCharPressed(c); + } + // FIXME: Implement Shift+Tab + /* + if (Shortcut(ImGuiKey_Tab | ImGuiMod_Shift, ImGuiInputFlags_Repeat, id)) + { + } + */ + } + + // Process regular text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. + const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeyCtrl); + if (io.InputQueueCharacters.Size > 0) + { + if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav) + for (int n = 0; n < io.InputQueueCharacters.Size; n++) + { + // Insert character if they pass filtering + unsigned int c = (unsigned int)io.InputQueueCharacters[n]; + if (c == '\t') // Skip Tab, see above. + continue; + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) + state->OnCharPressed(c); + } + + // Consume characters + io.InputQueueCharacters.resize(0); + } + } + + // Process other shortcuts/key-presses + bool revert_edit = false; + if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) + { + IM_ASSERT(state != NULL); + + const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1); + state->Stb->row_count_per_page = row_count_per_page; + + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = is_osx && io.KeyCtrl && !io.KeySuper && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + + // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use Ctrl+A and Ctrl+B: former would be handled by InputText) + // Otherwise we could simply assume that we own the keys as we are active. + const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat; + const bool is_cut = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_X, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Delete, f_repeat, id)) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); + const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection()); + const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly; + const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable; + const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable; + const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id); + + // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful. + const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const bool is_enter = Shortcut(ImGuiKey_Enter, f_repeat, id) || Shortcut(ImGuiKey_KeypadEnter, f_repeat, id); + const bool is_ctrl_enter = Shortcut(ImGuiMod_Ctrl | ImGuiKey_Enter, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_KeypadEnter, f_repeat, id); + const bool is_gamepad_validate = nav_gamepad_active && (IsKeyPressed(ImGuiKey_NavGamepadActivate, false) || IsKeyPressed(ImGuiKey_NavGamepadInput, false)); + const bool is_cancel = Shortcut(ImGuiKey_Escape, f_repeat, id) || (nav_gamepad_active && Shortcut(ImGuiKey_NavGamepadCancel, f_repeat, id)); + + // FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of. + // FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line. + if (IsKeyPressed(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressed(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressed(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressed(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; } + else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; } + else if (IsKeyPressed(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressed(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut) + { + if (!state->HasSelection()) + { + // OSX doesn't seem to have Super+Delete to delete until end-of-line, so we don't emulate that (as opposed to Super+Backspace) + if (is_wordmove_key_down) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } + state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); + } + else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly) + { + if (!state->HasSelection()) + { + if (is_wordmove_key_down) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT); + else if (is_osx && io.KeyCtrl && !io.KeyAlt && !io.KeySuper) + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT); + } + state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (is_enter || is_ctrl_enter || is_gamepad_validate) + { + // Determine if we turn Enter into a \n character + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != is_ctrl_enter)) + { + validated = true; + if (io.ConfigInputTextEnterKeepActive && !is_multiline) + state->SelectAll(); // No need to scroll + else + clear_active_id = true; + } + else if (!is_readonly) + { + // Insert new line + unsigned int c = '\n'; + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) + state->OnCharPressed(c); + } + } + else if (is_cancel) + { + if (flags & ImGuiInputTextFlags_EscapeClearsAll) + { + if (state->TextA.Data[0] != 0) + { + revert_edit = true; + } + else + { + render_cursor = render_selection = false; + clear_active_id = true; + } + } + else + { + clear_active_id = revert_edit = true; + render_cursor = render_selection = false; + } + } + else if (is_undo || is_redo) + { + state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); + state->ClearSelection(); + } + else if (is_select_all) + { + state->SelectAll(); + state->CursorFollow = true; + } + else if (is_cut || is_copy) + { + // Cut, Copy + if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) + { + // SetClipboardText() only takes null terminated strings + state->TextSrc may point to read-only user buffer, so we need to make a copy. + const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0; + const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen; + g.TempBuffer.reserve(ie - ib + 1); + memcpy(g.TempBuffer.Data, state->TextSrc + ib, ie - ib); + g.TempBuffer.Data[ie - ib] = 0; + SetClipboardText(g.TempBuffer.Data); + } + if (is_cut) + { + if (!state->HasSelection()) + state->SelectAll(); + state->CursorFollow = true; + stb_textedit_cut(state, state->Stb); + } + } + else if (is_paste) + { + if (const char* clipboard = GetClipboardText()) + { + // Filter pasted buffer + const int clipboard_len = (int)ImStrlen(clipboard); + const char* clipboard_end = clipboard + clipboard_len; + ImVector clipboard_filtered; + clipboard_filtered.reserve(clipboard_len + 1); + for (const char* s = clipboard; *s != 0; ) + { + unsigned int c; + int in_len = ImTextCharFromUtf8(&c, s, clipboard_end); + s += in_len; + if (!InputTextFilterCharacter(&g, state, &c, callback, callback_user_data, true)) + continue; + char c_utf8[5]; + ImTextCharToUtf8(c_utf8, c); + int out_len = (int)ImStrlen(c_utf8); + clipboard_filtered.resize(clipboard_filtered.Size + out_len); + memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len); + } + if (clipboard_filtered.Size > 0) // If everything was filtered, ignore the pasting operation + { + clipboard_filtered.push_back(0); + stb_textedit_paste(state, state->Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1); + state->CursorFollow = true; + } + } + } + + // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. + render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + } + + // Process callbacks and apply result back to user's buffer. + const char* apply_new_text = NULL; + int apply_new_text_length = 0; + if (g.ActiveId == id) + { + IM_ASSERT(state != NULL); + if (revert_edit && !is_readonly) + { + if (flags & ImGuiInputTextFlags_EscapeClearsAll) + { + // Clear input + IM_ASSERT(state->TextA.Data[0] != 0); + apply_new_text = ""; + apply_new_text_length = 0; + value_changed = true; + char empty_string = 0; + stb_textedit_replace(state, state->Stb, &empty_string, 0); + } + else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0) + { + apply_new_text = state->TextToRevertTo.Data; + apply_new_text_length = state->TextToRevertTo.Size - 1; + + // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. + // Push records into the undo stack so we can Ctrl+Z the revert operation itself + value_changed = true; + stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1); + } + } + + // FIXME-OPT: We always reapply the live buffer back to the input buffer before clearing ActiveId, + // even though strictly speaking it wasn't modified on this frame. Should mark dirty state from the stb_textedit callbacks. + // If we do that, need to ensure that as special case, 'validated == true' also writes back. + // This also allows the user to use InputText() without maintaining any user-side storage. + // (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object + // unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize). + const bool apply_edit_back_to_user_buffer = true;// !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); + if (apply_edit_back_to_user_buffer) + { + // Apply current edited text immediately. + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiInputTextFlags event_flag = 0; + ImGuiKey event_key = ImGuiKey_None; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && Shortcut(ImGuiKey_Tab, 0, id)) + { + event_flag = ImGuiInputTextFlags_CallbackCompletion; + event_key = ImGuiKey_Tab; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_UpArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_DownArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited) + { + event_flag = ImGuiInputTextFlags_CallbackEdit; + } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + { + event_flag = ImGuiInputTextFlags_CallbackAlways; + } + + if (event_flag) + { + ImGuiInputTextCallbackData callback_data; + callback_data.Ctx = &g; + callback_data.ID = id; + callback_data.Flags = flags; + callback_data.EventFlag = event_flag; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); + callback_data.UserData = callback_user_data; + + // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 + char* callback_buf = is_readonly ? buf : state->TextA.Data; + IM_ASSERT(callback_buf == state->TextSrc); + state->CallbackTextBackup.resize(state->TextLen + 1); + memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1); + + callback_data.EventKey = event_key; + callback_data.Buf = callback_buf; + callback_data.BufTextLen = state->TextLen; + callback_data.BufSize = state->BufCapacity; + callback_data.BufDirty = false; + callback_data.CursorPos = state->Stb->cursor; + callback_data.SelectionStart = state->Stb->select_start; + callback_data.SelectionEnd = state->Stb->select_end; + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback + IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == state->BufCapacity); + IM_ASSERT(callback_data.Flags == flags); + if (callback_data.BufDirty || callback_data.CursorPos != state->Stb->cursor) + state->CursorFollow = true; + state->Stb->cursor = ImClamp(callback_data.CursorPos, 0, callback_data.BufTextLen); + state->Stb->select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen); + state->Stb->select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen); + if (callback_data.BufDirty) + { + // Callback may update buffer and thus set buf_dirty even in read-only mode. + IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen); + state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + state->CursorAnimReset(); + } + } + } + + // Will copy result string if modified + if (!is_readonly && strcmp(state->TextSrc, buf) != 0) + { + apply_new_text = state->TextSrc; + apply_new_text_length = state->TextLen; + value_changed = true; + } + } + } + + // Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details) + if (g.InputTextDeactivatedState.ID == id) + { + if (g.ActiveId != id && IsItemDeactivatedAfterEdit() && !is_readonly && strcmp(g.InputTextDeactivatedState.TextA.Data, buf) != 0) + { + apply_new_text = g.InputTextDeactivatedState.TextA.Data; + apply_new_text_length = g.InputTextDeactivatedState.TextA.Size - 1; + value_changed = true; + //IMGUI_DEBUG_LOG("InputText(): apply Deactivated data for 0x%08X: \"%.*s\".\n", id, apply_new_text_length, apply_new_text); + } + g.InputTextDeactivatedState.ID = 0; + } + + // Copy result to user buffer. This can currently only happen when (g.ActiveId == id) + if (apply_new_text != NULL) + { + //// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size + //// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used + //// without any storage on user's side. + IM_ASSERT(apply_new_text_length >= 0); + if (is_resizable) + { + ImGuiInputTextCallbackData callback_data; + callback_data.Ctx = &g; + callback_data.ID = id; + callback_data.Flags = flags; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); + callback_data.Buf = buf; + callback_data.BufTextLen = apply_new_text_length; + callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); + callback_data.UserData = callback_user_data; + callback(&callback_data); + buf = callback_data.Buf; + buf_size = callback_data.BufSize; + apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1); + IM_ASSERT(apply_new_text_length <= buf_size); + } + //IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length); + + // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. + ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size)); + } + + // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) + // Otherwise request text input ahead for next frame. + if (g.ActiveId == id && clear_active_id) + ClearActiveID(); + + // Render frame + if (!is_multiline) + { + RenderNavCursor(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + } + + ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.0f, 0.0f); + ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size + if (is_multiline) + clip_rect.ClipWith(draw_window->ClipRect); + + // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line + // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. + // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. + const int buf_display_max_length = 2 * 1024 * 1024; + const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595 + const char* buf_display_end = NULL; // We have specialized paths below for setting the length + + // Display hint when contents is empty + // At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368) + const bool new_is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); + if (new_is_displaying_hint != is_displaying_hint) + { + if (is_password && !is_displaying_hint) + PopPasswordFont(); + is_displaying_hint = new_is_displaying_hint; + if (is_password && !is_displaying_hint) + PushPasswordFont(); + } + if (is_displaying_hint) + { + buf_display = hint; + buf_display_end = hint + ImStrlen(hint); + } + else + { + if (render_cursor || render_selection || g.ActiveId == id) + buf_display_end = buf_display + state->TextLen; //-V595 + else if (is_multiline && !is_wordwrap) + buf_display_end = NULL; // Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path. + else + buf_display_end = buf_display + ImStrlen(buf_display); + } + + // Calculate visibility + int line_visible_n0 = 0, line_visible_n1 = 1; + if (is_multiline) + CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1); + + // Build line index for easy data access (makes code below simpler and faster) + ImGuiTextIndex* line_index = &g.InputTextLineIndex; + line_index->Offsets.resize(0); + int line_count = 1; + if (is_multiline) + { + // If scrolling is expected to change build full index. + // FIXME-OPT: Could append to index when new value of line_visible_n1 becomes bigger, see second call to CalcClipRectVisibleItemsY() below. + bool will_scroll_y = state && ((state->CursorFollow && render_cursor) || (state->CursorCenterY && (render_cursor || render_selection))); + line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, will_scroll_y ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end); + } + line_index->EndOffset = (int)(buf_display_end - buf_display); + line_visible_n1 = ImMin(line_visible_n1, line_count); + + // Store text height (we don't need width) + text_size = ImVec2(inner_size.x, line_count * g.FontSize); + //GetForegroundDrawList()->AddRect(draw_pos + ImVec2(0, line_visible_n0 * g.FontSize), draw_pos + ImVec2(frame_size.x, line_visible_n1 * g.FontSize), IM_COL32(255, 0, 0, 255)); + + // Calculate blinking cursor position + const ImVec2 cursor_offset = render_cursor && state ? InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state->Stb->cursor) : ImVec2(0.0f, 0.0f); + ImVec2 draw_scroll; + + // Render text. We currently only render selection when the widget is active or while scrolling. + const ImU32 text_col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); + if (render_cursor || render_selection) + { + // Render text (with cursor and selection) + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + IM_ASSERT(state != NULL); + state->LineCount = line_count; + + // Scroll + float new_scroll_y = scroll_y; + if (render_cursor && state->CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = inner_size.x * 0.25f; + const float visible_width = inner_size.x - style.FramePadding.x; + if (cursor_offset.x < state->Scroll.x) + state->Scroll.x = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x)); + else if (cursor_offset.x - visible_width >= state->Scroll.x) + state->Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x); + } + else + { + state->Scroll.x = 0.0f; + } + + // Vertical scroll + if (is_multiline) + { + // Test if cursor is vertically visible + if (cursor_offset.y - g.FontSize < scroll_y) + new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y) + new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; + } + state->CursorFollow = false; + } + if (state->CursorCenterY) + { + if (is_multiline) + new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5f - style.FramePadding.y); + state->CursorCenterY = false; + render_cursor = false; + } + if (new_scroll_y != scroll_y) + { + const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); + scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y); + draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag + draw_window->Scroll.y = scroll_y; + CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1); + line_visible_n1 = ImMin(line_visible_n1, line_count); + } + + // Draw selection + draw_scroll.x = state->Scroll.x; + if (render_selection) + { + const ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + const float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + const float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + const float bg_eol_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + + const char* text_selected_begin = buf_display + ImMin(state->Stb->select_start, state->Stb->select_end); + const char* text_selected_end = buf_display + ImMax(state->Stb->select_start, state->Stb->select_end); + for (int line_n = line_visible_n0; line_n < line_visible_n1; line_n++) + { + const char* p = line_index->get_line_begin(buf_display, line_n); + const char* p_eol = line_index->get_line_end(buf_display, line_n); + const bool p_eol_is_wrap = (p_eol < buf_display_end && *p_eol != '\n'); + if (p_eol_is_wrap) + p_eol++; + const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p; + const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol; + + float rect_width = 0.0f; + if (line_selected_begin < line_selected_end) + rect_width += CalcTextSize(line_selected_begin, line_selected_end).x; + if (text_selected_begin <= p_eol && text_selected_end > p_eol && !p_eol_is_wrap) + rect_width += bg_eol_width; // So we can see selected empty lines + if (rect_width == 0.0f) + continue; + + ImRect rect; + rect.Min.x = draw_pos.x - draw_scroll.x + CalcTextSize(p, line_selected_begin).x; + rect.Min.y = draw_pos.y - draw_scroll.y + line_n * g.FontSize; + rect.Max.x = rect.Min.x + rect_width; + rect.Max.y = rect.Min.y + bg_offy_dn + g.FontSize; + rect.Min.y -= bg_offy_up; + rect.ClipWith(clip_rect); + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + } + } + + // Find render position for right alignment (single-line only) + if (g.ActiveId != id && flags & ImGuiInputTextFlags_ElideLeft) + draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); + //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive? + + // Render text + if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) + g.Font->RenderText(draw_window->DrawList, g.FontSize, + draw_pos - draw_scroll + ImVec2(0.0f, line_visible_n0 * g.FontSize), + text_col, clip_rect.AsVec4(), + line_index->get_line_begin(buf_display, line_visible_n0), + line_index->get_line_end(buf_display, line_visible_n1 - 1), + wrap_width, ImDrawTextFlags_WrapKeepBlanks | ImDrawTextFlags_CpuFineClip); + + // Render blinking cursor + if (render_cursor) + { + state->CursorAnim += io.DeltaTime; + bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + // This is required for some backends (SDL3) to start emitting character/text inputs. + // As per #6341, make sure we don't set that on the deactivating frame. + if (!is_readonly && g.ActiveId == id) + { + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler) + ime_data->WantVisible = true; + ime_data->WantTextInput = true; + ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + ime_data->InputLineHeight = g.FontSize; + ime_data->ViewportId = window->Viewport->ID; + } + } + + if (is_password && !is_displaying_hint) + PopPasswordFont(); + + if (is_multiline) + { + // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)... + Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y)); + g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; + EndChild(); + item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow); + + // ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active... + // FIXME: This quite messy/tricky, should attempt to get rid of the child window. + EndGroup(); + if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y)) + { + g.LastItemData.ID = id; + g.LastItemData.ItemFlags = item_data_backup.ItemFlags; + g.LastItemData.StatusFlags = item_data_backup.StatusFlags; + } + } + if (state && is_readonly) + state->TextSrc = NULL; + + // Log as text + if (g.LogEnabled && (!is_password || is_displaying_hint)) + { + LogSetNextTextDecoration("{", "}"); + LogRenderedText(&draw_pos, buf_display, buf_display_end); + } + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if (value_changed) + MarkItemEdited(id); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable); + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return validated; + else + return value_changed; +} + +void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + ImGuiContext& g = *GImGui; + ImStb::STB_TexteditState* stb_state = state->Stb; + ImStb::StbUndoState* undo_state = &stb_state->undostate; + Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId); + DebugLocateItemOnHover(state->ID); + Text("TextLen: %d, Cursor: %d%s, Selection: %d..%d", state->TextLen, stb_state->cursor, + (state->Flags & ImGuiInputTextFlags_WordWrap) ? (state->LastMoveDirectionLR == ImGuiDir_Left ? " (L)" : " (R)") : "", + stb_state->select_start, stb_state->select_end); + Text("BufCapacity: %d, LineCount: %d", state->BufCapacity, state->LineCount); + Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity); + Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x); + Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point); + if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state + { + PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + for (int n = 0; n < IMSTB_TEXTEDIT_UNDOSTATECOUNT; n++) + { + ImStb::StbUndoRecord* undo_rec = &undo_state->undo_rec[n]; + const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' '; + if (undo_rec_type == ' ') + BeginDisabled(); + const int buf_preview_len = (undo_rec_type != ' ' && undo_rec->char_storage != -1) ? undo_rec->insert_length : 0; + const char* buf_preview_str = undo_state->undo_char + undo_rec->char_storage; + Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"", + undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, buf_preview_len, buf_preview_str); + if (undo_rec_type == ' ') + EndDisabled(); + } + PopStyleVar(); + } + EndChild(); +#else + IM_UNUSED(state); +#endif +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +//------------------------------------------------------------------------- +// - ColorEdit3() +// - ColorEdit4() +// - ColorPicker3() +// - RenderColorRectWithAlphaCheckerboard() [Internal] +// - ColorPicker4() +// - ColorButton() +// - SetColorEditOptions() +// - ColorTooltip() [Internal] +// - ColorEditOptionsPopup() [Internal] +// - ColorPickerOptionsPopup() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); +} + +static void ColorEditRestoreH(const float* col, float* H) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.ColorEditCurrentID != 0); + if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0))) + return; + *H = g.ColorEditSavedHue; +} + +// ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation. +// Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting. +static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.ColorEditCurrentID != 0); + if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0))) + return; + + // When S == 0, H is undefined. + // When H == 1 it wraps around to 0. + if (*S == 0.0f || (*H == 0.0f && g.ColorEditSavedHue == 1)) + *H = g.ColorEditSavedHue; + + // When V == 0, S is undefined. + if (*V == 0.0f) + *S = g.ColorEditSavedSat; +} + +// Edit colors components (each component in 0.0f..1.0f range). +// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// With typical options: Left-click on color square to open color picker. Right-click to open option menu. Ctrl+Click over input fields to edit them and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float square_sz = GetFrameHeight(); + const char* label_display_end = FindRenderedTextEnd(label); + float w_full = CalcItemWidth(); + g.NextItemData.ClearFlags(); + + BeginGroup(); + PushID(label); + const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0); + if (set_current_color_edit_id) + g.ColorEditCurrentID = window->IDStack.back(); + + // If we're not showing any slider there's no point in doing any HSV conversions + const ImGuiColorEditFlags flags_untouched = flags; + if (flags & ImGuiColorEditFlags_NoInputs) + flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions; + + // Context menu: display and modify options (before defaults are applied) + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorEditOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags_DisplayMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_); + if (!(flags & ImGuiColorEditFlags_DataTypeMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_); + if (!(flags & ImGuiColorEditFlags_PickerMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_); + if (!(flags & ImGuiColorEditFlags_InputMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_)); + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected + + const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; + const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; + const int components = alpha ? 4 : 3; + const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); + const float w_inputs = ImMax(w_full - w_button, 1.0f); + w_full = w_inputs + w_button; + + // Convert to the formats we need + float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; + if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB)) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV)) + { + // Hue is lost when converting from grayscale rgb (saturation=0). Restore it. + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorEditRestoreHS(col, &f[0], &f[1], &f[2]); + } + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; + + bool value_changed = false; + bool value_changed_as_float = false; + + const ImVec2 pos = window->DC.CursorPos; + const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f; + window->DC.CursorPos.x = pos.x + inputs_offset_x; + + if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB/HSV 0..255 Sliders + const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1); + const float w_per_component = IM_TRUNC(w_items / components); + const bool draw_color_marker = (flags & (ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoColorMarkers)) == 0; + + const bool hide_prefix = draw_color_marker || (w_per_component <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); + static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + static const char* fmt_table_int[3][4] = + { + { "%3d", "%3d", "%3d", "%3d" }, // Short display + { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA + { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA + }; + static const char* fmt_table_float[3][4] = + { + { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display + { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA + { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA + }; + const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; + const ImGuiSliderFlags drag_flags = draw_color_marker ? ImGuiSliderFlags_ColorMarkers : ImGuiSliderFlags_None; + + float prev_split = 0.0f; + for (int n = 0; n < components; n++) + { + if (n > 0) + SameLine(0, style.ItemInnerSpacing.x); + float next_split = IM_TRUNC(w_items * (n + 1) / components); + SetNextItemWidth(ImMax(next_split - prev_split, 1.0f)); + prev_split = next_split; + if (draw_color_marker) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[n]); + + // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. + if (flags & ImGuiColorEditFlags_Float) + { + value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n], drag_flags); + value_changed_as_float |= value_changed; + } + else + { + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n], drag_flags); + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + } + else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB Hexadecimal Input + char buf[64]; + if (alpha) + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255)); + else + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255)); + SetNextItemWidth(w_inputs); + if (InputText("##Text", buf, IM_COUNTOF(buf), ImGuiInputTextFlags_CharsUppercase)) + { + value_changed = true; + char* p = buf; + while (*p == '#' || ImCharIsBlankA(*p)) + p++; + i[0] = i[1] = i[2] = 0; + i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha) + int r; + if (alpha) + r = sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + r = sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'. + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + + ImGuiWindow* picker_active_window = NULL; + if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) + { + const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x; + window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y); + + const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); + if (ColorButton("##ColorButton", col_v4, flags)) + { + if (!(flags & ImGuiColorEditFlags_NoPicker)) + { + // Store current color and open a picker + g.ColorPickerRef = col_v4; + OpenPopup("picker"); + SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y)); + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + + if (BeginPopup("picker")) + { + if (g.CurrentWindow->BeginCount == 1) + { + picker_active_window = g.CurrentWindow; + if (label != label_display_end) + { + TextEx(label, label_display_end); + Spacing(); + } + ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? + value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); + } + EndPopup(); + } + } + + if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) + { + // Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left), + // but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this. + SameLine(0.0f, style.ItemInnerSpacing.x); + window->DC.CursorPos.x = pos.x + ((flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x); + TextEx(label, label_display_end); + } + + // Convert back + if (value_changed && picker_active_window == NULL) + { + if (!value_changed_as_float) + for (int n = 0; n < 4; n++) + f[n] = i[n] / 255.0f; + if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB)) + { + g.ColorEditSavedHue = f[0]; + g.ColorEditSavedSat = f[1]; + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + g.ColorEditSavedID = g.ColorEditCurrentID; + g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0)); + } + if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; + } + + if (set_current_color_edit_id) + g.ColorEditCurrentID = 0; + PopID(); + EndGroup(); + + // Drag and Drop Target + // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. + if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget()) + { + bool accepted_drag_drop = false; + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 //-V1086 + value_changed = accepted_drag_drop = true; + } + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * components); + value_changed = accepted_drag_drop = true; + } + + // Drag-drop payloads are always RGB + if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]); + EndDragDropTarget(); + } + + // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). + if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window) + g.LastItemData.ID = g.ActiveId; + + if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + float col4[4] = { col[0], col[1], col[2], 1.0f }; + if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) + return false; + col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; + return true; +} + +// Helper for ColorPicker4() +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) +{ + ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); +} + +// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) +// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +// FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) +bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImDrawList* draw_list = window->DrawList; + ImGuiStyle& style = g.Style; + ImGuiIO& io = g.IO; + + const float width = CalcItemWidth(); + const bool is_readonly = ((g.NextItemData.ItemFlags | g.CurrentItemFlags) & ImGuiItemFlags_ReadOnly) != 0; + g.NextItemData.ClearFlags(); + + PushID(label); + const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0); + if (set_current_color_edit_id) + g.ColorEditCurrentID = window->IDStack.back(); + BeginGroup(); + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + flags |= ImGuiColorEditFlags_NoSmallPreview; + + // Context menu: display and store options. + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorPickerOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags_PickerMask_)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_; + if (!(flags & ImGuiColorEditFlags_InputMask_)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected + if (!(flags & ImGuiColorEditFlags_NoOptions)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); + + // Setup + int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4; + bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha); + ImVec2 picker_pos = window->DC.CursorPos; + float square_sz = GetFrameHeight(); + float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars + float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box + float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; + float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; + float bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20f); + + float backup_initial_col[4]; + memcpy(backup_initial_col, col, components * sizeof(float)); + + float wheel_thickness = sv_picker_size * 0.08f; + float wheel_r_outer = sv_picker_size * 0.50f; + float wheel_r_inner = wheel_r_outer - wheel_thickness; + ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f); + + // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. + float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); + ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point. + ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. + ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. + + float H = col[0], S = col[1], V = col[2]; + float R = col[0], G = col[1], B = col[2]; + if (flags & ImGuiColorEditFlags_InputRGB) + { + // Hue is lost when converting from grayscale rgb (saturation=0). Restore it. + ColorConvertRGBtoHSV(R, G, B, H, S, V); + ColorEditRestoreHS(col, &H, &S, &V); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + ColorConvertHSVtoRGB(H, S, V, R, G, B); + } + + bool value_changed = false, value_changed_h = false, value_changed_sv = false; + + PushItemFlag(ImGuiItemFlags_NoNav, true); + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Hue wheel + SV triangle logic + InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size)); + if (IsItemActive() && !is_readonly) + { + ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; + ImVec2 current_off = g.IO.MousePos - wheel_center; + float initial_dist2 = ImLengthSqr(initial_off); + if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1)) + { + // Interactive with Hue wheel + H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f; + if (H < 0.0f) + H += 1.0f; + value_changed = value_changed_h = true; + } + float cos_hue_angle = ImCos(-H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(-H * 2.0f * IM_PI); + if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle))) + { + // Interacting with SV triangle + ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle); + if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)) + current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated); + float uu, vv, ww; + ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww); + V = ImClamp(1.0f - vv, 0.0001f, 1.0f); + S = ImClamp(uu / V, 0.0001f, 1.0f); + value_changed = value_changed_sv = true; + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // SV rectangle logic + InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); + if (IsItemActive() && !is_readonly) + { + S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1)); + V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + ColorEditRestoreH(col, &H); // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. + value_changed = value_changed_sv = true; + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + + // Hue bar logic + SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); + InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive() && !is_readonly) + { + H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + value_changed = value_changed_h = true; + } + } + + // Alpha bar logic + if (alpha_bar) + { + SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y)); + InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive()) + { + col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + value_changed = true; + } + } + PopItemFlag(); // ImGuiItemFlags_NoNav + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + SameLine(0, style.ItemInnerSpacing.x); + BeginGroup(); + } + + if (!(flags & ImGuiColorEditFlags_NoLabel)) + { + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + if ((flags & ImGuiColorEditFlags_NoSidePreview)) + SameLine(0, style.ItemInnerSpacing.x); + TextEx(label, label_display_end); + } + } + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if ((flags & ImGuiColorEditFlags_NoLabel)) + Text("Current"); + + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoTooltip; + ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); + if (ref_col != NULL) + { + Text("Original"); + ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); + if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2))) + { + memcpy(col, ref_col, components * sizeof(float)); + value_changed = true; + } + } + PopItemFlag(); + EndGroup(); + } + + // Convert back color to RGB + if (value_changed_h || value_changed_sv) + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]); + g.ColorEditSavedHue = H; + g.ColorEditSavedSat = S; + g.ColorEditSavedID = g.ColorEditCurrentID; + g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + col[0] = H; + col[1] = S; + col[2] = V; + } + } + + // R,G,B and H,S,V slider color editor + bool value_changed_fix_hue_wrap = false; + if ((flags & ImGuiColorEditFlags_NoInputs) == 0) + { + PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview; + ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; + if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) + { + // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. + // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) + value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); + value_changed = true; + } + if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV); + if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex); + PopItemWidth(); + } + + // Try to cancel hue wrap (after ColorEdit4 call), if any + if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB)) + { + float new_H, new_S, new_V; + ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); + if (new_H <= 0 && H > 0) + { + if (new_V <= 0 && V != new_V) + ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]); + else if (new_S <= 0) + ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]); + } + } + + if (value_changed) + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + R = col[0]; + G = col[1]; + B = col[2]; + ColorConvertRGBtoHSV(R, G, B, H, S, V); + ColorEditRestoreHS(col, &H, &S, &V); // Fix local Hue as display below will use it immediately. + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + H = col[0]; + S = col[1]; + V = col[2]; + ColorConvertHSVtoRGB(H, S, V, R, G, B); + } + } + + const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha); + const ImU32 col_black = IM_COL32(0,0,0,style_alpha8); + const ImU32 col_white = IM_COL32(255,255,255,style_alpha8); + const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8); + const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) }; + + ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); + ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); + ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!! + + ImVec2 sv_cursor_pos; + + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Render Hue Wheel + const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). + const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); + for (int n = 0; n < 6; n++) + { + const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps; + const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; + const int vert_start_idx = draw_list->VtxBuffer.Size; + draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); + draw_list->PathStroke(col_white, 0, wheel_thickness); + const int vert_end_idx = draw_list->VtxBuffer.Size; + + // Paint colors over existing vertices + ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); + ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); + ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]); + } + + // Render Cursor + preview on Hue Wheel + float cos_hue_angle = ImCos(H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(H * 2.0f * IM_PI); + ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f); + float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; + int hue_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(hue_cursor_rad); // Lock segment count so the +1 one matches others. + draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments); + + // Render SV triangle (rotated according to hue) + ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); + ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle); + ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle); + ImVec2 uv_white = GetFontTexUvWhitePixel(); + draw_list->PrimReserve(3, 3); + draw_list->PrimVtx(tra, uv_white, hue_color32); + draw_list->PrimVtx(trb, uv_white, col_black); + draw_list->PrimVtx(trc, uv_white, col_white); + draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f); + sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // Render SV Square + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white); + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black); + RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f); + sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much + sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); + + // Render Hue Bar + for (int i = 0; i < 6; ++i) + draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]); + float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size); + RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); + } + + // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) + float sv_cursor_rad = value_changed_sv ? wheel_thickness * 0.55f : wheel_thickness * 0.40f; + int sv_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(sv_cursor_rad); // Lock segment count so the +1 one matches others. + draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments); + + // Render alpha bar + if (alpha_bar) + { + float alpha = ImSaturate(col[3]); + ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); + RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); + draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK); + float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size); + RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); + } + + EndGroup(); + + if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0) + value_changed = false; + if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId + MarkItemEdited(g.LastItemData.ID); + + if (set_current_color_edit_id) + g.ColorEditCurrentID = 0; + PopID(); + + return value_changed; +} + +// A little color square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. +bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(desc_id); + const float default_size = GetFrameHeight(); + const ImVec2 size(size_arg.x == 0.0f ? default_size : size_arg.x, size_arg.y == 0.0f ? default_size : size_arg.y); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + if (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque)) + flags &= ~(ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf); + + ImVec4 col_rgb = col; + if (flags & ImGuiColorEditFlags_InputHSV) + ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z); + + ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); + float grid_step = ImMin(size.x, size.y) / 2.99f; + float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); + ImRect bb_inner = bb; + float off = 0.0f; + if ((flags & ImGuiColorEditFlags_NoBorder) == 0) + { + off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. + bb_inner.Expand(off); + } + if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) + { + float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f); + if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0) + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight); + else + window->DrawList->AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight); + window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft); + } + else + { + // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha + ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaOpaque) ? col_rgb_without_alpha : col_rgb; + if (col_source.w < 1.0f && (flags & ImGuiColorEditFlags_AlphaNoBg) == 0) + RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); + else + window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding); + } + RenderNavCursor(bb, id); + if ((flags & ImGuiColorEditFlags_NoBorder) == 0) + { + if (g.Style.FrameBorderSize > 0.0f) + RenderFrameBorder(bb.Min, bb.Max, rounding); + else + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI + } + + // Drag and Drop Source + // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test. + if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource()) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once); + else + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once); + ColorButton(desc_id, col, flags); + SameLine(); + TextEx("Color"); + EndDragDropSource(); + } + + // Tooltip + if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_)); + + return pressed; +} + +// Initialize/override default color options +// FIXME: Could be moved to a simple IO field. +void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_; + if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_; + if ((flags & ImGuiColorEditFlags_PickerMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_; + if ((flags & ImGuiColorEditFlags_InputMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check only 1 option is selected + g.ColorEditOptions = flags; +} + +// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + + if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None)) + return; + const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; + if (text_end > text) + { + TextEx(text, text_end); + Separator(); + } + + ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); + ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + ImGuiColorEditFlags flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_; + ColorButton("##preview", cf, (flags & flags_to_forward) | ImGuiColorEditFlags_NoTooltip, sz); + SameLine(); + if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_)) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); + else + Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]); + else + Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]); + } + EndTooltip(); +} + +void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) +{ + bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_); + bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_); + if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) + return; + + ImGuiContext& g = *GImGui; + PushItemFlag(ImGuiItemFlags_NoMarkEdited, true); + ImGuiColorEditFlags opts = g.ColorEditOptions; + if (allow_opt_inputs) + { + if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB; + if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV; + if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex; + } + if (allow_opt_datatype) + { + if (allow_opt_inputs) Separator(); + if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8; + if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float; + } + + if (allow_opt_inputs || allow_opt_datatype) + Separator(); + if (Button("Copy as..", ImVec2(-1, 0))) + OpenPopup("Copy"); + if (BeginPopup("Copy")) + { + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + char buf[64]; + ImFormatString(buf, IM_COUNTOF(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if (Selectable(buf)) + SetClipboardText(buf); + ImFormatString(buf, IM_COUNTOF(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X", cr, cg, cb); + if (Selectable(buf)) + SetClipboardText(buf); + if (!(flags & ImGuiColorEditFlags_NoAlpha)) + { + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + } + EndPopup(); + } + + g.ColorEditOptions = opts; + PopItemFlag(); + EndPopup(); +} + +void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags) +{ + bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_); + bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); + if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context")) + return; + + ImGuiContext& g = *GImGui; + PushItemFlag(ImGuiItemFlags_NoMarkEdited, true); + if (allow_opt_picker) + { + ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function + PushItemWidth(picker_size.x); + for (int picker_type = 0; picker_type < 2; picker_type++) + { + // Draw small/thumbnail version of each picker type (over an invisible button for selection) + if (picker_type > 0) Separator(); + PushID(picker_type); + ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha); + if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; + ImVec2 backup_pos = GetCursorScreenPos(); + if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup + g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_); + SetCursorScreenPos(backup_pos); + ImVec4 previewing_ref_col; + memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); + ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags); + PopID(); + } + PopItemWidth(); + } + if (allow_opt_alpha_bar) + { + if (allow_opt_picker) Separator(); + CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); + } + PopItemFlag(); + EndPopup(); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +//------------------------------------------------------------------------- +// - TreeNode() +// - TreeNodeV() +// - TreeNodeEx() +// - TreeNodeExV() +// - TreeNodeStoreStackData() [Internal] +// - TreeNodeBehavior() [Internal] +// - TreePush() +// - TreePop() +// - GetTreeNodeToLabelSpacing() +// - SetNextItemOpen() +// - CollapsingHeader() +//------------------------------------------------------------------------- + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, flags, label, NULL); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiID id = window->GetID(str_id); + const char* label, *label_end; + ImFormatStringToTempBufferV(&label, &label_end, fmt, args); + return TreeNodeBehavior(id, flags, label, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiID id = window->GetID(ptr_id); + const char* label, *label_end; + ImFormatStringToTempBufferV(&label, &label_end, fmt, args); + return TreeNodeBehavior(id, flags, label, label_end); +} + +bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) +{ + ImGuiContext& g = *GImGui; + ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; + return storage->GetInt(storage_id, 0) != 0; +} + +void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open) +{ + ImGuiContext& g = *GImGui; + ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; + storage->SetInt(storage_id, open ? 1 : 0); +} + +bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) +{ + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; + + // We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStorage* storage = window->DC.StateStorage; + + bool is_open; + if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasOpen) + { + if (g.NextItemData.OpenCond & ImGuiCond_Always) + { + is_open = g.NextItemData.OpenVal; + TreeNodeSetOpen(storage_id, is_open); + } + else + { + // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. + const int stored_value = storage->GetInt(storage_id, -1); + if (stored_value == -1) + { + is_open = g.NextItemData.OpenVal; + TreeNodeSetOpen(storage_id, is_open); + } + else + { + is_open = stored_value != 0; + } + } + } + else + { + is_open = storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + } + + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand) + is_open = true; + + return is_open; +} + +// Store ImGuiTreeNodeStackData for just submitted node. +// Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. +static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1); + ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + tree_node_data->ID = g.LastItemData.ID; + tree_node_data->TreeFlags = flags; + tree_node_data->ItemFlags = g.LastItemData.ItemFlags; + tree_node_data->NavRect = g.LastItemData.NavRect; + + // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. + const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0; + tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; + tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; + tree_node_data->DrawLinesToNodesY2 = -FLT_MAX; + window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); + if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) + window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth); +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // When not framed, we vertically increase height up to typical framed widget height + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const bool use_frame_padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)); + const ImVec2 padding = use_frame_padding ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y)); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing + const float text_offset_y = use_frame_padding ? ImMax(style.FramePadding.y, window->DC.CurrLineTextBaseOffset) : window->DC.CurrLineTextBaseOffset; // Latch before ItemSize changes it + const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow + + const float frame_height = label_size.y + padding.y * 2; + const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); + const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL); + ImRect frame_bb; + frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; + frame_bb.Min.y = window->DC.CursorPos.y + (text_offset_y - padding.y); + frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanLabelWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x; + frame_bb.Max.y = window->DC.CursorPos.y + (text_offset_y - padding.y) + frame_height; + if (display_frame) + { + const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits + frame_bb.Min.x -= outer_extend; + frame_bb.Max.x += outer_extend; + } + + ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y); + ItemSize(ImVec2(text_width, frame_height), padding.y); + + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + ImRect interact_bb = frame_bb; + if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanLabelWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0) + interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f); + + // Compute open and multi-select states before ItemAdd() as it clear NextItem data. + ImGuiID storage_id = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id; + bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); + + bool is_visible; + if (span_all_columns || span_all_columns_label) + { + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. + const float backup_clip_rect_min_x = window->ClipRect.Min.x; + const float backup_clip_rect_max_x = window->ClipRect.Max.x; + window->ClipRect.Min.x = window->ParentWorkRect.Min.x; + window->ClipRect.Max.x = window->ParentWorkRect.Max.x; + is_visible = ItemAdd(interact_bb, id); + window->ClipRect.Min.x = backup_clip_rect_min_x; + window->ClipRect.Max.x = backup_clip_rect_max_x; + } + else + { + is_visible = ItemAdd(interact_bb, id); + } + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; + g.LastItemData.DisplayRect = frame_bb; + + // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled: + // Store data for the current depth to allow returning to this node from any child item. + // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). + // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle. + bool store_tree_node_stack_data = false; + if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) + flags |= g.Style.TreeLinesFlags; + const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); + if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + { + store_tree_node_stack_data = draw_tree_lines; + if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive) + if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + store_tree_node_stack_data = true; + } + + const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; + if (!is_visible) + { + if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1)))) + { + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. + if (frame_bb.Min.y >= window->ClipRect.Max.y) + window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done + } + if (is_open && store_tree_node_stack_data) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushOverrideID(id); + IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); + return is_open; + } + + if (span_all_columns || span_all_columns_label) + { + TablePushBackgroundChannel(); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect; + g.LastItemData.ClipRect = window->ClipRect; + } + + ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None; + if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) + button_flags |= ImGuiButtonFlags_AllowOverlap; + if (!is_leaf) + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + + // We allow clicking on the arrow section with keyboard modifiers held, in order to easily + // allow browsing a tree while preserving selection with code implementing multi-selection patterns. + // When clicking on the rest of the tree node we always disallow keyboard modifiers. + const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x; + const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x; + const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2); + + const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; + if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default + flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow; + + // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. + // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. + // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) + // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) + // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) + // It is rather standard that arrow click react on Down rather than Up. + // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. + if (is_mouse_x_over_arrow) + button_flags |= ImGuiButtonFlags_PressedOnClick; + else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + if (flags & ImGuiTreeNodeFlags_NoNavFocus) + button_flags |= ImGuiButtonFlags_NoNavFocus; + + bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; + const bool was_selected = selected; + + // Multi-selection support (header) + if (is_multi_select) + { + // Handle multi-select + alter button flags for it + MultiSelectItemHeader(id, &selected, &button_flags); + if (is_mouse_x_over_arrow) + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; + } + else + { + if (window != g.HoveredWindow || !is_mouse_x_over_arrow) + button_flags |= ImGuiButtonFlags_NoKeyModsAllowed; + } + + bool hovered, held; + bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + bool toggled = false; + if (!is_leaf) + { + if (pressed && g.DragDropHoldJustPressedId != id) + { + if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select)) + toggled = true; // Single click + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= is_mouse_x_over_arrow && !g.NavHighlightItemUnderNav; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job + if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2) + toggled = true; // Double click + } + else if (pressed && g.DragDropHoldJustPressedId == id) + { + IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold); + if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. + toggled = true; + else + pressed = false; // Cancel press so it doesn't trigger selection. + } + + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open) + { + toggled = true; + NavClearPreferredPosForAxis(ImGuiAxis_X); + NavMoveRequestCancel(); + } + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority? + { + toggled = true; + NavClearPreferredPosForAxis(ImGuiAxis_X); + NavMoveRequestCancel(); + } + + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(storage_id, is_open); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen; + } + } + + // Multi-selection support (footer) + if (is_multi_select) + { + bool pressed_copy = pressed && !toggled; + MultiSelectItemFooter(id, &selected, &pressed_copy); + if (pressed) + SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb); + } + + if (selected != was_selected) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + + // Render + { + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact; + if (is_multi_select) + nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle + if (display_frame) + { + // Framed type + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); + RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); + else if (!is_leaf) + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 1.0f); + else // Leaf without bullet, left-adjusted text + text_pos.x -= text_offset_x - padding.x; + if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) + frame_bb.Max.x -= g.FontSize + style.FramePadding.x; + if (g.LogEnabled) + LogSetNextTextDecoration("###", "###"); + } + else + { + // Unframed typed for tree nodes + if (hovered || selected) + { + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); + } + RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); + else if (!is_leaf) + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); + if (g.LogEnabled) + LogSetNextTextDecoration(">", NULL); + } + + if (draw_tree_lines) + TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f)); + + // Label + if (display_frame) + RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + else + RenderText(text_pos, label, label_end, false); + + if (span_all_columns_label) + TablePopBackgroundChannel(); + } + + if (is_open && store_tree_node_stack_data) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); + return is_open; +} + +// Draw horizontal line from our parent node +// This is only called for visible child nodes so we are not too fussy anymore about performances +void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0) + return; + + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + float x1 = ImTrunc(parent_data->DrawLinesX1); + float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); + float y = ImTrunc(target_pos.y); + float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); + if (x1 >= x2) + return; + if (rounding > 0.0f) + { + x1 += 0.5f + rounding; + window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); + if (x1 < x2) + window->DrawList->PathLineTo(ImVec2(x2, y)); + window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize); + } + else + { + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + } +} + +// Draw vertical line of the hierarchy +void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); + float y2 = data->DrawLinesToNodesY2; + if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) + { + float y2_full = window->DC.CursorPos.y; + if (g.CurrentTable) + y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); + y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + if (y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y + y2 = y2_full; + } + y2 = ImMin(y2, window->ClipRect.Max.y); + if (y2 <= y1) + return; + float x = ImTrunc(data->DrawLinesX1); + if (data->DrawLinesTableColumn != -1) + TablePushColumnChannel(data->DrawLinesTableColumn); + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + if (data->DrawLinesTableColumn != -1) + TablePopColumnChannel(); +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(str_id); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(ptr_id); +} + +void ImGui::TreePushOverrideID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + Indent(); + window->DC.TreeDepth++; + PushOverrideID(id); +} + +void ImGui::TreePop() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + Unindent(); + + window->DC.TreeDepth--; + ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); + + if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) + { + const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + IM_ASSERT(data->ID == window->IDStack.back()); + + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled) + if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) + if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); + + // Draw hierarchy lines + if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y) + TreeNodeDrawLineToTreePop(data); + + g.TreeNodeStack.pop_back(); + window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; + window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask; + } + + IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. + PopID(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +// Set next TreeNode/CollapsingHeader open state. +void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->SkipItems) + return; + g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasOpen; + g.NextItemData.OpenVal = is_open; + g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always); +} + +// Set next TreeNode/CollapsingHeader storage id. +void ImGui::SetNextItemStorageID(ImGuiID storage_id) +{ + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->SkipItems) + return; + g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasStorageID; + g.NextItemData.StorageId = storage_id; +} + +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label); +} + +// p_visible == NULL : regular collapsing header +// p_visible != NULL && *p_visible == true : show a small close button on the corner of the header, clicking the button will set *p_visible = false +// p_visible != NULL && *p_visible == false : do not show the header at all +// Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen. +bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (p_visible && !*p_visible) + return false; + + ImGuiID id = window->GetID(label); + flags |= ImGuiTreeNodeFlags_CollapsingHeader; + if (p_visible) + flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton; + bool is_open = TreeNodeBehavior(id, flags, label); + if (p_visible != NULL) + { + // Create a small overlapping close button + // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. + ImGuiContext& g = *GImGui; + ImGuiLastItemData last_item_backup = g.LastItemData; + float button_size = g.FontSize; + float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x - button_size); + float button_y = g.LastItemData.Rect.Min.y + g.Style.FramePadding.y; + ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id); + if (CloseButton(close_button_id, ImVec2(button_x, button_y))) + *p_visible = false; + g.LastItemData = last_item_backup; + } + + return is_open; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Selectable +//------------------------------------------------------------------------- +// - Selectable() +//------------------------------------------------------------------------- + +// Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. +// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. +// With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags. +// FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrLineTextBaseOffset; + ItemSize(size, 0.0f); + + // Fill horizontal space + // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets. + const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; + const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) + size.x = ImMax(label_size.x, max_x - min_x); + + // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. + // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos. + ImRect bb(min_x, pos.y, min_x + size.x, pos.y + size.y); + if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) + { + const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; + const float spacing_L = IM_TRUNC(spacing_x * 0.50f); + const float spacing_U = IM_TRUNC(spacing_y * 0.50f); + bb.Min.x -= spacing_L; + bb.Min.y -= spacing_U; + bb.Max.x += (spacing_x - spacing_L); + bb.Max.y += (spacing_y - spacing_U); + } + //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } + + const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; + const ImGuiItemFlags extra_item_flags = disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None; + bool is_visible; + if (span_all_columns) + { + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. + const float backup_clip_rect_min_x = window->ClipRect.Min.x; + const float backup_clip_rect_max_x = window->ClipRect.Max.x; + window->ClipRect.Min.x = window->ParentWorkRect.Min.x; + window->ClipRect.Max.x = window->ParentWorkRect.Max.x; + is_visible = ItemAdd(bb, id, NULL, extra_item_flags); + window->ClipRect.Min.x = backup_clip_rect_min_x; + window->ClipRect.Max.x = backup_clip_rect_max_x; + } + else + { + is_visible = ItemAdd(bb, id, NULL, extra_item_flags); + } + + const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; + if (!is_visible) + if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) // Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) + return false; + + const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + if (disabled_item && !disabled_global) // Only testing this as an optimization + BeginDisabled(); + + // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only, + // which would be advantageous since most selectable are not selected. + if (span_all_columns) + { + if (g.CurrentTable) + TablePushBackgroundChannel(); + else if (window->DC.CurrentColumns) + PushColumnsBackground(); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect; + g.LastItemData.ClipRect = window->ClipRect; + } + + // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; } + if (flags & ImGuiSelectableFlags_NoSetKeyOwner) { button_flags |= ImGuiButtonFlags_NoSetKeyOwner; } + if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; } + if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; } + if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; } + if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } + + // Multi-selection support (header) + const bool was_selected = selected; + if (is_multi_select) + { + // Handle multi-select + alter button flags for it + MultiSelectItemHeader(id, &selected, &button_flags); + } + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + bool auto_selected = false; + + // Multi-selection support (footer) + if (is_multi_select) + { + MultiSelectItemFooter(id, &selected, &pressed); + } + else + { + // Auto-select when moved into + // - This will be more fully fleshed in the range-select branch + // - This is not exposed as it won't nicely work with some user side handling of shift/control + // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons + // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) + // - (2) usage will fail with clipped items + // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. + if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) + if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0) + selected = pressed = auto_selected = true; + } + + // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad + if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) + { + if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) + { + SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect) + if (g.IO.ConfigNavCursorVisibleAuto) + g.NavCursorVisible = false; + } + } + if (pressed) + MarkItemEdited(id); + + if (selected != was_selected) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + + // Render + if (is_visible) + { + const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight); + if (highlighted || selected) + { + // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106) + ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + } + if (g.NavId == id) + { + ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding; + if (is_multi_select) + nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle + RenderNavCursor(bb, id, nav_render_cursor_flags); + } + } + + if (span_all_columns) + { + if (g.CurrentTable) + TablePopBackgroundChannel(); + else if (window->DC.CurrentColumns) + PopColumnsBackground(); + } + + // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns. + if (is_visible) + RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb); + + // Automatically close popups + if (pressed && !auto_selected && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) + CloseCurrentPopup(); + + if (disabled_item && !disabled_global) + EndDisabled(); + + // Selectable() always returns a pressed state! + // Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve + // selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect(). + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; //-V1020 +} + +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + if (Selectable(label, *p_selected, flags, size_arg)) + { + *p_selected = !*p_selected; + return true; + } + return false; +} + + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Typing-Select support +//------------------------------------------------------------------------- + +// [Experimental] Currently not exposed in public API. +// Consume character inputs and return search request, if any. +// This would typically only be called on the focused window or location you want to grab inputs for, e.g. +// if (ImGui::IsWindowFocused(...)) +// if (ImGuiTypingSelectRequest* req = ImGui::GetTypingSelectRequest()) +// focus_idx = ImGui::TypingSelectFindMatch(req, my_items.size(), [](void*, int n) { return my_items[n]->Name; }, &my_items, -1); +// However the code is written in a way where calling it from multiple locations is safe (e.g. to obtain buffer). +ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiTypingSelectState* data = &g.TypingSelectState; + ImGuiTypingSelectRequest* out_request = &data->Request; + + // Clear buffer + const float TYPING_SELECT_RESET_TIMER = 1.80f; // FIXME: Potentially move to IO config. + const int TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK = 4; // Lock single char matching when repeating same char 4 times + if (data->SearchBuffer[0] != 0) + { + bool clear_buffer = false; + clear_buffer |= (g.NavFocusScopeId != data->FocusScope); + clear_buffer |= (data->LastRequestTime + TYPING_SELECT_RESET_TIMER < g.Time); + clear_buffer |= g.NavAnyRequest; + clear_buffer |= g.ActiveId != 0 && g.NavActivateId == 0; // Allow temporary SPACE activation to not interfere + clear_buffer |= IsKeyPressed(ImGuiKey_Escape) || IsKeyPressed(ImGuiKey_Enter); + clear_buffer |= IsKeyPressed(ImGuiKey_Backspace) && (flags & ImGuiTypingSelectFlags_AllowBackspace) == 0; + //if (clear_buffer) { IMGUI_DEBUG_LOG("GetTypingSelectRequest(): Clear SearchBuffer.\n"); } + if (clear_buffer) + data->Clear(); + } + + // Append to buffer + const int buffer_max_len = IM_COUNTOF(data->SearchBuffer) - 1; + int buffer_len = (int)ImStrlen(data->SearchBuffer); + bool select_request = false; + for (ImWchar w : g.IO.InputQueueCharacters) + { + const int w_len = ImTextCountUtf8BytesFromStr(&w, &w + 1); + if (w < 32 || (buffer_len == 0 && ImCharIsBlankW(w)) || (buffer_len + w_len > buffer_max_len)) // Ignore leading blanks + continue; + char w_buf[5]; + ImTextCharToUtf8(w_buf, (unsigned int)w); + if (data->SingleCharModeLock && w_len == out_request->SingleCharSize && memcmp(w_buf, data->SearchBuffer, w_len) == 0) + { + select_request = true; // Same character: don't need to append to buffer. + continue; + } + if (data->SingleCharModeLock) + { + data->Clear(); // Different character: clear + buffer_len = 0; + } + memcpy(data->SearchBuffer + buffer_len, w_buf, w_len + 1); // Append + buffer_len += w_len; + select_request = true; + } + g.IO.InputQueueCharacters.resize(0); + + // Handle backspace + if ((flags & ImGuiTypingSelectFlags_AllowBackspace) && IsKeyPressed(ImGuiKey_Backspace, ImGuiInputFlags_Repeat)) + { + char* p = (char*)(void*)ImTextFindPreviousUtf8Codepoint(data->SearchBuffer, data->SearchBuffer + buffer_len); + *p = 0; + buffer_len = (int)(p - data->SearchBuffer); + } + + // Return request if any + if (buffer_len == 0) + return NULL; + if (select_request) + { + data->FocusScope = g.NavFocusScopeId; + data->LastRequestFrame = g.FrameCount; + data->LastRequestTime = (float)g.Time; + } + out_request->Flags = flags; + out_request->SearchBufferLen = buffer_len; + out_request->SearchBuffer = data->SearchBuffer; + out_request->SelectRequest = (data->LastRequestFrame == g.FrameCount); + out_request->SingleCharMode = false; + out_request->SingleCharSize = 0; + + // Calculate if buffer contains the same character repeated. + // - This can be used to implement a special search mode on first character. + // - Performed on UTF-8 codepoint for correctness. + // - SingleCharMode is always set for first input character, because it usually leads to a "next". + if (flags & ImGuiTypingSelectFlags_AllowSingleCharMode) + { + const char* buf_begin = out_request->SearchBuffer; + const char* buf_end = out_request->SearchBuffer + out_request->SearchBufferLen; + const int c0_len = ImTextCountUtf8BytesFromChar(buf_begin, buf_end); + const char* p = buf_begin + c0_len; + for (; p < buf_end; p += c0_len) + if (memcmp(buf_begin, p, (size_t)c0_len) != 0) + break; + const int single_char_count = (p == buf_end) ? (out_request->SearchBufferLen / c0_len) : 0; + out_request->SingleCharMode = (single_char_count > 0 || data->SingleCharModeLock); + out_request->SingleCharSize = (ImS8)c0_len; + data->SingleCharModeLock |= (single_char_count >= TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK); // From now on we stop search matching to lock to single char mode. + } + + return out_request; +} + +static int ImStrimatchlen(const char* s1, const char* s1_end, const char* s2) +{ + int match_len = 0; + while (s1 < s1_end && ImToUpper(*s1++) == ImToUpper(*s2++)) + match_len++; + return match_len; +} + +// Default handler for finding a result for typing-select. You may implement your own. +// You might want to display a tooltip to visualize the current request SearchBuffer +// When SingleCharMode is set: +// - it is better to NOT display a tooltip of other on-screen display indicator. +// - the index of the currently focused item is required. +// if your SetNextItemSelectionUserData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData. +int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx) +{ + if (req == NULL || req->SelectRequest == false) // Support NULL parameter so both calls can be done from same spot. + return -1; + int idx = -1; + if (req->SingleCharMode && (req->Flags & ImGuiTypingSelectFlags_AllowSingleCharMode)) + idx = TypingSelectFindNextSingleCharMatch(req, items_count, get_item_name_func, user_data, nav_item_idx); + else + idx = TypingSelectFindBestLeadingMatch(req, items_count, get_item_name_func, user_data); + if (idx != -1) + SetNavCursorVisibleAfterMove(); + return idx; +} + +// Special handling when a single character is repeated: perform search on a single letter and goes to next. +int ImGui::TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx) +{ + // FIXME: Assume selection user data is index. Would be extremely practical. + //if (nav_item_idx == -1) + // nav_item_idx = (int)g.NavLastValidSelectionUserData; + + int first_match_idx = -1; + bool return_next_match = false; + for (int idx = 0; idx < items_count; idx++) + { + const char* item_name = get_item_name_func(user_data, idx); + if (ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SingleCharSize, item_name) < req->SingleCharSize) + continue; + if (return_next_match) // Return next matching item after current item. + return idx; + if (first_match_idx == -1 && nav_item_idx == -1) // Return first match immediately if we don't have a nav_item_idx value. + return idx; + if (first_match_idx == -1) // Record first match for wrapping. + first_match_idx = idx; + if (nav_item_idx == idx) // Record that we encountering nav_item so we can return next match. + return_next_match = true; + } + return first_match_idx; // First result +} + +int ImGui::TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data) +{ + int longest_match_idx = -1; + int longest_match_len = 0; + for (int idx = 0; idx < items_count; idx++) + { + const char* item_name = get_item_name_func(user_data, idx); + const int match_len = ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SearchBufferLen, item_name); + if (match_len <= longest_match_len) + continue; + longest_match_idx = idx; + longest_match_len = match_len; + if (match_len == req->SearchBufferLen) + break; + } + return longest_match_idx; +} + +void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + Text("SearchBuffer = \"%s\"", data->SearchBuffer); + Text("SingleCharMode = %d, Size = %d, Lock = %d", data->Request.SingleCharMode, data->Request.SingleCharSize, data->SingleCharModeLock); + Text("LastRequest = time: %.2f, frame: %d", data->LastRequestTime, data->LastRequestFrame); +#else + IM_UNUSED(data); +#endif +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Box-Select support +// This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet. +//------------------------------------------------------------------------- +// Extra logic in MultiSelectItemFooter() and ImGuiListClipper::Step() +//------------------------------------------------------------------------- +// - BoxSelectPreStartDrag() [Internal] +// - BoxSelectActivateDrag() [Internal] +// - BoxSelectDeactivateDrag() [Internal] +// - BoxSelectScrollWithMouseDrag() [Internal] +// - BeginBoxSelect() [Internal] +// - EndBoxSelect() [Internal] +//------------------------------------------------------------------------- + +// Call on the initial click. +static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item) +{ + ImGuiContext& g = *GImGui; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + bs->ID = id; + bs->IsStarting = true; // Consider starting box-select. + bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); + bs->IsStartedSetNavIdOnce = bs->IsStartedFromVoid; + bs->KeyMods = g.IO.KeyMods; + bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); + bs->ScrollAccum = ImVec2(0.0f, 0.0f); +} + +static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Activate\n", bs->ID); + bs->IsActive = true; + bs->Window = window; + bs->IsStarting = false; + ImGui::SetActiveID(bs->ID, window); + ImGui::SetActiveIdUsingAllKeyboardKeys(); + if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) + bs->RequestClear = true; +} + +static void BoxSelectDeactivateDrag(ImGuiBoxSelectState* bs) +{ + ImGuiContext& g = *GImGui; + bs->IsActive = bs->IsStarting = false; + if (g.ActiveId == bs->ID) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Deactivate\n", bs->ID); + ImGui::ClearActiveID(); + } + bs->ID = 0; +} + +static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window, const ImRect& inner_r) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(bs->Window == window); + for (int n = 0; n < 2; n++) // each axis + { + const float mouse_pos = g.IO.MousePos[n]; + const float dist = (mouse_pos > inner_r.Max[n]) ? mouse_pos - inner_r.Max[n] : (mouse_pos < inner_r.Min[n]) ? mouse_pos - inner_r.Min[n] : 0.0f; + const float scroll_curr = window->Scroll[n]; + if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n])) + continue; + + const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance + const float scroll_step = g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime; + bs->ScrollAccum[n] += scroll_step; + + // Accumulate into a stored value so we can handle high-framerate + const float scroll_step_i = ImFloor(bs->ScrollAccum[n]); + if (scroll_step_i == 0.0f) + continue; + if (n == 0) + ImGui::SetScrollX(window, scroll_curr + scroll_step_i); + else + ImGui::SetScrollY(window, scroll_curr + scroll_step_i); + bs->ScrollAccum[n] -= scroll_step_i; + } +} + +bool ImGui::BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + KeepAliveID(box_select_id); + if (bs->ID != box_select_id) + return false; + + // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. + bs->UnclipMode = false; + bs->RequestClear = false; + if (bs->IsStarting && IsMouseDragPastThreshold(0)) + BoxSelectActivateDrag(bs, window); + else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) + BoxSelectDeactivateDrag(bs); + if (!bs->IsActive) + return false; + + // Current frame absolute prev/current rectangles are used to toggle selection. + // They are derived from positions relative to scrolling space. + ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already + ImVec2 curr_end_pos_abs = g.IO.MousePos; + if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow + curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); + bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); + bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); + + // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) + // Storing an extra rect used by widgets supporting box-select. + if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d) + if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) + { + bs->UnclipMode = true; + bs->UnclipRect = bs->BoxSelectRectPrev; // FIXME-OPT: UnclipRect x coordinates could be intersection of Prev and Curr rect on X axis. + bs->UnclipRect.Add(bs->BoxSelectRectCurr); + } + + //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); + //GetForegroundDrawList()->AddRect(bs->BoxSelectRectPrev.Min, bs->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); + //GetForegroundDrawList()->AddRect(bs->BoxSelectRectCurr.Min, bs->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f); + return true; +} + +void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + IM_ASSERT(bs->IsActive); + bs->UnclipMode = false; + + // Render selection rectangle + bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view + ImRect box_select_r = bs->BoxSelectRectCurr; + box_select_r.ClipWith(scope_rect); + window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling + + // Scroll + const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; + if (enable_scroll) + { + ImRect scroll_r = scope_rect; + scroll_r.Expand(-g.FontSize); + //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); + if (!scroll_r.Contains(g.IO.MousePos)) + BoxSelectScrollWithMouseDrag(bs, window, scroll_r); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Multi-Select support +//------------------------------------------------------------------------- +// - DebugLogMultiSelectRequests() [Internal] +// - CalcScopeRect() [Internal] +// - BeginMultiSelect() +// - EndMultiSelect() +// - SetNextItemSelectionUserData() +// - MultiSelectItemHeader() [Internal] +// - MultiSelectItemFooter() [Internal] +// - DebugNodeMultiSelectState() [Internal] +//------------------------------------------------------------------------- + +static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) +{ + ImGuiContext& g = *GImGui; + IM_UNUSED(function); + for (const ImGuiSelectionRequest& req : io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear"); + if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d (dir %d)\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.Selected, req.RangeDirection); + } +} + +static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) + { + // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only + return ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)); + } + else + { + // When a table, pull HostClipRect, which allows us to predict ClipRect before first row/layout is performed. (#7970) + ImRect scope_rect = window->InnerClipRect; + if (g.CurrentTable != NULL) + scope_rect = g.CurrentTable->HostClipRect; + + // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect? + scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max); + return scope_rect; + } +} + +// Return ImGuiMultiSelectIO structure. +// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). +// Passing 'selection_size' and 'items_count' parameters is currently optional. +// - 'selection_size' is useful to disable some shortcut routing: e.g. ImGuiMultiSelectFlags_ClearOnEscape won't claim Escape key when selection_size 0, +// allowing a first press to clear selection THEN the second press to leave child window and return to parent. +// - 'items_count' is stored in ImGuiMultiSelectIO which makes it a convenient way to pass the information to your ApplyRequest() handler (but you may pass it differently). +// - If they are costly for you to compute (e.g. external intrusive selection without maintaining size), you may avoid them and pass -1. +// - If you can easily tell if your selection is empty or not, you may pass 0/1, or you may enable ImGuiMultiSelectFlags_ClearOnEscape flag dynamically. +ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size, int items_count) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (++g.MultiSelectTempDataStacked > g.MultiSelectTempData.Size) + g.MultiSelectTempData.resize(g.MultiSelectTempDataStacked, ImGuiMultiSelectTempData()); + ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1]; + IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that. + g.CurrentMultiSelect = ms; + if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) + flags |= ImGuiMultiSelectFlags_ScopeWindow; + if (flags & ImGuiMultiSelectFlags_SingleSelect) + flags &= ~(ImGuiMultiSelectFlags_BoxSelect2d | ImGuiMultiSelectFlags_BoxSelect1d); + if (flags & ImGuiMultiSelectFlags_BoxSelect2d) + flags &= ~ImGuiMultiSelectFlags_BoxSelect1d; + + // FIXME: Workaround to the fact we override CursorMaxPos, meaning size measurement are lost. (#8250) + // They should perhaps be stacked properly? + if (ImGuiTable* table = g.CurrentTable) + if (table->CurrentColumn != -1) + TableEndCell(table); // This is currently safe to call multiple time. If that properly is lost we can extract the "save measurement" part of it. + + // FIXME: BeginFocusScope() + const ImGuiID id = window->IDStack.back(); + ms->Clear(); + ms->FocusScopeId = id; + ms->Flags = flags; + ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); + ms->BackupCursorMaxPos = window->DC.CursorMaxPos; + ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos; + PushFocusScope(ms->FocusScopeId); + if (flags & ImGuiMultiSelectFlags_ScopeWindow) // Mark parent child window as navigable into, with highlight. Assume user will always submit interactive items. + window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; + + // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. + ms->KeyMods = g.NavJustMovedToId ? (g.NavJustMovedToIsTabbing ? 0 : g.NavJustMovedToKeyMods) : g.IO.KeyMods; + if (flags & ImGuiMultiSelectFlags_NoRangeSelect) + ms->KeyMods &= ~ImGuiMod_Shift; + + // Bind storage + ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id); + storage->ID = id; + storage->LastFrameActive = g.FrameCount; + storage->LastSelectionSize = selection_size; + storage->Window = window; + ms->Storage = storage; + + // Output to user + ms->IO.Requests.resize(0); + ms->IO.RangeSrcItem = storage->RangeSrcItem; + ms->IO.NavIdItem = storage->NavIdItem; + ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; + ms->IO.ItemsCount = items_count; + + // Clear when using Navigation to move within the scope + // (we compare FocusScopeId so it possible to use multiple selections inside a same window) + bool request_clear = false; + bool request_select_all = false; + if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) + { + if (ms->KeyMods & ImGuiMod_Shift) + ms->IsKeyboardSetRange = true; + if (ms->IsKeyboardSetRange) + IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear? + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0) + request_clear = true; + } + else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId) + { + // Also clear on leaving scope (may be optional?) + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0) + request_clear = true; + } + + // Box-select handling: update active state. + ImGuiBoxSelectState* bs = &g.BoxSelectState; + if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) + { + ms->BoxSelectId = GetID("##BoxSelect"); + if (BeginBoxSelect(CalcScopeRect(ms, window), window, ms->BoxSelectId, flags)) + request_clear |= bs->RequestClear; + } + + if (ms->IsFocused) + { + // Shortcut: Clear selection (Escape) + // - Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window. + // - Box select also handle Escape and needs to pass an id to bypass ActiveIdUsingAllKeyboardKeys lock. + if (flags & ImGuiMultiSelectFlags_ClearOnEscape) + { + if (selection_size != 0 || bs->IsActive) + if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_None, bs->IsActive ? bs->ID : 0)) + { + request_clear = true; + if (bs->IsActive) + BoxSelectDeactivateDrag(bs); + } + } + + // Shortcut: Select all (Ctrl+A) + if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) + request_select_all = true; + } + + if (request_clear || request_select_all) + { + MultiSelectAddSetAll(ms, request_select_all); + if (!request_select_all) + storage->LastSelectionSize = 0; + } + ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; + ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid; + + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) + DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO); + + return &ms->IO; +} + +// Return updated ImGuiMultiSelectIO structure. +// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). +ImGuiMultiSelectIO* ImGui::EndMultiSelect() +{ + ImGuiContext& g = *GImGui; + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + ImGuiMultiSelectState* storage = ms->Storage; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR(ms->FocusScopeId == g.CurrentFocusScopeId, "EndMultiSelect() FocusScope mismatch!"); + IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); + IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect); + + ImRect scope_rect = CalcScopeRect(ms, window); + if (ms->IsFocused) + { + // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. + if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at beginning of the scope (see tests for easy failure) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. + storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; + } + if (ms->NavIdPassedBy == false && storage->NavIdItem != ImGuiSelectionUserData_Invalid) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n"); + storage->NavIdItem = ImGuiSelectionUserData_Invalid; + storage->NavIdSelected = -1; + } + + if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId)) + EndBoxSelect(scope_rect, ms->Flags); + } + + if (ms->IsEndIO == false) + ms->IO.Requests.resize(0); + + // Clear selection when clicking void? + // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! + // The InnerRect test is necessary for non-child/decorated windows. + bool scope_hovered = IsWindowHovered() && window->InnerRect.Contains(g.IO.MousePos); + if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)) + scope_hovered &= scope_rect.Contains(g.IO.MousePos); + if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) + { + if (ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) + { + if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) + { + BoxSelectPreStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); + FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal); + SetHoveredID(ms->BoxSelectId); + if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) + SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from void to box-select. + } + } + + if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) + if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) + MultiSelectAddSetAll(ms, false); + } + + // Courtesy nav wrapping helper flag + if (ms->Flags & ImGuiMultiSelectFlags_NavWrapX) + { + IM_ASSERT(ms->Flags & ImGuiMultiSelectFlags_ScopeWindow); // Only supported at window scope + ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); + } + + // Unwind + window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos); + PopFocusScope(); + + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) + DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO); + + ms->FocusScopeId = 0; + ms->Flags = ImGuiMultiSelectFlags_None; + g.CurrentMultiSelect = (--g.MultiSelectTempDataStacked > 0) ? &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] : NULL; + + return &ms->IO; +} + +void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data) +{ + // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code! + // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api. + ImGuiContext& g = *GImGui; + g.NextItemData.SelectionUserData = selection_user_data; + g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; + + if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) + { + // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; + if (ms->IO.RangeSrcItem == selection_user_data) + ms->RangeSrcPassedBy = true; + } + else + { + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; + } +} + +// In charge of: +// - Applying SetAll for submitted items. +// - Applying SetRange for submitted items and record end points. +// - Altering button behavior flags to facilitate use with drag and drop. +void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + + bool selected = *p_selected; + if (ms->IsFocused) + { + ImGuiMultiSelectState* storage = ms->Storage; + ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; + IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); + + // Apply SetAll (Clear/SelectAll) requests requested by BeginMultiSelect(). + // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. + // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect() + if (ms->LoopRequestSetAll != -1) + selected = (ms->LoopRequestSetAll == 1); + + // When using Shift+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) + // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) + if (ms->IsKeyboardSetRange) + { + IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); + const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + if (is_range_dst) + ms->RangeDstPassedBy = true; + if (is_range_dst && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected ? 1 : 0; + } + const bool is_range_src = storage->RangeSrcItem == item_data; + if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) + { + // Apply range-select value to visible items + IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); + selected = (storage->RangeSelected != 0); + } + else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0 && (ms->Flags & ImGuiMultiSelectFlags_NoAutoClear) == 0) + { + // Clear other items + selected = false; + } + } + *p_selected = selected; + } + + // Alter button behavior flags + // To handle drag and drop of multiple items we need to avoid clearing selection on click. + // Enabling this test makes actions using Ctrl+Shift delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. + if (p_button_flags != NULL) + { + ImGuiButtonFlags button_flags = *p_button_flags; + button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + *p_button_flags = button_flags; + } +} + +// In charge of: +// - Auto-select on navigation. +// - Box-select toggle handling. +// - Right-click handling. +// - Altering selection based on Ctrl/Shift modifiers, both for keyboard and mouse. +// - Record current selection state for RangeSrc +// This is all rather complex, best to run and refer to "widgets_multiselect_xxx" tests in imgui_test_suite. +void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + bool selected = *p_selected; + bool pressed = *p_pressed; + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + ImGuiMultiSelectState* storage = ms->Storage; + if (pressed) + ms->IsFocused = true; + + bool hovered = false; + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) + hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (!ms->IsFocused && !hovered) + return; + + ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; + + ImGuiMultiSelectFlags flags = ms->Flags; + const bool is_singleselect = (flags & ImGuiMultiSelectFlags_SingleSelect) != 0; + bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; + bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; + + bool apply_to_range_src = false; + + if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) + apply_to_range_src = true; + if (ms->IsEndIO == false) + { + ms->IO.Requests.resize(0); + ms->IsEndIO = true; + } + + // Auto-select as you navigate a list + if (g.NavJustMovedToId == id) + { + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + { + if (is_ctrl && is_shift) + pressed = true; + else if (!is_ctrl) + selected = pressed = true; + } + else + { + // With NoAutoSelect, using Shift+keyboard performs a write/copy + if (is_shift) + pressed = true; + else if (!is_ctrl) + apply_to_range_src = true; // Since if (pressed) {} main block is not running we update this + } + } + + if (apply_to_range_src) + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected; // Will be updated at the end of this function anyway. + } + + // Box-select toggle handling + if (ms->BoxSelectId != 0) + if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId)) + { + const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); + const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); + if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) + { + if (storage->LastSelectionSize <= 0 && bs->IsStartedSetNavIdOnce) + { + pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overridden anyway) + bs->IsStartedSetNavIdOnce = false; + } + else + { + selected = !selected; + MultiSelectAddSetRange(ms, selected, +1, item_data, item_data); + } + storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1); + } + } + + // Right-click handling. + // FIXME-MULTISELECT: Maybe should be moved to Selectable()? Also see #5816, #8200, #9015 + if (hovered && IsMouseClicked(1) && (flags & (ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoSelectOnRightClick)) == 0) + { + if (g.ActiveId != 0 && g.ActiveId != id) + ClearActiveID(); + SetFocusID(id, window); + if (!pressed && !selected) + { + pressed = true; + is_ctrl = is_shift = false; + } + } + + // Unlike Space, Enter doesn't alter selection (but can still return a press) unless current item is not selected. + // The later, "unless current item is not select", may become optional? It seems like a better default if Enter doesn't necessarily open something + // (unlike e.g. Windows explorer). For use case where Enter always open something, we might decide to make this optional? + const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput); + + // Alter selection + if (pressed && (!enter_pressed || !selected)) + { + // Box-select + ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) + if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) + BoxSelectPreStartDrag(ms->BoxSelectId, item_data); + + //---------------------------------------------------------------------------------------- + // ACTION | Begin | Pressed/Activated | End + //---------------------------------------------------------------------------------------- + // Keys Navigated: | Clear | Src=item, Sel=1 SetRange 1 + // Keys Navigated: Ctrl | n/a | n/a + // Keys Navigated: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1 + // Keys Navigated: Ctrl+Shift | n/a | Dst=item, Sel=Src => Clear + SetRange Src-Dst + // Keys Activated: | n/a | Src=item, Sel=1 => Clear + SetRange 1 + // Keys Activated: Ctrl | n/a | Src=item, Sel=!Sel => SetSange 1 + // Keys Activated: Shift | n/a | Dst=item, Sel=1 => Clear + SetSange 1 + //---------------------------------------------------------------------------------------- + // Mouse Pressed: | n/a | Src=item, Sel=1, => Clear + SetRange 1 + // Mouse Pressed: Ctrl | n/a | Src=item, Sel=!Sel => SetRange 1 + // Mouse Pressed: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1 + // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst + //---------------------------------------------------------------------------------------- + + if ((flags & ImGuiMultiSelectFlags_NoAutoClear) == 0) + { + bool request_clear = false; + if (is_singleselect) + request_clear = true; + else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) + request_clear = (flags & ImGuiMultiSelectFlags_NoAutoClearOnReselect) ? !selected : true; + else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) + request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. + if (request_clear) + MultiSelectAddSetAll(ms, false); + } + + int range_direction; + bool range_selected; + if (is_shift && !is_singleselect) + { + //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); + if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) + storage->RangeSrcItem = item_data; + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + { + // Shift+Arrow always select + // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected) + range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + } + else + { + // Shift+Arrow copy source selection state + // Shift+Click always copy from target selection state + if (ms->IsKeyboardSetRange) + range_selected = (storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + else + range_selected = !selected; + } + range_direction = ms->RangeSrcPassedBy ? +1 : -1; + } + else + { + // Ctrl inverts selection, otherwise always select + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + selected = is_ctrl ? !selected : true; + else + selected = !selected; + storage->RangeSrcItem = item_data; + range_selected = selected; + range_direction = +1; + } + MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data); + } + + // Update/store the selection state of the Source item (used by Ctrl+Shift, when Source is unselected we perform a range unselect) + if (storage->RangeSrcItem == item_data) + storage->RangeSelected = selected ? 1 : 0; + + // Update/store the selection state of focused item + if (g.NavId == id) + { + storage->NavIdItem = item_data; + storage->NavIdSelected = selected ? 1 : 0; + } + if (storage->NavIdItem == item_data) + ms->NavIdPassedBy = true; + ms->LastSubmittedItem = item_data; + + *p_selected = selected; + *p_pressed = pressed; +} + +void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected) +{ + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ms->IO.Requests.resize(0); // Can always clear previous requests + ms->IO.Requests.push_back(req); // Add new request +} + +void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item) +{ + // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges) + if (ms->IO.Requests.Size > 0 && first_item == last_item && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0) + { + ImGuiSelectionRequest* prev = &ms->IO.Requests.Data[ms->IO.Requests.Size - 1]; + if (prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->LastSubmittedItem && prev->Selected == selected) + { + prev->RangeLastItem = last_item; + return; + } + } + + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item }; + ms->IO.Requests.push_back(req); // Add new request +} + +void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here. + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode((void*)(intptr_t)storage->ID, "MultiSelect 0x%08X in '%s'%s", storage->ID, storage->Window ? storage->Window->Name : "N/A", is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (!open) + return; + Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected); + Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected); + Text("LastSelectionSize = %d", storage->LastSelectionSize); // Provided by user + TreePop(); +#else + IM_UNUSED(storage); +#endif +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Multi-Select helpers +//------------------------------------------------------------------------- +// - ImGuiSelectionBasicStorage +// - ImGuiSelectionExternalStorage +//------------------------------------------------------------------------- + +ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage() +{ + Size = 0; + PreserveOrder = false; + UserData = NULL; + AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; + _SelectionOrder = 1; // Always >0 +} + +void ImGuiSelectionBasicStorage::Clear() +{ + Size = 0; + _SelectionOrder = 1; // Always >0 + _Storage.Data.resize(0); +} + +void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r) +{ + ImSwap(Size, r.Size); + ImSwap(_SelectionOrder, r._SelectionOrder); + _Storage.Data.swap(r._Storage.Data); +} + +bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const +{ + return _Storage.GetInt(id, 0) != 0; +} + +static int IMGUI_CDECL PairComparerByValueInt(const void* lhs, const void* rhs) +{ + int lhs_v = ((const ImGuiStoragePair*)lhs)->val_i; + int rhs_v = ((const ImGuiStoragePair*)rhs)->val_i; + return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0); +} + +// GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user. +// (e.g. store unselected vs compact down, compact down on demand, use raw ImVector instead of ImGuiStorage...) +bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id) +{ + ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it; + ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size; + if (PreserveOrder && it == NULL && it_end != NULL) + ImQsort(_Storage.Data.Data, (size_t)_Storage.Data.Size, sizeof(ImGuiStoragePair), PairComparerByValueInt); // ~ImGuiStorage::BuildSortByValueInt() + if (it == NULL) + it = _Storage.Data.Data; + IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); + if (it != it_end) + while (it->val_i == 0 && it < it_end) + it++; + const bool has_more = (it != it_end); + *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); + *out_id = has_more ? it->key : 0; + if (PreserveOrder && !has_more) + _Storage.BuildSortByKey(); + return has_more; +} + +void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) +{ + int* p_int = _Storage.GetIntRef(id, 0); + if (selected && *p_int == 0) { *p_int = _SelectionOrder++; Size++; } + else if (!selected && *p_int != 0) { *p_int = 0; Size--; } +} + +// Optimized for batch edits (with same value of 'selected') +static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends, int selection_order) +{ + ImGuiStorage* storage = &selection->_Storage; + ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); + const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id); + if (selected == (is_contained && it->val_i != 0)) + return; + if (selected && !is_contained) + storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() + else if (is_contained) + it->val_i = selected ? selection_order : 0; // Modify in-place. + selection->Size += selected ? +1 : -1; +} + +static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends) +{ + ImGuiStorage* storage = &selection->_Storage; + if (selected && selection->Size != size_before_amends) + storage->BuildSortByKey(); // When done selecting: sort everything +} + +// Apply requests coming from BeginMultiSelect() and EndMultiSelect(). +// - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. +// - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. +// - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. +// - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform +// a lookup in order to have some way to iterate/interpolate between two items. +// - A full-featured application is likely to allow search/filtering which is likely to lead to using indices +// and constructing a view index <> object id/ptr data structure anyway. +// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ImGuiSelectionBasicStorage' INDIRECTION LOGIC. +// Notice that with the simplest adapter (using indices everywhere), all functions return their parameters. +// The most simple implementation (using indices everywhere) would look like: +// for (ImGuiSelectionRequest& req : ms_io->Requests) +// { +// if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { SetItemSelected(n, true); } } +// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { SetItemSelected(n, ms_io->Selected); } } +// } +void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) +{ + // For convenience we obtain ItemsCount as passed to BeginMultiSelect(), which is optional. + // It makes sense when using ImGuiSelectionBasicStorage to simply pass your items count to BeginMultiSelect(). + // Other scheme may handle SetAll differently. + IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!"); + IM_ASSERT(AdapterIndexToStorageId != NULL); + + // This is optimized/specialized to cope with very large selections (e.g. 100k+ items) + // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish(). + // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass. + // - A more optimal version wouldn't even use ImGuiStorage but directly a ImVector to reduce bandwidth, but this is a reasonable trade off to reuse code. + // - There are many ways this could be better optimized. The worse case scenario being: using BoxSelect2d in a grid, box-select scrolling down while wiggling + // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each. + // FIXME-OPT: For each block of consecutive SetRange request: + // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage. + // - rewrite sorted storage a single time. + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + { + Clear(); + if (req.Selected) + { + _Storage.Data.reserve(ms_io->ItemsCount); + const int size_before_amends = _Storage.Data.Size; + for (int idx = 0; idx < ms_io->ItemsCount; idx++, _SelectionOrder++) + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, _SelectionOrder); + ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); + } + } + else if (req.Type == ImGuiSelectionRequestType_SetRange) + { + const int selection_changes = (int)req.RangeLastItem - (int)req.RangeFirstItem + 1; + //ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_SELECTION("Req %d/%d: set %d to %d\n", ms_io->Requests.index_from_ptr(&req), ms_io->Requests.Size, selection_changes, req.Selected); + if (selection_changes == 1 || (selection_changes < Size / 100)) + { + // Multiple sorted insertion + copy likely to be faster. + // Technically we could do a single copy with a little more work (sort sequential SetRange requests) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + SetItemSelected(GetStorageIdFromIndex(idx), req.Selected); + } + else + { + // Append insertion + single sort likely be faster. + // Use req.RangeDirection to set order field so that Shift+Clicking from 1 to 5 is different than Shift+Clicking from 5 to 1 + const int size_before_amends = _Storage.Data.Size; + int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0); + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection) + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order); + if (req.Selected) + _SelectionOrder += selection_changes; + ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); + } + } + } +} + +//------------------------------------------------------------------------- + +ImGuiSelectionExternalStorage::ImGuiSelectionExternalStorage() +{ + UserData = NULL; + AdapterSetItemSelected = NULL; +} + +// Apply requests coming from BeginMultiSelect() and EndMultiSelect(). +// We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage +// This makes no assumption about underlying storage. +void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) +{ + IM_ASSERT(AdapterSetItemSelected); + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + for (int idx = 0; idx < ms_io->ItemsCount; idx++) + AdapterSetItemSelected(this, idx, req.Selected); + if (req.Type == ImGuiSelectionRequestType_SetRange) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + AdapterSetItemSelected(this, idx, req.Selected); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ListBox +//------------------------------------------------------------------------- +// - BeginListBox() +// - EndListBox() +// - ListBox() +//------------------------------------------------------------------------- + +// This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. +// This handle some subtleties with capturing info from the label. +// If you don't need a label you can pretty much directly use ImGui::BeginChild() with ImGuiChildFlags_FrameStyle. +// Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty" +// Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.5f * item_height). +bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Size default to hold ~7.25 items. + // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + ImVec2 size = ImTrunc(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f)); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + g.NextItemData.ClearFlags(); + + if (!IsRectVisible(bb.Min, bb.Max)) + { + ItemSize(bb.GetSize(), style.FramePadding.y); + ItemAdd(bb, 0, &frame_bb); + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + // FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well. + BeginGroup(); + if (label_size.x > 0.0f) + { + ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y); + RenderText(label_pos, label); + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size); + AlignTextToFramePadding(); + } + + BeginChild(id, frame_bb.GetSize(), ImGuiChildFlags_FrameStyle); + return true; +} + +void ImGui::EndListBox() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?"); + IM_UNUSED(window); + + EndChild(); + EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label +} + +bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) +{ + const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); + return value_changed; +} + +// This is merely a helper around BeginListBox(), EndListBox(). +// Considering using those directly to submit custom data or store selection differently. +bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items) +{ + ImGuiContext& g = *GImGui; + + // Calculate size from "height_in_items" + if (height_in_items < 0) + height_in_items = ImMin(items_count, 7); + float height_in_items_f = height_in_items + 0.25f; + ImVec2 size(0.0f, ImTrunc(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f)); + + if (!BeginListBox(label, size)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different height, + // you can create a custom version of ListBox() in your code without using the clipper. + bool value_changed = false; + ImGuiListClipper clipper; + clipper.Begin(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. + clipper.IncludeItemByIndex(*current_item); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const char* item_text = getter(user_data, i); + if (item_text == NULL) + item_text = "*Unknown item*"; + + PushID(i); + const bool item_selected = (i == *current_item); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + EndListBox(); + + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: PlotLines, PlotHistogram +//------------------------------------------------------------------------- +// - PlotEx() [Internal] +// - PlotLines() +// - PlotHistogram() +//------------------------------------------------------------------------- +// Plot/Graph widgets are not very good. +// Consider writing your own, or using a third-party one, see: +// - ImPlot https://github.com/epezent/implot +// - others https://github.com/ocornut/imgui/wiki/Useful-Extensions +//------------------------------------------------------------------------- + +int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, const ImVec2& size_arg) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return -1; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav)) + return -1; + bool hovered; + ButtonBehavior(frame_bb, id, &hovered, NULL); + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + if (v != v) // Ignore NaN values + continue; + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; + int idx_hovered = -1; + if (values_count >= values_count_min) + { + int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + + // Tooltip on hover + if (hovered && inner_bb.Contains(g.IO.MousePos)) + { + const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * item_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + SetTooltip("%d: %8.4g", v_idx, v0); + idx_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle + float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (1 + scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands + + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); + if (plot_type == ImGuiPlotType_Lines) + { + window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); + } + else if (plot_type == ImGuiPlotType_Histogram) + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); + } + + t0 = t1; + tp0 = tp1; + } + } + + // Text overlay + if (overlay_text) + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + + // Return hovered index or -1 if none are hovered. + // This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). + return idx_hovered; +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + int Stride; + + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Value helpers +// Those is not very useful, legacy API. +//------------------------------------------------------------------------- +// - Value() +//------------------------------------------------------------------------- + +void ImGui::Value(const char* prefix, bool b) +{ + Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + ImFormatString(fmt, IM_COUNTOF(fmt), "%%s: %s", float_format); + Text(fmt, prefix, v); + } + else + { + Text("%s: %.3f", prefix, v); + } +} + +//------------------------------------------------------------------------- +// [SECTION] MenuItem, BeginMenu, EndMenu, etc. +//------------------------------------------------------------------------- +// - ImGuiMenuColumns [Internal] +// - BeginMenuBar() +// - EndMenuBar() +// - BeginMainMenuBar() +// - EndMainMenuBar() +// - BeginMenu() +// - EndMenu() +// - MenuItemEx() [Internal] +// - MenuItem() +//------------------------------------------------------------------------- + +// Helpers for internal use +void ImGuiMenuColumns::Update(float spacing, bool window_reappearing) +{ + if (window_reappearing) + memset(Widths, 0, sizeof(Widths)); + Spacing = (ImU16)spacing; + CalcNextTotalWidth(true); + memset(Widths, 0, sizeof(Widths)); + TotalWidth = NextTotalWidth; + NextTotalWidth = 0; +} + +void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets) +{ + ImU16 offset = 0; + bool want_spacing = false; + for (int i = 0; i < IM_COUNTOF(Widths); i++) + { + ImU16 width = Widths[i]; + if (want_spacing && width > 0) + offset += Spacing; + want_spacing |= (width > 0); + if (update_offsets) + { + if (i == 1) { OffsetLabel = offset; } + if (i == 2) { OffsetShortcut = offset; } + if (i == 3) { OffsetMark = offset; } + } + offset += width; + } + NextTotalWidth = offset; +} + +float ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark) +{ + Widths[0] = ImMax(Widths[0], (ImU16)w_icon); + Widths[1] = ImMax(Widths[1], (ImU16)w_label); + Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut); + Widths[3] = ImMax(Widths[3], (ImU16)w_mark); + CalcNextTotalWidth(false); + return (float)ImMax(TotalWidth, NextTotalWidth); +} + +// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere.. +// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer. +// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary. +// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars. +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore + PushID("##MenuBar"); + + // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. + // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. + const float border_top = ImMax(IM_ROUND(window->WindowBorderSize * 0.5f - window->TitleBarHeight), 0.0f); + const float border_half = IM_ROUND(window->WindowBorderSize * 0.5f); + ImRect bar_rect = window->MenuBarRect(); + ImRect clip_rect(ImFloor(bar_rect.Min.x + border_half), ImFloor(bar_rect.Min.y + border_top), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, border_half))), ImFloor(bar_rect.Max.y)); + clip_rect.ClipWith(window->OuterRectClipped); + PushClipRect(clip_rect.Min, clip_rect.Max, false); + + // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags). + window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.IsSameLine = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + window->DC.MenuBarAppending = true; + AlignTextToFramePadding(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + + // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. + if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + { + // Try to find out if the request is for one of our child menu + ImGuiWindow* nav_earliest_child = g.NavWindow; + while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) + nav_earliest_child = nav_earliest_child->ParentWindow; + if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0) + { + // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering) + const ImGuiNavLayer layer = ImGuiNavLayer_Menu; + IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary) + FocusWindow(window); + SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]); + // FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto? + if (g.NavCursorVisible) + { + g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again + g.NavCursorHideFrames = 2; + } + g.NavHighlightItemUnderNav = g.NavMousePosDirty = true; + NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat + } + } + else + { + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_WrapX); + } + + PopClipRect(); + PopID(); + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. + + // FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here. + ImGuiGroupData& group_data = g.GroupStack.back(); + group_data.EmitItem = false; + ImVec2 restore_cursor_max_pos = group_data.BackupCursorMaxPos; + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, window->DC.CursorMaxPos.x - window->Scroll.x); // Convert ideal extents for scrolling layer equivalent. + EndGroup(); // Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.IsSameLine = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.MenuBarAppending = false; + window->DC.CursorMaxPos = restore_cursor_max_pos; +} + +// Important: calling order matters! +// FIXME: Somehow overlapping with docking tech. +// FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) +bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags) +{ + IM_ASSERT(dir != ImGuiDir_None); + + ImGuiWindow* bar_window = FindWindowByName(name); + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport()); + if (bar_window == NULL || bar_window->BeginCount == 0) + { + // Calculate and set window size/position + ImRect avail_rect = viewport->GetBuildWorkRect(); + ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + ImVec2 pos = avail_rect.Min; + if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) + pos[axis] = avail_rect.Max[axis] - axis_size; + ImVec2 size = avail_rect.GetSize(); + size[axis] = axis_size; + SetNextWindowPos(pos); + SetNextWindowSize(size); + + // Report our size into work area (for next frame) using actual window size + if (dir == ImGuiDir_Up || dir == ImGuiDir_Left) + viewport->BuildWorkInsetMin[axis] += axis_size; + else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right) + viewport->BuildWorkInsetMax[axis] += axis_size; + } + + window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; + SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set. + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint + bool is_open = Begin(name, NULL, window_flags); + PopStyleVar(2); + + return is_open; +} + +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport(); + + // Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change + SetCurrentViewport(NULL, viewport); + + // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea? + // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f)); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; + float height = GetFrameHeight(); + bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags); + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); + if (!is_open) + { + End(); + return false; + } + + // Temporarily disable _NoSavedSettings, in the off-chance that tables or child windows submitted within the menu-bar may want to use settings. (#8356) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings; + BeginMenuBar(); + return is_open; +} + +void ImGui::EndMainMenuBar() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT_USER_ERROR_RET(g.CurrentWindow->DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar + + EndMenuBar(); + g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356) + + // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window + // FIXME: With this strategy we won't be able to restore a NULL focus. + if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0) + FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild); + + End(); +} + +static bool IsRootOfOpenMenuSet() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu)) + return false; + + // Initially we used 'upper_popup->OpenParentId == window->IDStack.back()' to differentiate multiple menu sets from each others + // (e.g. inside menu bar vs loose menu items) based on parent ID. + // This would however prevent the use of e.g. PushID() user code submitting menus. + // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag, + // making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects. + // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup + // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu. + // In the end, lack of ID check made it so we could no longer differentiate between separate menu sets. To compensate for that, we at least check parent window nav layer. + // This fixes the most common case of menu opening on hover when moving between window content and menu bar. Multiple different menu sets in same nav layer would still + // open on hover, but that should be a lesser problem, because if such menus are close in proximity in window content then it won't feel weird and if they are far apart + // it likely won't be a problem anyone runs into. + const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size]; + if (window->DC.NavLayerCurrent != upper_popup->ParentNavLayer) + return false; + return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true, false); +} + +bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None); + + // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + // The first menu in a hierarchy isn't so hovering doesn't get across (otherwise e.g. resizing borders with ImGuiButtonFlags_FlattenChildren would react), but top-most BeginMenu() will bypass that limitation. + ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; + if (window->Flags & ImGuiWindowFlags_ChildMenu) + window_flags |= ImGuiWindowFlags_ChildWindow; + + // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). + // We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. + // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. + if (g.MenusIdSubmittedThisFrame.contains(id)) + { + if (menu_is_open) + menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + else + g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values + return menu_is_open; + } + + // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu + g.MenusIdSubmittedThisFrame.push_back(id); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) + // This is only done for items for the menu set and not the full parent window. + const bool menuset_is_open = IsRootOfOpenMenuSet(); + if (menuset_is_open) + PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true); + + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). + // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. + ImVec2 popup_pos; + ImVec2 pos = window->DC.CursorPos; + PushID(label); + if (!enabled) + BeginDisabled(); + const ImGuiMenuColumns* offsets = &window->DC.MenuColumns; + bool pressed; + + // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another. + const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Menu inside a horizontal menu bar + // Selectable extend their highlight by half ItemSpacing in each direction. + // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() + window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f); + PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f); + float w = label_size.x; + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, pos.y + window->DC.CurrLineTextBaseOffset); + pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y)); + LogSetNextTextDecoration("[", "]"); + RenderText(text_pos, label); + PopStyleVar(); + window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), text_pos.y - style.FramePadding.y + window->MenuBarHeight); + } + else + { + // Menu inside a regular/vertical menu + // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. + // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.) + float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; + float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); + float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); + ImVec2 text_pos(window->DC.CursorPos.x, pos.y + window->DC.CurrLineTextBaseOffset); + pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); + LogSetNextTextDecoration("", ">"); + RenderText(ImVec2(text_pos.x + offsets->OffsetLabel, text_pos.y), label); + if (icon_w > 0.0f) + RenderText(ImVec2(text_pos.x + offsets->OffsetIcon, text_pos.y), icon); + RenderArrow(window->DrawList, ImVec2(text_pos.x + offsets->OffsetMark + extra_w + g.FontSize * 0.30f, text_pos.y), GetColorU32(ImGuiCol_Text), ImGuiDir_Right); + popup_pos = ImVec2(pos.x, text_pos.y - style.WindowPadding.y); + } + if (!enabled) + EndDisabled(); + + const bool hovered = (g.HoveredId == id) && enabled && !g.NavHighlightItemUnderNav; + if (menuset_is_open) + PopItemFlag(); + + bool want_open = false; + bool want_open_nav_init = false; + bool want_close = false; + if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_toward_child_menu = false; + ImGuiPopupData* child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) ? &g.OpenPopupStack[g.BeginPopupStack.Size] : NULL; // Popup candidate (testing below) + ImGuiWindow* child_menu_window = (child_popup && child_popup->Window && child_popup->Window->ParentWindow == window) ? child_popup->Window : NULL; + if (g.HoveredWindow == window && child_menu_window != NULL) + { + const float ref_unit = g.FontSize; // FIXME-DPI + const float child_dir = (window->Pos.x < child_menu_window->Pos.x) ? 1.0f : -1.0f; + const ImRect next_window_rect = child_menu_window->Rect(); + ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta); + ImVec2 tb = (child_dir > 0.0f) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (child_dir > 0.0f) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + const float pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, ref_unit * 0.5f, ref_unit * 2.5f); // Add a bit of extra slack. + ta.x += child_dir * -0.5f; + tb.x += child_dir * ref_unit; + tc.x += child_dir * ref_unit; + tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0f); // Triangle has maximum height to limit the slope and the bias toward large sub-menus + tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, +ref_unit * 8.0f); + moving_toward_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); + //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG] + } + + // The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not) + // But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon. + // (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.) + if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavHighlightItemUnderNav && g.ActiveId == 0) + want_close = true; + + // Open + // (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test) + if (!menu_is_open && pressed) // Click/activate to open + want_open = true; + else if (!menu_is_open && hovered && !moving_toward_child_menu) // Hover to open + want_open = true; + else if (!menu_is_open && hovered && g.HoveredIdTimer >= 0.30f && g.MouseStationaryTimer >= 0.30f) // Hover to open (timer fallback) + want_open = true; + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open + { + want_open = want_open_nav_init = true; + NavMoveRequestCancel(); + SetNavCursorVisibleAfterMove(); + } + } + else + { + // Menu bar + if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others + { + want_open = true; + } + else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open + { + want_open = true; + NavMoveRequestCancel(); + } + } + + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None)) + ClosePopupToLevel(g.BeginPopupStack.Size, true); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0)); + PopID(); + + if (want_open && !menu_is_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size) + { + // Don't reopen/recycle same menu level in the same frame if it is a different menu ID, first close the other menu and yield for a frame. + OpenPopup(label); + } + else if (want_open) + { + menu_is_open = true; + OpenPopup(label, ImGuiPopupFlags_NoReopen);// | (want_open_nav_init ? ImGuiPopupFlags_NoReopenAlwaysNavInit : 0)); + } + + if (menu_is_open) + { + ImGuiLastItemData last_item_in_parent = g.LastItemData; + SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos. + PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding + menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display) + PopStyleVar(); + if (menu_is_open) + { + // Implement what ImGuiPopupFlags_NoReopenAlwaysNavInit would do: + // Perform an init request in the case the popup was already open (via a previous mouse hover) + if (want_open && want_open_nav_init && !g.NavInitRequest) + { + FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags_UnlessBelowModal); + NavInitWindow(g.CurrentWindow, false); + } + + // Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu() + // (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags_NoWindowHoverableCheck) + g.LastItemData = last_item_in_parent; + if (g.HoveredWindow == window) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + } + } + else + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + } + + return menu_is_open; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + return BeginMenuEx(label, NULL, enabled); +} + +void ImGui::EndMenu() +{ + // Nav: When a left move request our menu failed, close ourselves. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR_RET((window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu), "Calling EndMenu() in wrong window!"); + + ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert. + if (window->BeginCount == window->BeginCountPreviousFrame) + if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet()) + if (g.NavWindow && (g.NavWindow->RootWindowForNav == window) && parent_window->DC.LayoutType == ImGuiLayoutType_Vertical) + { + ClosePopupToLevel(g.BeginPopupStack.Size - 1, true); + NavMoveRequestCancel(); + } + + EndPopup(); +} + +bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + + // See BeginMenuEx() for comments about this. + const bool menuset_is_open = IsRootOfOpenMenuSet(); + if (menuset_is_open) + PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true); + + // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. + bool pressed; + PushID(label); + if (!enabled) + BeginDisabled(); + + // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another. + const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SetNavIdOnHover; + const ImGuiMenuColumns* offsets = &window->DC.MenuColumns; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark. + float w = label_size.x; + window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f); + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f); + pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f)); + PopStyleVar(); + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) + RenderText(text_pos, label); + window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + } + else + { + // Menu item inside a vertical menu + // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. + // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.) + float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; + float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f; + float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); + float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame + float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); + ImVec2 text_pos(pos.x, pos.y + window->DC.CurrLineTextBaseOffset); + pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) + { + RenderText(text_pos + ImVec2(offsets->OffsetLabel, 0.0f), label); + if (icon_w > 0.0f) + RenderText(text_pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); + if (shortcut_w > 0.0f) + { + PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); + LogSetNextTextDecoration("(", ")"); + RenderText(text_pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + if (selected) + RenderCheckMark(window->DrawList, text_pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f); + } + } + IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0)); + if (!enabled) + EndDisabled(); + PopID(); + if (menuset_is_open) + PopItemFlag(); + + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + return MenuItemEx(label, NULL, shortcut, selected, enabled); +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +//------------------------------------------------------------------------- +// - BeginTabBar() +// - BeginTabBarEx() [Internal] +// - EndTabBar() +// - TabBarLayout() [Internal] +// - TabBarCalcTabID() [Internal] +// - TabBarCalcMaxTabWidth() [Internal] +// - TabBarFindTabById() [Internal] +// - TabBarFindTabByOrder() [Internal] +// - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal] +// - TabBarGetCurrentTab() [Internal] +// - TabBarGetTabName() [Internal] +// - TabBarAddTab() [Internal] +// - TabBarRemoveTab() [Internal] +// - TabBarCloseTab() [Internal] +// - TabBarScrollClamp() [Internal] +// - TabBarScrollToTab() [Internal] +// - TabBarQueueFocus() [Internal] +// - TabBarQueueReorder() [Internal] +// - TabBarProcessReorderFromMousePos() [Internal] +// - TabBarProcessReorder() [Internal] +// - TabBarScrollingButtons() [Internal] +// - TabBarTabListPopupButton() [Internal] +//------------------------------------------------------------------------- + +struct ImGuiTabBarSection +{ + int TabCount; // Number of tabs in this section. + float Width; // Sum of width of tabs in this section (after shrinking down) + float WidthAfterShrinkMinWidth; + float Spacing; // Horizontal spacing at the end of the section. + + ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); } +}; + +namespace ImGui +{ + static void TabBarLayout(ImGuiTabBar* tab_bar); + static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window); + static float TabBarCalcMaxTabWidth(); + static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); + static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections); + static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar); + static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar); +} + +ImGuiTabBar::ImGuiTabBar() +{ + memset(this, 0, sizeof(*this)); + CurrFrameVisible = PrevFrameVisible = -1; + LastTabItemIdx = -1; +} + +static inline int TabItemGetSectionIdx(const ImGuiTabItem* tab) +{ + return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; +} + +static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) +{ + const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; + const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; + const int a_section = TabItemGetSectionIdx(a); + const int b_section = TabItemGetSectionIdx(b); + if (a_section != b_section) + return a_section - b_section; + return (int)(a->IndexDuringLayout - b->IndexDuringLayout); +} + +static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs) +{ + const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; + const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; + return (int)(a->BeginOrder - b->BeginOrder); +} + +static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref) +{ + ImGuiContext& g = *GImGui; + return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index); +} + +static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + if (g.TabBars.Contains(tab_bar)) + return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar)); + return ImGuiPtrOrIndex(tab_bar); +} + +ImGuiTabBar* ImGui::TabBarFindByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.TabBars.GetByKey(id); +} + +// Remove TabBar data (currently only used by TestEngine) +void ImGui::TabBarRemove(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + g.TabBars.Remove(tab_bar->ID, tab_bar); +} + +bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiID id = window->GetID(str_id); + ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); + ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); + tab_bar->ID = id; + tab_bar->SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f); + tab_bar->SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f); + //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false)) + flags |= ImGuiTabBarFlags_IsFocused; + return BeginTabBarEx(tab_bar, tab_bar_bb, flags); +} + +bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + IM_ASSERT(tab_bar->ID != 0); + if ((flags & ImGuiTabBarFlags_DockNode) == 0) // Already done + PushOverrideID(tab_bar->ID); + + // Add to stack + g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); + g.CurrentTabBar = tab_bar; + tab_bar->Window = window; + + // Append with multiple BeginTabBar()/EndTabBar() pairs. + tab_bar->BackupCursorPos = window->DC.CursorPos; + if (tab_bar->CurrFrameVisible == g.FrameCount) + { + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); + tab_bar->BeginCount++; + return true; + } + + // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable + if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable))) + if ((flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + tab_bar->TabsAddedNew = false; + + // Flags + if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + + tab_bar->Flags = flags; + tab_bar->BarRect = tab_bar_bb; + tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() + tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; + tab_bar->CurrFrameVisible = g.FrameCount; + tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight; + tab_bar->CurrTabsContentsHeight = 0.0f; + tab_bar->ItemSpacingY = g.Style.ItemSpacing.y; + tab_bar->FramePadding = g.Style.FramePadding; + tab_bar->TabsActiveCount = 0; + tab_bar->LastTabItemIdx = -1; + tab_bar->BeginCount = 1; + + // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); + + // Draw separator + // (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable) + const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected); + if (g.Style.TabBarBorderSize > 0.0f) + { + const float y = tab_bar->BarRect.Max.y; + window->DrawList->AddRectFilled(ImVec2(tab_bar->SeparatorMinX, y - g.Style.TabBarBorderSize), ImVec2(tab_bar->SeparatorMaxX, y), col); + } + return true; +} + +void ImGui::EndTabBar() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); + + // Fallback in case no TabItem have been submitted + if (tab_bar->WantLayout) + TabBarLayout(tab_bar); + + // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) + { + tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; + } + else + { + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight; + } + if (tab_bar->BeginCount > 1) + window->DC.CursorPos = tab_bar->BackupCursorPos; + + tab_bar->LastTabItemIdx = -1; + if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) // Already done + PopID(); + + g.CurrentTabBarStack.pop_back(); + g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back()); +} + +// Scrolling happens only in the central section (leading/trailing sections are not scrolling) +static float TabBarCalcScrollableWidth(ImGuiTabBar* tab_bar, ImGuiTabBarSection* sections) +{ + return tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing; +} + +// This is called only once a frame before by the first call to ItemTab() +// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. +static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + tab_bar->WantLayout = false; + + // Track selected tab when resizing our parent down + const bool scroll_to_selected_tab = (tab_bar->BarRectPrevWidth > tab_bar->BarRect.GetWidth()); + tab_bar->BarRectPrevWidth = tab_bar->BarRect.GetWidth(); + + // Garbage collect by compacting list + // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section) + int tab_dst_n = 0; + bool need_sort_by_section = false; + ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing + for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; + if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) + { + // Remove tab + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } + continue; + } + if (tab_dst_n != tab_src_n) + tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; + + tab = &tab_bar->Tabs[tab_dst_n]; + tab->IndexDuringLayout = (ImS16)tab_dst_n; + + // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) + int curr_tab_section_n = TabItemGetSectionIdx(tab); + if (tab_dst_n > 0) + { + ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; + int prev_tab_section_n = TabItemGetSectionIdx(prev_tab); + if (curr_tab_section_n == 0 && prev_tab_section_n != 0) + need_sort_by_section = true; + if (prev_tab_section_n == 2 && curr_tab_section_n != 2) + need_sort_by_section = true; + } + + sections[curr_tab_section_n].TabCount++; + tab_dst_n++; + } + if (tab_bar->Tabs.Size != tab_dst_n) + tab_bar->Tabs.resize(tab_dst_n); + + if (need_sort_by_section) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection); + + // Calculate spacing between sections + const float tab_spacing = g.Style.ItemInnerSpacing.x; + sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? tab_spacing : 0.0f; + sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? tab_spacing : 0.0f; + + // Setup next selected tab + ImGuiID scroll_to_tab_id = 0; + if (tab_bar->NextScrollToTabId) + { + scroll_to_tab_id = tab_bar->NextScrollToTabId; + tab_bar->NextScrollToTabId = 0; + } + if (tab_bar->NextSelectedTabId) + { + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId; + tab_bar->NextSelectedTabId = 0; + scroll_to_tab_id = tab_bar->SelectedTabId; + } + + // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). + if (tab_bar->ReorderRequestTabId != 0) + { + if (TabBarProcessReorder(tab_bar)) + if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId) + scroll_to_tab_id = tab_bar->ReorderRequestTabId; + tab_bar->ReorderRequestTabId = 0; + } + + // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) + const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; + if (tab_list_popup_button) + if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! + scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + + // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + // (whereas our tabs are stored as: leading, central, trailing) + int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount }; + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + + // Minimum shrink width + const float shrink_min_width = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed) ? g.Style.TabMinWidthShrink : 1.0f; + + // Compute ideal tabs widths + store them into shrink buffer + ImGuiTabItem* most_recently_selected_tab = NULL; + int curr_section_n = -1; + bool found_selected_tab_id = false; + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible); + + if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button)) + most_recently_selected_tab = tab; + if (tab->ID == tab_bar->SelectedTabId) + found_selected_tab_id = true; + if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID) + scroll_to_tab_id = tab->ID; + + // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. + // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, + // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. + const char* tab_name = TabBarGetTabName(tab_bar, tab); + const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument); + tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x; + if ((tab->Flags & ImGuiTabItemFlags_Button) == 0) + tab->ContentWidth = ImMax(tab->ContentWidth, g.Style.TabMinWidthBase); + + int section_n = TabItemGetSectionIdx(tab); + ImGuiTabBarSection* section = §ions[section_n]; + section->Width += tab->ContentWidth + (section_n == curr_section_n ? tab_spacing : 0.0f); + section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? tab_spacing : 0.0f); + curr_section_n = section_n; + + // Store data so we can build an array sorted by width if we need to shrink tabs down + IM_MSVC_WARNING_SUPPRESS(6385); + ImGuiShrinkWidthItem* shrink_width_item = &g.ShrinkWidthBuffer[shrink_buffer_indexes[section_n]++]; + shrink_width_item->Index = tab_n; + shrink_width_item->Width = shrink_width_item->InitialWidth = tab->ContentWidth; + tab->Width = ImMax(tab->ContentWidth, 1.0f); + } + + // Compute total ideal width (used for e.g. auto-resizing a window) + float width_all_tabs_after_min_width_shrink = 0.0f; + tab_bar->WidthAllTabsIdeal = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + { + tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; + width_all_tabs_after_min_width_shrink += sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing; + } + + // Horizontal scrolling buttons + // Important: note that TabBarScrollButtons() will alter BarRect.Max.x. + const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed); + const float width_all_tabs_to_use_for_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) ? tab_bar->WidthAllTabs : width_all_tabs_after_min_width_shrink; + tab_bar->ScrollButtonEnabled = ((width_all_tabs_to_use_for_scroll > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll); + if (tab_bar->ScrollButtonEnabled) + if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar)) + { + scroll_to_tab_id = scroll_and_select_tab->ID; + if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0) + tab_bar->SelectedTabId = scroll_to_tab_id; + } + if (scroll_to_tab_id == 0 && scroll_to_selected_tab) + scroll_to_tab_id = tab_bar->SelectedTabId; + + // Shrink widths if full tabs don't fit in their allocated space + float section_0_w = sections[0].Width + sections[0].Spacing; + float section_1_w = sections[1].Width + sections[1].Spacing; + float section_2_w = sections[2].Width + sections[2].Spacing; + bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth(); + float width_excess; + if (central_section_is_visible) + width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section + else + width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section + + // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore + const bool can_shrink = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed); + if (width_excess >= 1.0f && (can_shrink || !central_section_is_visible)) + { + int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); + int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0); + ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess, shrink_min_width); + + // Apply shrunk values into tabs and sections + for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; + float shrinked_width = IM_TRUNC(g.ShrinkWidthBuffer[tab_n].Width); + if (shrinked_width < 0.0f) + continue; + + shrinked_width = ImMax(1.0f, shrinked_width); + int section_n = TabItemGetSectionIdx(tab); + sections[section_n].Width -= (tab->Width - shrinked_width); + tab->Width = shrinked_width; + } + } + + // Layout all active tabs + int section_tab_index = 0; + float tab_offset = 0.0f; + tab_bar->WidthAllTabs = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + { + ImGuiTabBarSection* section = §ions[section_n]; + if (section_n == 2) + tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset); + + for (int tab_n = 0; tab_n < section->TabCount; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n]; + tab->Offset = tab_offset; + tab->NameOffset = -1; + tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); + } + tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f); + tab_offset += section->Spacing; + section_tab_index += section->TabCount; + } + + // Clear name buffers + tab_bar->TabsNames.Buf.resize(0); + + // If we have lost the selected tab, select the next most recently active one + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + if (found_selected_tab_id == false && !tab_bar_appearing) + tab_bar->SelectedTabId = 0; + if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL) + scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; + + // Lock in visible tab + tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabWasSubmitted = false; + + // CTRL+TAB can override visible tab temporarily + if (g.NavWindowingTarget != NULL && g.NavWindowingTarget->DockNode && g.NavWindowingTarget->DockNode->TabBar == tab_bar) + tab_bar->VisibleTabId = scroll_to_tab_id = g.NavWindowingTarget->TabId; + + // Apply request requests + if (scroll_to_tab_id != 0) + TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections); + else if (tab_bar->ScrollButtonEnabled && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow)) + { + const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH; + const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX; + if (TestKeyOwner(wheel_key, tab_bar->ID) && wheel != 0.0f) + { + const float scroll_step = wheel * TabBarCalcScrollableWidth(tab_bar, sections) / 3.0f; + tab_bar->ScrollingTargetDistToVisibility = 0.0f; + tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget - scroll_step); + } + SetKeyOwner(wheel_key, tab_bar->ID); + } + + // Update scrolling + tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim); + tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget); + if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) + { + // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + // Teleport if we are aiming far off the visible line + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize); + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f); + const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize); + tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed); + } + else + { + tab_bar->ScrollingSpeed = 0.0f; + } + tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing; + tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing; + + // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) + ImGuiWindow* window = g.CurrentWindow; + window->DC.CursorPos = tab_bar->BarRect.Min; + ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal); +} + +// Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. +static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window) +{ + if (docked_window != NULL) + { + IM_UNUSED(tab_bar); + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); + ImGuiID id = docked_window->TabId; + KeepAliveID(id); + return id; + } + else + { + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(label); + } +} + +static float ImGui::TabBarCalcMaxTabWidth() +{ + ImGuiContext& g = *GImGui; + return g.FontSize * 20.0f; +} + +ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id) +{ + if (tab_id != 0) + for (int n = 0; n < tab_bar->Tabs.Size; n++) + if (tab_bar->Tabs[n].ID == tab_id) + return &tab_bar->Tabs[n]; + return NULL; +} + +// Order = visible order, not submission order! (which is tab->BeginOrder) +ImGuiTabItem* ImGui::TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order) +{ + if (order < 0 || order >= tab_bar->Tabs.Size) + return NULL; + return &tab_bar->Tabs[order]; +} + +// FIXME: See references to #2304 in TODO.txt +ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* most_recently_selected_tab = NULL; + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) + if (tab->Window && tab->Window->WasActive) + most_recently_selected_tab = tab; + } + return most_recently_selected_tab; +} + +ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar) +{ + if (tab_bar->LastTabItemIdx < 0 || tab_bar->LastTabItemIdx >= tab_bar->Tabs.Size) + return NULL; + return &tab_bar->Tabs[tab_bar->LastTabItemIdx]; +} + +const char* ImGui::TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) +{ + if (tab->Window) + return tab->Window->Name; + if (tab->NameOffset == -1) + return "N/A"; + IM_ASSERT(tab->NameOffset < tab_bar->TabsNames.Buf.Size); + return tab_bar->TabsNames.Buf.Data + tab->NameOffset; +} + +// The purpose of this call is to register tab in advance so we can control their order at the time they appear. +// Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. +void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(TabBarFindTabByID(tab_bar, window->TabId) == NULL); + IM_ASSERT(g.CurrentTabBar != tab_bar); // Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar->CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) + + if (!window->HasCloseButton) + tab_flags |= ImGuiTabItemFlags_NoCloseButton; // Set _NoCloseButton immediately because it will be used for first-frame width calculation. + + ImGuiTabItem new_tab; + new_tab.ID = window->TabId; + new_tab.Flags = tab_flags; + new_tab.LastFrameVisible = tab_bar->CurrFrameVisible; // Required so BeginTabBar() doesn't ditch the tab + if (new_tab.LastFrameVisible == -1) + new_tab.LastFrameVisible = g.FrameCount - 1; + new_tab.Window = window; // Required so tab bar layout can compute the tab width before tab submission + tab_bar->Tabs.push_back(new_tab); +} + +// The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. +void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) +{ + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab_bar->Tabs.erase(tab); + if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } +} + +// Called on manual closure attempt +void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) +{ + if (tab->Flags & ImGuiTabItemFlags_Button) + return; // A button appended with TabItemButton(). + + if ((tab->Flags & (ImGuiTabItemFlags_UnsavedDocument | ImGuiTabItemFlags_NoAssumedClosure)) == 0) + { + // This will remove a frame of lag for selecting another tab on closure. + // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure + tab->WantClose = true; + if (tab_bar->VisibleTabId == tab->ID) + { + tab->LastFrameVisible = -1; + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; + } + } + else + { + // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) + if (tab_bar->VisibleTabId != tab->ID) + TabBarQueueFocus(tab_bar, tab); + } +} + +static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) +{ + scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth()); + return ImMax(scrolling, 0.0f); +} + +// Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys +static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections) +{ + ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id); + if (tab == NULL) + return; + if (tab->Flags & ImGuiTabItemFlags_SectionMask_) + return; + + ImGuiContext& g = *GImGui; + float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + int order = TabBarGetTabOrder(tab_bar, tab); + + // Scrolling happens only in the central section (leading/trailing sections are not scrolling) + float scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections); + + // We make all tabs positions all relative Sections[0].Width to make code simpler + float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f); + float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f); + tab_bar->ScrollingTargetDistToVisibility = 0.0f; + if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) + { + // Scroll to the left + tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); + tab_bar->ScrollingTarget = tab_x1; + } + else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width) + { + // Scroll to the right + tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f); + tab_bar->ScrollingTarget = tab_x2 - scrollable_width; + } +} + +void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) +{ + tab_bar->NextSelectedTabId = tab->ID; +} + +void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name) +{ + IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars + ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name, NULL); + tab_bar->NextSelectedTabId = tab_id; +} + +void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset) +{ + IM_ASSERT(offset != 0); + IM_ASSERT(tab_bar->ReorderRequestTabId == 0); + tab_bar->ReorderRequestTabId = tab->ID; + tab_bar->ReorderRequestOffset = (ImS16)offset; +} + +void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* src_tab, ImVec2 mouse_pos) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(tab_bar->ReorderRequestTabId == 0); + if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0) + return; + + const float tab_spacing = g.Style.ItemInnerSpacing.x; + const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0; + const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0); + + // Count number of contiguous tabs we are crossing over + const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1; + const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab); + int dst_idx = src_idx; + for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir) + { + // Reordered tabs must share the same section + const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i]; + if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder) + break; + if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_)) + break; + dst_idx = i; + + // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. + const float x1 = bar_offset + dst_tab->Offset - tab_spacing; + const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + tab_spacing; + //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); + if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2)) + break; + } + + if (dst_idx != src_idx) + TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx); +} + +bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId); + if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder)) + return false; + + //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools + int tab2_order = TabBarGetTabOrder(tab_bar, tab1) + tab_bar->ReorderRequestOffset; + if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size) + return false; + + // Reordered tabs must share the same section + // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too) + ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; + if (tab2->Flags & ImGuiTabItemFlags_NoReorder) + return false; + if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_)) + return false; + + ImGuiTabItem item_tmp = *tab1; + ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2; + ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1; + const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset; + memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem)); + *tab2 = item_tmp; + + if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) + MarkIniSettingsDirty(); + return true; +} + +static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); + const float scrolling_buttons_width = arrow_button_size.x * 2.0f; + + const ImVec2 backup_cursor_pos = window->DC.CursorPos; + //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255)); + + int select_dir = 0; + ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; + arrow_col.w *= 0.5f; + + PushStyleColor(ImGuiCol_Text, arrow_col); + PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + PushItemFlag(ImGuiItemFlags_ButtonRepeat | ImGuiItemFlags_NoNav, true); + const float backup_repeat_delay = g.IO.KeyRepeatDelay; + const float backup_repeat_rate = g.IO.KeyRepeatRate; + g.IO.KeyRepeatDelay = 0.250f; + g.IO.KeyRepeatRate = 0.200f; + float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width); + window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y); + if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick)) + select_dir = -1; + window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y); + if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick)) + select_dir = +1; + PopItemFlag(); + PopStyleColor(2); + g.IO.KeyRepeatRate = backup_repeat_rate; + g.IO.KeyRepeatDelay = backup_repeat_delay; + + ImGuiTabItem* tab_to_scroll_to = NULL; + if (select_dir != 0) + if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + { + int selected_order = TabBarGetTabOrder(tab_bar, tab_item); + int target_order = selected_order + select_dir; + + // Skip tab item buttons until another tab item is found or end is reached + while (tab_to_scroll_to == NULL) + { + // If we are at the end of the list, still scroll to make our tab visible + tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; + + // Cross through buttons + // (even if first/last item is a button, return it so we can update the scroll) + if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button) + { + target_order += select_dir; + selected_order += select_dir; + tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL; + } + } + } + window->DC.CursorPos = backup_cursor_pos; + tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; + + return tab_to_scroll_to; +} + +static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // We use g.Style.FramePadding.y to match the square ArrowButton size + const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y; + const ImVec2 backup_cursor_pos = window->DC.CursorPos; + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y); + tab_bar->BarRect.Min.x += tab_list_popup_button_width; + + ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; + arrow_col.w *= 0.5f; + PushStyleColor(ImGuiCol_Text, arrow_col); + PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest); + PopStyleColor(2); + + ImGuiTabItem* tab_to_select = NULL; + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (tab->Flags & ImGuiTabItemFlags_Button) + continue; + + const char* tab_name = TabBarGetTabName(tab_bar, tab); + if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID)) + tab_to_select = tab; + } + EndCombo(); + } + + window->DC.CursorPos = backup_cursor_pos; + return tab_to_select; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +//------------------------------------------------------------------------- +// - BeginTabItem() +// - EndTabItem() +// - TabItemButton() +// - TabItemEx() [Internal] +// - SetTabItemClosed() +// - TabItemCalcSize() [Internal] +// - TabItemBackground() [Internal] +// - TabItemLabelAndCloseButton() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT_USER_ERROR_RETV(tab_bar != NULL, false, "Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! + + bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); + if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) + } + return ret; +} + +void ImGui::EndTabItem() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT(tab_bar->LastTabItemIdx >= 0); + ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) + PopID(); +} + +bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT_USER_ERROR_RETV(tab_bar != NULL, false, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL); +} + +void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); + SetNextItemWidth(width); + TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL); +} + +bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window) +{ + // Layout whole tab bar if not already done + ImGuiContext& g = *GImGui; + if (tab_bar->WantLayout) + { + ImGuiNextItemData backup_next_item_data = g.NextItemData; + TabBarLayout(tab_bar); + g.NextItemData = backup_next_item_data; + } + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window); + + // If the user called us with *p_open == false, we early out and don't render. + // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + if (p_open && !*p_open) + { + ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav); + return false; + } + + IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button)); + IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing + + // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented) + if (flags & ImGuiTabItemFlags_NoCloseButton) + p_open = NULL; + else if (p_open == NULL) + flags |= ImGuiTabItemFlags_NoCloseButton; + + // Acquire tab data + ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id); + bool tab_is_new = false; + if (tab == NULL) + { + tab_bar->Tabs.push_back(ImGuiTabItem()); + tab = &tab_bar->Tabs.back(); + tab->ID = id; + tab_bar->TabsAddedNew = tab_is_new = true; + } + tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab); + + // Calculate tab contents size + ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument)); + tab->RequestedWidth = -1.0f; + if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth) + size.x = tab->RequestedWidth = g.NextItemData.Width; + if (tab_is_new) + tab->Width = ImMax(1.0f, size.x); + tab->ContentWidth = size.x; + tab->BeginOrder = tab_bar->TabsActiveCount++; + + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; + const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount); + const bool tab_just_unsaved = (flags & ImGuiTabItemFlags_UnsavedDocument) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument); + const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0; + tab->LastFrameVisible = g.FrameCount; + tab->Flags = flags; + tab->Window = docked_window; + + // Append name _WITH_ the zero-terminator + // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) + if (docked_window != NULL) + { + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); + tab->NameOffset = -1; + } + else + { + tab->NameOffset = (ImS32)tab_bar->TabsNames.size(); + tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1); + } + + // Update selected tab + if (!is_tab_button) + { + if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0) + if (!tab_bar_appearing || tab_bar->SelectedTabId == 0) + TabBarQueueFocus(tab_bar, tab); // New tabs gets activated + if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // _SetSelected can only be passed on explicit tab bar + TabBarQueueFocus(tab_bar, tab); + } + + // Lock visibility + // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) + bool tab_contents_visible = (tab_bar->VisibleTabId == id); + if (tab_contents_visible) + tab_bar->VisibleTabWasSubmitted = true; + + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches + if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing && docked_window == NULL) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_contents_visible = true; + + // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. + if (tab_appearing && (!tab_bar_appearing || tab_is_new)) + { + ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav); + if (is_tab_button) + return false; + return tab_contents_visible; + } + + if (tab_bar->SelectedTabId == id) + tab->LastFrameSelected = g.FrameCount; + + // Backup current layout position + const ImVec2 backup_main_cursor_pos = window->DC.CursorPos; + + // Layout + const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0; + size.x = tab->Width; + if (is_central_section) + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_TRUNC(tab->Offset - tab_bar->ScrollingAnim), 0.0f); + else + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + size); + + // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) + const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX); + if (want_clip_rect) + PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true); + + ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; + ItemSize(bb.GetSize(), style.FramePadding.y); + window->DC.CursorMaxPos = backup_cursor_max_pos; + + if (!ItemAdd(bb, id)) + { + if (want_clip_rect) + PopClipRect(); + window->DC.CursorPos = backup_main_cursor_pos; + return tab_contents_visible; + } + + // Click to Select a tab + ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap); + if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + bool hovered, held, pressed; + if (flags & ImGuiTabItemFlags_Invisible) + hovered = held = pressed = false; + else + pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + if (pressed && !is_tab_button) + TabBarQueueFocus(tab_bar, tab); + + // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. + if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated) + g.ActiveIdWindow = docked_window; + + // Drag and drop a single floating window node moves it + ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL; + const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1); + if (held && single_floating_window_node && IsMouseDragging(0, 0.0f)) + { + // Move + StartMouseMovingWindow(docked_window); + } + else if (held && !tab_appearing && IsMouseDragging(0)) + { + // Drag and drop: re-order tabs + int drag_dir = 0; + float drag_distance_from_edge_x = 0.0f; + if (!g.DragDropActive && ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (docked_window != NULL))) + { + // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x) + { + drag_dir = -1; + drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x) + { + drag_dir = +1; + drag_distance_from_edge_x = g.IO.MousePos.x - bb.Max.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + } + + // Extract a Dockable window out of it's tab bar + const bool can_undock = docked_window != NULL && !(docked_window->Flags & ImGuiWindowFlags_NoMove) && !(node->MergedFlags & ImGuiDockNodeFlags_NoUndocking); + if (can_undock) + { + // We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar + bool undocking_tab = (g.DragDropActive && g.DragDropPayload.SourceId == id); + if (!undocking_tab) //&& (!g.IO.ConfigDockingWithShift || g.IO.KeyShift) + { + float threshold_base = g.FontSize; + float threshold_x = (threshold_base * 2.2f); + float threshold_y = (threshold_base * 1.5f) + ImClamp((ImFabs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0f) * 0.20f, 0.0f, threshold_base * 4.0f); + //GetForegroundDrawList()->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG] + + float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y); + if (distance_from_edge_y >= threshold_y) + undocking_tab = true; + if (drag_distance_from_edge_x > threshold_x) + if ((drag_dir < 0 && TabBarGetTabOrder(tab_bar, tab) == 0) || (drag_dir > 0 && TabBarGetTabOrder(tab_bar, tab) == tab_bar->Tabs.Size - 1)) + undocking_tab = true; + } + + if (undocking_tab) + { + // Undock + // FIXME: refactor to share more code with e.g. StartMouseMovingWindow + DockContextQueueUndockWindow(&g, docked_window); + g.MovingWindow = docked_window; + SetActiveID(g.MovingWindow->MoveId, g.MovingWindow); + g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min; + g.ActiveIdNoClearOnFocusLoss = true; + SetActiveIdUsingAllKeyboardKeys(); + } + } + } + +#if 0 + if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth) + { + // Enlarge tab display when hovering + bb.Max.x = bb.Min.x + IM_TRUNC(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f))); + display_draw_list = GetForegroundDrawList(window); + TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); + } +#endif + + // Render tab shape + const bool is_visible = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && !(flags & ImGuiTabItemFlags_Invisible); + if (is_visible) + { + ImDrawList* display_draw_list = window->DrawList; + const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); + TabItemBackground(display_draw_list, bb, flags, tab_col); + if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) + { + // Might be moved to TabItemBackground() ? + ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); + if (style.TabRounding > 0.0f) + { + float rounding = style.TabRounding; + display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9); + display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11); + display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize); + } + else + { + display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); + } + } + RenderNavCursor(bb, id); + + // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. + const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button) + TabBarQueueFocus(tab_bar, tab); + + if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) + flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Render tab label, process close button + const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0; + bool just_closed; + bool text_clipped; + TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); + if (just_closed && p_open != NULL) + { + *p_open = false; + TabBarCloseTab(tab_bar, tab); + } + + // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent) + // That state is copied to window->DockTabItemStatusFlags by our caller. + if (docked_window && (hovered || g.HoveredId == close_button_id)) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + + // Tooltip + // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok) + // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores) + // FIXME: This is a mess. + // FIXME: We may want disabled tab to still display the tooltip? + if (text_clipped && g.HoveredId == id && !held) + if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) + SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); + } + + // Restore main window position so user can draw there + if (want_clip_rect) + PopClipRect(); + window->DC.CursorPos = backup_main_cursor_pos; + + IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected + if (is_tab_button) + return pressed; + return tab_contents_visible; +} + +// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. +// To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). +// Tabs closed by the close button will automatically be flagged to avoid this issue. +void ImGui::SetTabItemClosed(const char* label) +{ + ImGuiContext& g = *GImGui; + bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); + if (is_within_manual_tab_bar) + { + ImGuiTabBar* tab_bar = g.CurrentTabBar; + ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL); + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab->WantClose = true; // Will be processed by next call to TabBarLayout() + } + else if (ImGuiWindow* window = FindWindowByName(label)) + { + if (window->DockIsActive) + if (ImGuiDockNode* node = window->DockNode) + { + ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window); + TabBarRemoveTab(node->TabBar, tab_id); + window->DockTabWantClose = true; + } + } +} + +ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker) +{ + ImGuiContext& g = *GImGui; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f); + if (has_close_button_or_unsaved_marker) + size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle. + else + size.x += g.Style.FramePadding.x + 1.0f; + return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y); +} + +ImVec2 ImGui::TabItemCalcSize(ImGuiWindow* window) +{ + return TabItemCalcSize(window->Name, window->HasCloseButton || (window->Flags & ImGuiWindowFlags_UnsavedDocument)); +} + +void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col) +{ + // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. + ImGuiContext& g = *GImGui; + const float width = bb.GetWidth(); + IM_UNUSED(flags); + IM_ASSERT(width > 0.0f); + const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); + const float y1 = bb.Min.y + 1.0f; + const float y2 = bb.Max.y - g.Style.TabBarBorderSize; + draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x, y2)); + draw_list->PathFillConvex(col); + if (g.Style.TabBorderSize > 0.0f) + { + draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2)); + draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize); + } +} + +// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic +// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. +void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped) +{ + ImGuiContext& g = *GImGui; + ImVec2 label_size = CalcTextSize(label, NULL, true); + + if (out_just_closed) + *out_just_closed = false; + if (out_text_clipped) + *out_text_clipped = false; + + if (bb.GetWidth() <= 1.0f) + return; + + // In Style V2 we'll have full override of all colors per state (e.g. focused, selected) + // But right now if you want to alter text color of tabs this is what you need to do. +#if 0 + const float backup_alpha = g.Style.Alpha; + if (!is_contents_visible) + g.Style.Alpha *= 0.7f; +#endif + + // Render text label (with clipping + alpha gradient) + unsaved marker + ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); + + // Return clipped state ignoring the close button + if (out_text_clipped) + { + *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x; + //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255)); + } + + const float button_sz = g.FontSize; + const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y); + + // Close Button & Unsaved Marker + // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() + // 'hovered' will be true when hovering the Tab but NOT when hovering the close button + // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button + // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false + bool close_button_pressed = false; + bool close_button_visible = false; + bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too. + + if (close_button_id != 0) + { + if (is_contents_visible) + close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected)); + else + close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected)); + } + + // When tabs/document is unsaved, the unsaved marker takes priority over the close button. + const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered); + if (unsaved_marker_visible) + { + ImVec2 bullet_pos = button_pos + ImVec2(button_sz, button_sz) * 0.5f; + RenderBullet(draw_list, bullet_pos, GetColorU32(ImGuiCol_UnsavedMarker)); + } + else if (close_button_visible) + { + ImGuiLastItemData last_item_backup = g.LastItemData; + if (CloseButton(close_button_id, button_pos)) + close_button_pressed = true; + g.LastItemData = last_item_backup; + + // Close with middle mouse button + if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) + close_button_pressed = true; + } + + // This is all rather complicated + // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) + // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist.. + float ellipsis_max_x = text_ellipsis_clip_bb.Max.x; + if (close_button_visible || unsaved_marker_visible) + { + const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f; + if (visible_without_hover) + { + text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f; + ellipsis_max_x -= button_sz * 0.90f; + } + else + { + text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f; + } + } + LogSetNextTextDecoration("/", "\\"); + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size); + +#if 0 + if (!is_contents_visible) + g.Style.Alpha = backup_alpha; +#endif + + if (out_just_closed) + *out_just_closed = close_button_pressed; +} + + +#endif // #ifndef IMGUI_DISABLE diff --git a/libs/imgui/imstb_rectpack.h b/libs/imgui/imstb_rectpack.h new file mode 100644 index 0000000..f6917e7 --- /dev/null +++ b/libs/imgui/imstb_rectpack.h @@ -0,0 +1,627 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_rect_pack.h 1.01. +// Grep for [DEAR IMGUI] to find the changes. +// +// stb_rect_pack.h - v1.01 - public domain - rectangle packing +// Sean Barrett 2014 +// +// Useful for e.g. packing rectangular textures into an atlas. +// Does not do rotation. +// +// Before #including, +// +// #define STB_RECT_PACK_IMPLEMENTATION +// +// in the file that you want to have the implementation. +// +// Not necessarily the awesomest packing method, but better than +// the totally naive one in stb_truetype (which is primarily what +// this is meant to replace). +// +// Has only had a few tests run, may have issues. +// +// More docs to come. +// +// No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. +// +// This library currently uses the Skyline Bottom-Left algorithm. +// +// Please note: better rectangle packers are welcome! Please +// implement them to the same API, but with a different init +// function. +// +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// github:IntellectualKitty +// +// Bugfixes / warning fixes +// Jeremy Jaussaud +// Fabian Giesen +// +// Version history: +// +// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section +// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles +// 0.99 (2019-02-07) warning fixes +// 0.11 (2017-03-03) return packing success/fail result +// 0.10 (2016-10-25) remove cast-away-const to avoid warnings +// 0.09 (2016-08-27) fix compiler warnings +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +// 0.05: added STBRP_ASSERT to allow replacing assert +// 0.04: fixed minor bug in STBRP_LARGE_RECTS support +// 0.01: initial release +// +// LICENSE +// +// See end of file for license information. + +////////////////////////////////////////////////////////////////////////////// +// +// INCLUDE SECTION +// + +#ifndef STB_INCLUDE_STB_RECT_PACK_H +#define STB_INCLUDE_STB_RECT_PACK_H + +#define STB_RECT_PACK_VERSION 1 + +#ifdef STBRP_STATIC +#define STBRP_DEF static +#else +#define STBRP_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct stbrp_context stbrp_context; +typedef struct stbrp_node stbrp_node; +typedef struct stbrp_rect stbrp_rect; + +typedef int stbrp_coord; + +#define STBRP__MAXVAL 0x7fffffff +// Mostly for internal use, but this is the maximum supported coordinate value. + +STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); +// Assign packed locations to rectangles. The rectangles are of type +// 'stbrp_rect' defined below, stored in the array 'rects', and there +// are 'num_rects' many of them. +// +// Rectangles which are successfully packed have the 'was_packed' flag +// set to a non-zero value and 'x' and 'y' store the minimum location +// on each axis (i.e. bottom-left in cartesian coordinates, top-left +// if you imagine y increasing downwards). Rectangles which do not fit +// have the 'was_packed' flag set to 0. +// +// You should not try to access the 'rects' array from another thread +// while this function is running, as the function temporarily reorders +// the array while it executes. +// +// To pack into another rectangle, you need to call stbrp_init_target +// again. To continue packing into the same rectangle, you can call +// this function again. Calling this multiple times with multiple rect +// arrays will probably produce worse packing results than calling it +// a single time with the full rectangle array, but the option is +// available. +// +// The function returns 1 if all of the rectangles were successfully +// packed and 0 otherwise. + +struct stbrp_rect +{ + // reserved for your use: + int id; + + // input: + stbrp_coord w, h; + + // output: + stbrp_coord x, y; + int was_packed; // non-zero if valid packing + +}; // 16 bytes, nominally + + +STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); +// Initialize a rectangle packer to: +// pack a rectangle that is 'width' by 'height' in dimensions +// using temporary storage provided by the array 'nodes', which is 'num_nodes' long +// +// You must call this function every time you start packing into a new target. +// +// There is no "shutdown" function. The 'nodes' memory must stay valid for +// the following stbrp_pack_rects() call (or calls), but can be freed after +// the call (or calls) finish. +// +// Note: to guarantee best results, either: +// 1. make sure 'num_nodes' >= 'width' +// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' +// +// If you don't do either of the above things, widths will be quantized to multiples +// of small integers to guarantee the algorithm doesn't run out of temporary storage. +// +// If you do #2, then the non-quantized algorithm will be used, but the algorithm +// may run out of temporary storage and be unable to pack some rectangles. + +STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); +// Optionally call this function after init but before doing any packing to +// change the handling of the out-of-temp-memory scenario, described above. +// If you call init again, this will be reset to the default (false). + + +STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); +// Optionally select which packing heuristic the library should use. Different +// heuristics will produce better/worse results for different data sets. +// If you call init again, this will be reset to the default. + +enum +{ + STBRP_HEURISTIC_Skyline_default=0, + STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, + STBRP_HEURISTIC_Skyline_BF_sortHeight +}; + + +////////////////////////////////////////////////////////////////////////////// +// +// the details of the following structures don't matter to you, but they must +// be visible so you can handle the memory allocations for them + +struct stbrp_node +{ + stbrp_coord x,y; + stbrp_node *next; +}; + +struct stbrp_context +{ + int width; + int height; + int align; + int init_mode; + int heuristic; + int num_nodes; + stbrp_node *active_head; + stbrp_node *free_head; + stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' +}; + +#ifdef __cplusplus +} +#endif + +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION SECTION +// + +#ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT +#include +#define STBRP_SORT qsort +#endif + +#ifndef STBRP_ASSERT +#include +#define STBRP_ASSERT assert +#endif + +#ifdef _MSC_VER +#define STBRP__NOTUSED(v) (void)(v) +#define STBRP__CDECL __cdecl +#else +#define STBRP__NOTUSED(v) (void)sizeof(v) +#define STBRP__CDECL +#endif + +enum +{ + STBRP__INIT_skyline = 1 +}; + +STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) +{ + switch (context->init_mode) { + case STBRP__INIT_skyline: + STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); + context->heuristic = heuristic; + break; + default: + STBRP_ASSERT(0); + } +} + +STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) +{ + if (allow_out_of_mem) + // if it's ok to run out of memory, then don't bother aligning them; + // this gives better packing, but may fail due to OOM (even though + // the rectangles easily fit). @TODO a smarter approach would be to only + // quantize once we've hit OOM, then we could get rid of this parameter. + context->align = 1; + else { + // if it's not ok to run out of memory, then quantize the widths + // so that num_nodes is always enough nodes. + // + // I.e. num_nodes * align >= width + // align >= width / num_nodes + // align = ceil(width/num_nodes) + + context->align = (context->width + context->num_nodes-1) / context->num_nodes; + } +} + +STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) +{ + int i; + + for (i=0; i < num_nodes-1; ++i) + nodes[i].next = &nodes[i+1]; + nodes[i].next = NULL; + context->init_mode = STBRP__INIT_skyline; + context->heuristic = STBRP_HEURISTIC_Skyline_default; + context->free_head = &nodes[0]; + context->active_head = &context->extra[0]; + context->width = width; + context->height = height; + context->num_nodes = num_nodes; + stbrp_setup_allow_out_of_mem(context, 0); + + // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) + context->extra[0].x = 0; + context->extra[0].y = 0; + context->extra[0].next = &context->extra[1]; + context->extra[1].x = (stbrp_coord) width; + context->extra[1].y = (1<<30); + context->extra[1].next = NULL; +} + +// find minimum y position if it starts at x1 +static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +{ + stbrp_node *node = first; + int x1 = x0 + width; + int min_y, visited_width, waste_area; + + STBRP__NOTUSED(c); + + STBRP_ASSERT(first->x <= x0); + + #if 0 + // skip in case we're past the node + while (node->next->x <= x0) + ++node; + #else + STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency + #endif + + STBRP_ASSERT(node->x <= x0); + + min_y = 0; + waste_area = 0; + visited_width = 0; + while (node->x < x1) { + if (node->y > min_y) { + // raise min_y higher. + // we've accounted for all waste up to min_y, + // but we'll now add more waste for everything we've visted + waste_area += visited_width * (node->y - min_y); + min_y = node->y; + // the first time through, visited_width might be reduced + if (node->x < x0) + visited_width += node->next->x - x0; + else + visited_width += node->next->x - node->x; + } else { + // add waste area + int under_width = node->next->x - node->x; + if (under_width + visited_width > width) + under_width = width - visited_width; + waste_area += under_width * (min_y - node->y); + visited_width += under_width; + } + node = node->next; + } + + *pwaste = waste_area; + return min_y; +} + +typedef struct +{ + int x,y; + stbrp_node **prev_link; +} stbrp__findresult; + +static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) +{ + int best_waste = (1<<30), best_x, best_y = (1 << 30); + stbrp__findresult fr; + stbrp_node **prev, *node, *tail, **best = NULL; + + // align to multiple of c->align + width = (width + c->align - 1); + width -= width % c->align; + STBRP_ASSERT(width % c->align == 0); + + // if it can't possibly fit, bail immediately + if (width > c->width || height > c->height) { + fr.prev_link = NULL; + fr.x = fr.y = 0; + return fr; + } + + node = c->active_head; + prev = &c->active_head; + while (node->x + width <= c->width) { + int y,waste; + y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); + if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL + // bottom left + if (y < best_y) { + best_y = y; + best = prev; + } + } else { + // best-fit + if (y + height <= c->height) { + // can only use it if it first vertically + if (y < best_y || (y == best_y && waste < best_waste)) { + best_y = y; + best_waste = waste; + best = prev; + } + } + } + prev = &node->next; + node = node->next; + } + + best_x = (best == NULL) ? 0 : (*best)->x; + + // if doing best-fit (BF), we also have to try aligning right edge to each node position + // + // e.g, if fitting + // + // ____________________ + // |____________________| + // + // into + // + // | | + // | ____________| + // |____________| + // + // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + // + // This makes BF take about 2x the time + + if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { + tail = c->active_head; + node = c->active_head; + prev = &c->active_head; + // find first node that's admissible + while (tail->x < width) + tail = tail->next; + while (tail) { + int xpos = tail->x - width; + int y,waste; + STBRP_ASSERT(xpos >= 0); + // find the left position that matches this + while (node->next->x <= xpos) { + prev = &node->next; + node = node->next; + } + STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); + y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); + if (y + height <= c->height) { + if (y <= best_y) { + if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { + best_x = xpos; + //STBRP_ASSERT(y <= best_y); [DEAR IMGUI] + best_y = y; + best_waste = waste; + best = prev; + } + } + } + tail = tail->next; + } + } + + fr.prev_link = best; + fr.x = best_x; + fr.y = best_y; + return fr; +} + +static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) +{ + // find best position according to heuristic + stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); + stbrp_node *node, *cur; + + // bail if: + // 1. it failed + // 2. the best node doesn't fit (we don't always check this) + // 3. we're out of memory + if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { + res.prev_link = NULL; + return res; + } + + // on success, create new node + node = context->free_head; + node->x = (stbrp_coord) res.x; + node->y = (stbrp_coord) (res.y + height); + + context->free_head = node->next; + + // insert the new node into the right starting point, and + // let 'cur' point to the remaining nodes needing to be + // stiched back in + + cur = *res.prev_link; + if (cur->x < res.x) { + // preserve the existing one, so start testing with the next one + stbrp_node *next = cur->next; + cur->next = node; + cur = next; + } else { + *res.prev_link = node; + } + + // from here, traverse cur and free the nodes, until we get to one + // that shouldn't be freed + while (cur->next && cur->next->x <= res.x + width) { + stbrp_node *next = cur->next; + // move the current node to the free list + cur->next = context->free_head; + context->free_head = cur; + cur = next; + } + + // stitch the list back in + node->next = cur; + + if (cur->x < res.x + width) + cur->x = (stbrp_coord) (res.x + width); + +#ifdef _DEBUG + cur = context->active_head; + while (cur->x < context->width) { + STBRP_ASSERT(cur->x < cur->next->x); + cur = cur->next; + } + STBRP_ASSERT(cur->next == NULL); + + { + int count=0; + cur = context->active_head; + while (cur) { + cur = cur->next; + ++count; + } + cur = context->free_head; + while (cur) { + cur = cur->next; + ++count; + } + STBRP_ASSERT(count == context->num_nodes+2); + } +#endif + + return res; +} + +static int STBRP__CDECL rect_height_compare(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + if (p->h > q->h) + return -1; + if (p->h < q->h) + return 1; + return (p->w > q->w) ? -1 : (p->w < q->w); +} + +static int STBRP__CDECL rect_original_order(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); +} + +STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) +{ + int i, all_rects_packed = 1; + + // we use the 'was_packed' field internally to allow sorting/unsorting + for (i=0; i < num_rects; ++i) { + rects[i].was_packed = i; + } + + // sort according to heuristic + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); + + for (i=0; i < num_rects; ++i) { + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space + } else { + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } + } + } + + // unsort + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); + + // set was_packed flags and all_rects_packed status + for (i=0; i < num_rects; ++i) { + rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); + if (!rects[i].was_packed) + all_rects_packed = 0; + } + + // return the all_rects_packed status + return all_rects_packed; +} +#endif + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/libs/imgui/imstb_textedit.h b/libs/imgui/imstb_textedit.h new file mode 100644 index 0000000..583508f --- /dev/null +++ b/libs/imgui/imstb_textedit.h @@ -0,0 +1,1527 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_textedit.h 1.14. +// Those changes would need to be pushed into nothings/stb: +// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) +// - Added name to struct or it may be forward declared in our code. +// - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) +// - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +// Grep for [DEAR IMGUI] to find some changes. +// - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* + +// stb_textedit.h - v1.14 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// See end of file for license information. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove', which you can override +// by defining IMSTB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +// 1.14 (2021-07-11) page up/down, various fixes +// 1.13 (2019-02-07) fix bug in undo size management +// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +// 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.9 (2016-08-27) customizable move-by-word +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X +// 1.4 (2014-08-17) fix signed/unsigned warnings +// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +// 1.2 (2014-05-27) fix some RAD types that had crept into the new code +// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +// 1.0 (2012-07-26) improve documentation, initial public release +// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +// 0.2 (2011-11-28) fixes to undo/redo +// 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +// Louis Schnellbach: page up/down in 1.14 +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut +// Dan Thompson +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHARCOUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string being edited, +// typically this is a wrapper object with other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters +// starting from character #n (see discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +// to the xpos of the i+1'th char for a line of characters +// starting at character #n (i.e. accounts for kerning +// with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character +// (return type is int, -1 means not valid to insert) +// (not supported if you want to use UTF-8, see below) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based +// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +// as manually wordwrapping for end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) try to insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// returns number of characters actually inserted. [DEAR IMGUI] +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME +// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END +// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME +// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +// STB_TEXTEDIT_K_UNDO keyboard input to perform undo +// STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text +// +// To support UTF-8: +// +// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character +// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// Do NOT define STB_TEXTEDIT_KEYTOTEXT. +// Instead, call stb_textedit_text() directly for text contents. +// +// Keyboard input must be encoded as a single integer value; e.g. a character code +// and some bitflags that represent shift states. to simplify the interface, SHIFT must +// be a bitflag, so we can test the shifted state of cursor movements to allow selection, +// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN +// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, +// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the +// API below. The control keys will only match WM_KEYDOWN events because of the +// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute word-wrapping +// here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the cursor +// and reset the selection start/end to the cursor point. the x,y must +// be relative to the text widget, with (0,0) being the top left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste buffer. +// (To copy, just copy the current selection out of the string yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the current +// selection if there is one. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from control +// inputs, set a high bit to distinguish the two; then you can define the +// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit +// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is +// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to +// anything other type you want before including. +// if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are +// transformed into text and stb_textedit_text() is automatically called. +// +// text: (added 2025) +// call this to directly send text input the textfield, which is required +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// cannot infer text length. +// +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_IMSTB_TEXTEDIT_H +#define INCLUDE_IMSTB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef IMSTB_TEXTEDIT_UNDOSTATECOUNT +#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef IMSTB_TEXTEDIT_UNDOCHARCOUNT +#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef IMSTB_TEXTEDIT_CHARTYPE +#define IMSTB_TEXTEDIT_CHARTYPE int +#endif +#ifndef IMSTB_TEXTEDIT_POSITIONTYPE +#define IMSTB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct +{ + // private data + IMSTB_TEXTEDIT_POSITIONTYPE where; + IMSTB_TEXTEDIT_POSITIONTYPE insert_length; + IMSTB_TEXTEDIT_POSITIONTYPE delete_length; + int char_storage; +} StbUndoRecord; + +typedef struct +{ + // private data + StbUndoRecord undo_rec [IMSTB_TEXTEDIT_UNDOSTATECOUNT]; + IMSTB_TEXTEDIT_CHARTYPE undo_char[IMSTB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + int undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct STB_TexteditState +{ + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + int row_count_per_page; + // page size in number of row. + // this value MUST be set to >0 for pageup or pagedown in multilines documents. + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries to seek to along x + StbUndoState undostate; +} STB_TexteditState; + + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct +{ + float x0,x1; // starting x location, end x location (allows for align=right, etc) + float baseline_y_delta; // position of baseline relative to previous row's baseline + float ymin,ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif //INCLUDE_IMSTB_TEXTEDIT_H + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef IMSTB_TEXTEDIT_IMPLEMENTATION + +#ifndef IMSTB_TEXTEDIT_memmove +#include +#define IMSTB_TEXTEDIT_memmove memmove +#endif + +// [DEAR IMGUI] +// Functions must be implemented for UTF8 support +// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. +// There is not necessarily a '[DEAR IMGUI]' at the usage sites. +#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX +#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +#endif +#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX +#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) +#endif + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y, int* out_side_on_line) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i=0, k; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + *out_side_on_line = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (i==0 && y < base_y + r.ymin) + return 0; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + { + *out_side_on_line = 1; + return n; + } + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + prev_x = r.x0; + for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); + if (x < prev_x+w) { + *out_side_on_line = (k == 0) ? 0 : 1; + if (x < prev_x+w/2) + return k+i; + else + return IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k); + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line case + } + + // if the last character is a newline, return that. otherwise return 'after' the last character + *out_side_on_line = 1; + if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) + return i+r.num_chars-1; + else + return i+r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset the selection +static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + int side_on_line; + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + state->cursor = stb_text_locate_coord(str, x, y, &side_on_line); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left); +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location +static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + int p = 0; + int side_on_line; + + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + if (state->select_start == state->select_end) + state->select_start = state->cursor; + + p = stb_text_locate_coord(str, x, y, &side_on_line); + state->cursor = state->select_end = p; + str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left); +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); + +typedef struct +{ + float x,y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous row in +// case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING *str, int n, int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i=0, first; + + if (n == z && single_line) { + // special case if it's at the end (may not be needed?) + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + return; + } + + // search rows to find the one that straddles character n + find->y = 0; + + for(;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (n < i + r.num_chars) + break; + if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling + break; + if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line + break; // [DEAR IMGUI] + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + if (i == z) // [DEAR IMGUI] + { + r.num_chars = 0; // [DEAR IMGUI] + break; // [DEAR IMGUI] + } + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + for (i=0; first+i < n; i = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i) - first) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) state->select_start = n; + if (state->select_end > n) state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +// [DEAR IMGUI] Extracted this function so we can more easily add support for word-wrapping. +#ifndef STB_TEXTEDIT_MOVELINESTART +static int stb_textedit_move_line_start(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor) +{ + if (state->single_line) + return 0; + while (cursor > 0) { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, cursor); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + cursor = prev; + } + return cursor; +} +#define STB_TEXTEDIT_MOVELINESTART stb_textedit_move_line_start +#endif +#ifndef STB_TEXTEDIT_MOVELINEEND +static int stb_textedit_move_line_end(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->single_line) + return n; + while (cursor < n && STB_TEXTEDIT_GETCHAR(str, cursor) != STB_TEXTEDIT_NEWLINE) + cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, cursor); + return cursor; +} +#define STB_TEXTEDIT_MOVELINEEND stb_textedit_move_line_end +#endif + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) +{ + return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; +} + +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c ) +{ + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character + while (c >= 0 && !is_word_boundary(str, c)) + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c); + + if( c < 0 ) + c = 0; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif + +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c ) +{ + const int len = STB_TEXTEDIT_STRINGLEN(str); + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character + while( c < len && !is_word_boundary( str, c ) ) + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); + + if( c > len ) + c = len; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str,state); // implicitly clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE *text, int len) +{ + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str,state); + // try to insert the characters + len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len); + if (len) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details) + return 0; +} + +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + +// API key: process text input +// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. +static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) +{ + // can't add newline in single-line mode + if (text[0] == '\n' && state->single_line) + return; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len); + if (text_len) { + state->cursor += text_len; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str, state); // implicitly clamps + text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len); + if (text_len) { + stb_text_makeundo_insert(state, state->cursor, text_len); + state->cursor += text_len; + state->has_preferred_x = 0; + } + } +} + +// API key: process a keyboard input +static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) +{ +retry: + switch (key) { + default: { +#ifdef STB_TEXTEDIT_KEYTOTEXT + // This is not suitable for UTF-8 support. + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; + stb_textedit_text(str, state, &ch, 1); + } +#endif + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else + if (state->cursor > 0) + state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + state->select_end = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->select_end); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_MOVEWORDLEFT + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + state->select_end = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->select_end); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGDOWN: + case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down in single-line behave like left&right + key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + int start = find.first_char + find.length; + + if (find.length == 0) + break; + + // [DEAR IMGUI] + // going down while being on the last line shouldn't bring us to that line end + //if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) + // break; + + // now find character position down a row + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + i += next - state->cursor; + state->cursor = next; + } + stb_textedit_clamp(str, state); + + if (state->cursor == find.first_char + find.length) + str->LastMoveDirectionLR = ImGuiDir_Left; + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to next line + find.first_char = find.first_char + find.length; + find.length = row.num_chars; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGUP: + case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down become left&right + key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + + // can only go up if there's a previous row + if (find.prev_first == find.first_char) + break; + + // now find character position up a row + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ) { + float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + i += next - state->cursor; + state->cursor = next; + } + stb_textedit_clamp(str, state); + + if (state->cursor == find.first_char) + str->LastMoveDirectionLR = ImGuiDir_Right; + else if (state->cursor == find.prev_first) + str->LastMoveDirectionLR = ImGuiDir_Left; + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to previous line + // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) + prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; + while (prev_scan > 0) + { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + prev_scan = prev; + } + find.first_char = find.prev_first; + find.prev_first = STB_TEXTEDIT_MOVELINESTART(str, state, prev_scan); + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete(str, state, state->cursor, IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor) - state->cursor); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + stb_textedit_delete(str, state, prev, state->cursor - prev); + state->cursor = prev; + } + } + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor); + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif + case STB_TEXTEDIT_K_LINEEND: { + stb_textedit_clamp(str, state); + stb_textedit_move_to_last(str, state); + state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor); + state->has_preferred_x = 0; + break; + } + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor); + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor); + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + } + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point -= n; + IMSTB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(IMSTB_TEXTEDIT_CHARTYPE))); + for (i=0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it + } + --state->undo_point; + IMSTB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = IMSTB_TEXTEDIT_UNDOSTATECOUNT-1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // move the remaining redo character data to the end of the buffer + state->redo_char_point += n; + IMSTB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((IMSTB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(IMSTB_TEXTEDIT_CHARTYPE))); + // adjust the position of all the other records to account for above memmove + for (i=state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage += n; + } + // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' + // [DEAR IMGUI] + size_t move_size = (size_t)((IMSTB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); + const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; + const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; + IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); + IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); + IMSTB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); + + // now move redo_point to point to the new one + ++state->redo_point; + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't undo + if (numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to make room + while (state->undo_char_point + numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static IMSTB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (IMSTB_TEXTEDIT_POSITIONTYPE) insert_len; + r->delete_length = (IMSTB_TEXTEDIT_POSITIONTYPE) delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point += insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo record + u = s->undo_rec[s->undo_point-1]; + r = &s->undo_rec[s->redo_point-1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo record will + // need to re-insert the characters that get deleted, so we need to store + // them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= IMSTB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters eventually + while (s->undo_char_point + u.delete_length > s->redo_char_point) { + // should never happen: + if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) + return; + // there's currently not enough room, so discard a redo record + stb_textedit_discard_redo(s); + } + r = &s->undo_rec[s->redo_point-1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = s->redo_char_point - u.delete_length; + + // now save the characters + for (i=0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + u.insert_length = STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo record + // was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo record + // needs to store the characters + + if (s->undo_char_point + u->insert_length > s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = s->undo_char_point + u->insert_length; + + // now save the characters + for (i=0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; + } + + state->cursor = r.where + r.insert_length; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) +{ + int i; + IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i=0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) +{ + int i; + IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); + if (p) { + for (i=0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char) is_single_line; + state->insert_mode = 0; + state->row_count_per_page = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +static int stb_textedit_paste(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + return stb_textedit_paste_internal(str, state, (IMSTB_TEXTEDIT_CHARTYPE *) ctext, len); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif//IMSTB_TEXTEDIT_IMPLEMENTATION + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/libs/imgui/imstb_truetype.h b/libs/imgui/imstb_truetype.h new file mode 100644 index 0000000..cf33289 --- /dev/null +++ b/libs/imgui/imstb_truetype.h @@ -0,0 +1,5085 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_truetype.h 1.26. +// Mostly fixing for compiler and static analyzer warnings. +// Grep for [DEAR IMGUI] to find the changes. + +// stb_truetype.h - v1.26 - public domain +// authored from 2009-2021 by Sean Barrett / RAD Game Tools +// +// ======================================================================= +// +// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +// +// This library does no range checking of the offsets found in the file, +// meaning an attacker can use it to read arbitrary memory. +// +// ======================================================================= +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +// Cass Everitt Martins Mozeiko github:aloucks +// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +// Brian Hook Omar Cornut github:vassvik +// Walter van Niftrik Ryan Griege +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. Brian Costabile +// Ken Voskuil (kaesve) +// +// VERSION HISTORY +// +// 1.26 (2021-08-28) fix broken rasterizer +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places need to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*-y0 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*-y0. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to = 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph received the font's "missing character" glyph, +// typically an empty box by convention. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + int skip_missing; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publicly so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + +typedef struct stbtt_kerningentry +{ + int glyph1; // use stbtt_FindGlyphIndex + int glyph2; + int advance; +} stbtt_kerningentry; + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); +// Retrieves a complete list of all of the kerning pairs provided by the font +// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. +// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of contours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); +// fills svg with the character's SVG data. +// returns data size or 0 if SVG not found. + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +// since most people won't use this, find this table the first time it's needed +static int stbtt__get_svg(stbtt_fontinfo *info) +{ + stbtt_uint32 t; + if (info->svg < 0) { + t = stbtt__find_table(info->data, info->fontstart, "SVG "); + if (t) { + stbtt_uint32 offset = ttULONG(info->data + t + 2); + info->svg = t + offset; + } else { + info->svg = 0; + } + } + return info->svg; +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + info->svg = -1; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start, last; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + last = ttUSHORT(data + endCount + 2*item); + if (unicode_codepoint < start || unicode_codepoint > last) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours < 0) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) return stbtt__new_buf(NULL, 0); // [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422 + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // FALLTHROUGH + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && b0 < 32) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) +{ + stbtt_uint8 *data = info->data + info->kern; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + return ttUSHORT(data+10); +} + +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) +{ + stbtt_uint8 *data = info->data + info->kern; + int k, length; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + length = ttUSHORT(data+10); + if (table_length < length) + length = table_length; + + for (k = 0; k < length; k++) + { + table[k].glyph1 = ttUSHORT(data+18+(k*6)); + table[k].glyph2 = ttUSHORT(data+20+(k*6)); + table[k].advance = ttSHORT(data+22+(k*6)); + } + + return length; +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch (coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + break; + } + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + break; + } + + default: return -1; // unsupported + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch (classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + break; + } + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + break; + } + + default: + return -1; // Unsupported definition type, return an error. + } + + // "All glyphs not assigned to a class fall into class 0". (OpenType spec) + return 0; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i, sti; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i= pairSetCount) return 0; + + needle=glyph2; + r=pairValueCount-1; + l=0; + + // Binary search. + while (l <= r) { + stbtt_uint16 secondGlyph; + stbtt_uint8 *pairValue; + m = (l + r) >> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } else + return 0; + break; + } + + case 2: { + stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? + stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + stbtt_uint16 class1Count = ttUSHORT(table + 12); + stbtt_uint16 class2Count = ttUSHORT(table + 14); + stbtt_uint8 *class1Records, *class2Records; + stbtt_int16 xAdvance; + + if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed + if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed + + class1Records = table + 16; + class2Records = class1Records + 2 * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + 2 * glyph2class); + return xAdvance; + } else + return 0; + break; + } + + default: + return 0; // Unsupported position format + } + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + else if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) +{ + int i; + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); + + int numEntries = ttUSHORT(svg_doc_list); + stbtt_uint8 *svg_docs = svg_doc_list + 2; + + for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) + return svg_doc; + } + return 0; +} + +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) +{ + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc; + + if (info->svg == 0) + return 0; + + svg_doc = stbtt_FindSVGDoc(info, gl); + if (svg_doc != NULL) { + *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); + return ttULONG(svg_doc + 8); + } else { + return 0; + } +} + +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) +{ + return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) +{ + STBTT_assert(top_width >= 0); + STBTT_assert(bottom_width >= 0); + return (top_width + bottom_width) / 2.0f * height; +} + +static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) +{ + return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); +} + +static float stbtt__sized_triangle_area(float height, float width) +{ + return height * width / 2; +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = (sy1 - sy0) * e->direction; + STBTT_assert(x >= 0 && x < len); + scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); + scanline_fill[x] += height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, y_final, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + STBTT_assert(dy >= 0); + STBTT_assert(dx >= 0); + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = y_top + dy * (x1+1 - x0); + + // compute intersection with y axis at x2 + y_final = y_top + dy * (x2 - x0); + + // x1 x_top x2 x_bottom + // y_top +------|-----+------------+------------+--------|---+------------+ + // | | | | | | + // | | | | | | + // sy0 | Txxxxx|............|............|............|............| + // y_crossing | *xxxxx.......|............|............|............| + // | | xxxxx..|............|............|............| + // | | /- xx*xxxx........|............|............| + // | | dy < | xxxxxx..|............|............| + // y_final | | \- | xx*xxx.........|............| + // sy1 | | | | xxxxxB...|............| + // | | | | | | + // | | | | | | + // y_bottom +------------+------------+------------+------------+------------+ + // + // goal is to measure the area covered by '.' in each pixel + + // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 + // @TODO: maybe test against sy1 rather than y_bottom? + if (y_crossing > y_bottom) + y_crossing = y_bottom; + + sign = e->direction; + + // area of the rectangle covered from sy0..y_crossing + area = sign * (y_crossing-sy0); + + // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) + scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); + + // check if final y_crossing is blown up; no test case for this + if (y_final > y_bottom) { + int denom = (x2 - (x1+1)); + y_final = y_bottom; + if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) + dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } + } + + // in second pixel, area covered by line segment found in first pixel + // is always a rectangle 1 wide * the height of that line segment; this + // is exactly what the variable 'area' stores. it also gets a contribution + // from the line segment within it. the THIRD pixel will get the first + // pixel's rectangle contribution, the second pixel's rectangle contribution, + // and its own contribution. the 'own contribution' is the same in every pixel except + // the leftmost and rightmost, a trapezoid that slides down in each pixel. + // the second pixel's contribution to the third pixel will be the + // rectangle 1 wide times the height change in the second pixel, which is dy. + + step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, + // which multiplied by 1-pixel-width is how much pixel area changes for each step in x + // so the area advances by 'step' every time + + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; // area of trapezoid is 1*step/2 + area += step; + } + STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down + STBTT_assert(sy1 > y_final-0.01f); + + // area covered in the last pixel is the rectangle from all the pixels to the left, + // plus the trapezoid filled by the line segment in this pixel all the way to the right edge + scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); + + // the rest of the line is filled based on the total height of the line segment in this pixel + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + // note though that this does happen some of the time because + // x_top and x_bottom can be extrapolated at the top & bottom of + // the shape and actually lie outside the bounding box + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + float y1 = (x - x0) / dx + y_top; + float y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + spc->skip_missing = 0; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + int missing_glyph_added = 0; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + if (glyph == 0) + missing_glyph_added = 1; + } + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, missing_glyph = -1, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed && r->w != 0 && r->h != 0) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + + if (glyph == 0) + missing_glyph = j; + } else if (spc->skip_missing) { + return_value = 0; + } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { + ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i, j, n, return_value; // [DEAR IMGUI] removed = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + + orig[0] = x; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; + int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; + int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; + int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; + int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); + int by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + float q0[2],q1[2],q2[2]; + float hits[2][2]; + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (equal(q0,q1) || equal(q1,q2)) { + x0 = (int)verts[i-1].x; //-V1048 + y0 = (int)verts[i-1].y; //-V1048 + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + a*x^2 + b*x + c = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + if (scale == 0) return NULL; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) + return NULL; + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; + float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; + float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; + float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float len2 = bx*bx + by*by; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + float val; + float min_dist = 999999.0f; + float sx = (float) x + 0.5f; + float sy = (float) y + 0.5f; + float x_gspace = (sx / scale_x); + float y_gspace = (sy / scale_y); + + int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + + if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { + float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; + + float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + float dx = x1-x0, dy = y1-y0; + float px = x0-sx, py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + float t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; + float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; + float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + int num=0; + float ax = x1-x0, ay = y1-y0; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float mx = x0 - sx, my = y0 - sy; + float res[3] = {0.f,0.f,0.f}; + float px,py,t,it,dist2; + float a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + float a = 3*(ax*bx + ay*by); + float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + float c = mx*ax+my*ay; + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { + res[num++] = -c/b; + } + } else { + float discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + float root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + float d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/libs/incbin.h b/libs/incbin.h new file mode 100644 index 0000000..25d2418 --- /dev/null +++ b/libs/incbin.h @@ -0,0 +1,107 @@ +/* + * incbin.h — Portable binary embedding via assembler .incbin directive + * + * Usage: + * INCBIN(myData, "path/to/file.bin"); + * + * This creates: + * extern const unsigned char g_myData_data[]; // file contents + * extern const unsigned char *g_myData_end; // one past end + * extern const unsigned int g_myData_size; // byte count + * + * Compared to xxd -i hex arrays, this uses near-zero compile-time RAM + * because the assembler streams the file directly into the object file + * without building an AST for millions of array elements. + * + * Supports: GCC, Clang, MinGW (any target that uses GAS). + * MSVC: not supported (would need a different strategy). + * + * Based on the public-domain incbin technique. + * Adapted for DragonX Wallet by The Hush Developers, 2024-2026. + */ + +#ifndef DRAGONX_INCBIN_H +#define DRAGONX_INCBIN_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Helper macros for token pasting and stringification. + */ +#define INCBIN_CAT(a, b) INCBIN_CAT_(a, b) +#define INCBIN_CAT_(a, b) a ## b +#define INCBIN_STR(x) INCBIN_STR_(x) +#define INCBIN_STR_(x) #x + +/* + * Section attribute: place embedded data in .rodata so it lives in the + * read-only segment just like a normal const array would. + */ +#if defined(__APPLE__) +# define INCBIN_SECTION ".const_data" +# define INCBIN_MANGLE "_" +#else +# define INCBIN_SECTION ".rodata" +# define INCBIN_MANGLE "" +#endif + +/* + * Alignment: 16 bytes is sufficient for SIMD loads if anyone ever + * wants to process embedded data with SSE/NEON, and is a safe default. + */ +#define INCBIN_ALIGN 16 + +/* + * INCBIN_EXTERN — declare the symbols (use in headers) + */ +#define INCBIN_EXTERN(NAME) \ + extern const unsigned char INCBIN_CAT(g_, INCBIN_CAT(NAME, _data))[]; \ + extern const unsigned char *INCBIN_CAT(g_, INCBIN_CAT(NAME, _end)); \ + extern const unsigned int INCBIN_CAT(g_, INCBIN_CAT(NAME, _size)) + +/* + * INCBIN — define the symbols + embed the file (use in ONE .cpp/.c file) + * + * NAME : C identifier prefix (no quotes) + * FILE : path to the file to embed (string literal, relative to -I or absolute) + * + * The generated assembly: + * .section .rodata + * .balign 16 + * .global g_NAME_data + * g_NAME_data: + * .incbin "FILE" + * .global g_NAME_end + * g_NAME_end: + * .byte 0 // NUL sentinel for C string compatibility + * .balign 4 + * .global g_NAME_size + * g_NAME_size: + * .int g_NAME_end - g_NAME_data + */ +#define INCBIN(NAME, FILE) \ + __asm__( \ + ".section " INCBIN_SECTION "\n" \ + ".balign " INCBIN_STR(INCBIN_ALIGN) "\n" \ + ".global " INCBIN_MANGLE "g_" #NAME "_data\n" \ + INCBIN_MANGLE "g_" #NAME "_data:\n" \ + " .incbin \"" FILE "\"\n" \ + ".global " INCBIN_MANGLE "g_" #NAME "_end\n" \ + INCBIN_MANGLE "g_" #NAME "_end:\n" \ + " .byte 0\n" \ + ".balign 4\n" \ + ".global " INCBIN_MANGLE "g_" #NAME "_size\n" \ + INCBIN_MANGLE "g_" #NAME "_size:\n" \ + " .int " INCBIN_MANGLE "g_" #NAME "_end - " \ + INCBIN_MANGLE "g_" #NAME "_data\n" \ + ".text\n" /* restore default section */ \ + ); \ + INCBIN_EXTERN(NAME) + +#ifdef __cplusplus +} +#endif + +#endif /* DRAGONX_INCBIN_H */ diff --git a/libs/miniz/miniz.c b/libs/miniz/miniz.c new file mode 100644 index 0000000..d07b98d --- /dev/null +++ b/libs/miniz/miniz.c @@ -0,0 +1,646 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz.h" + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* ------------------- zlib-style API's */ + + mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) + { + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; + } + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#elif defined(USE_EXTERNAL_MZCRC) +/* If USE_EXTERNAL_CRC is defined, an external module will export the + * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. + * Depending on the impl, it may be necessary to ~ the input/output crc values. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, + 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, + 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, + 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, + 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, + 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, + 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, + 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, + 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, + 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, + 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, + 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, + 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, + 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, + 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, + 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, + 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, + 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + + void mz_free(void *p) + { + MZ_FREE(p); + } + + MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) + { + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); + } + MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) + { + (void)opaque, (void)address; + MZ_FREE(address); + } + MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) + { + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); + } + + const char *mz_version(void) + { + return MZ_VERSION; + } + +#ifndef MINIZ_NO_ZLIB_APIS + +#ifndef MINIZ_NO_DEFLATE_APIS + + int mz_deflateInit(mz_streamp pStream, int level) + { + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); + } + + int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) + { + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; + } + + int mz_deflateReset(mz_streamp pStream) + { + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; + } + + int mz_deflate(mz_streamp pStream, int flush) + { + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; + } + + int mz_deflateEnd(mz_streamp pStream) + { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; + } + + mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) + { + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); + } + + int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) + { + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((mz_uint64)(source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); + } + + int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) + { + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); + } + + mz_ulong mz_compressBound(mz_ulong source_len) + { + return mz_deflateBound(NULL, source_len); + } + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS + + typedef struct + { + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; + } inflate_state; + + int mz_inflateInit2(mz_streamp pStream, int window_bits) + { + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; + } + + int mz_inflateInit(mz_streamp pStream) + { + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); + } + + int mz_inflateReset(mz_streamp pStream) + { + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + + pDecomp = (inflate_state *)pStream->state; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + /* pDecomp->m_window_bits = window_bits */; + + return MZ_OK; + } + + int mz_inflate(mz_streamp pStream, int flush) + { + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + int mz_inflateEnd(mz_streamp pStream) + { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; + } + int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len) + { + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((mz_uint64)(*pSource_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)*pSource_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + *pSource_len = *pSource_len - stream.avail_in; + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); + } + + int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) + { + return mz_uncompress2(pDest, pDest_len, pSource, &source_len); + } + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + + const char *mz_error(int err) + { + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; + } + +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/libs/miniz/miniz.h b/libs/miniz/miniz.h new file mode 100644 index 0000000..0efc591 --- /dev/null +++ b/libs/miniz/miniz.h @@ -0,0 +1,615 @@ +/* miniz.c 3.1.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateReset/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +#pragma once + +#include "miniz_export.h" + +#if defined(__STRICT_ANSI__) +#define MZ_FORCEINLINE +#elif defined(_MSC_VER) +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32 and adler-32. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_DEFLATE_APIS to disable all compression API's. */ +/*#define MINIZ_NO_DEFLATE_APIS */ + +/* Define MINIZ_NO_INFLATE_APIS to disable all decompression API's. */ +/*#define MINIZ_NO_INFLATE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#ifdef MINIZ_NO_INFLATE_APIS +#define MINIZ_NO_ARCHIVE_APIS +#endif + +#ifdef MINIZ_NO_DEFLATE_APIS +#define MINIZ_NO_ARCHIVE_WRITING_APIS +#endif + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +/* Set MINIZ_LITTLE_ENDIAN only if not set */ +#if !defined(MINIZ_LITTLE_ENDIAN) +#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +#else + +#if MINIZ_X86_OR_X64_CPU +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +#endif +#endif + +/* Using unaligned loads and stores causes errors when using UBSan */ +#if defined(__has_feature) +#if __has_feature(undefined_behavior_sanitizer) +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* ------------------- zlib-style API Definitions. */ + + /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ + typedef unsigned long mz_ulong; + + /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ + MINIZ_EXPORT void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) + /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ + MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) + /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ + MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + + /* Compression strategies. */ + enum + { + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 + }; + +/* Method */ +#define MZ_DEFLATED 8 + + /* Heap allocation callbacks. + Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ + typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); + typedef void (*mz_free_func)(void *opaque, void *address); + typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + + /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ + enum + { + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 + }; + +#define MZ_VERSION "11.3.1" +#define MZ_VERNUM 0xB301 +#define MZ_VER_MAJOR 11 +#define MZ_VER_MINOR 3 +#define MZ_VER_REVISION 1 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + + /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ + enum + { + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 + }; + + /* Return status codes. MZ_PARAM_ERROR is non-standard. */ + enum + { + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 + }; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + + struct mz_internal_state; + + /* Compression/decompression stream struct. */ + typedef struct mz_stream_s + { + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ + } mz_stream; + + typedef mz_stream *mz_streamp; + + /* Returns the version string of miniz.c. */ + MINIZ_EXPORT const char *mz_version(void); + +#ifndef MINIZ_NO_DEFLATE_APIS + + /* mz_deflateInit() initializes a compressor with default options: */ + /* Parameters: */ + /* pStream must point to an initialized mz_stream struct. */ + /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ + /* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ + /* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ + /* Return values: */ + /* MZ_OK on success. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_PARAM_ERROR if the input parameters are bogus. */ + /* MZ_MEM_ERROR on out of memory. */ + MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); + + /* mz_deflateInit2() is like mz_deflate(), except with more control: */ + /* Additional parameters: */ + /* method must be MZ_DEFLATED */ + /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ + /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ + MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + + /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ + MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); + + /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ + /* Parameters: */ + /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ + /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ + /* Return values: */ + /* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ + /* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_PARAM_ERROR if one of the parameters is invalid. */ + /* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ + MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); + + /* mz_deflateEnd() deinitializes a compressor: */ + /* Return values: */ + /* MZ_OK on success. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); + + /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ + MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + + /* Single-call compression functions mz_compress() and mz_compress2(): */ + /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ + MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + + /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ + MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS + + /* Initializes a decompressor. */ + MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); + + /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ + /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ + MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); + + /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ + MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); + + /* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ + /* Parameters: */ + /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ + /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ + /* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ + /* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ + /* Return values: */ + /* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ + /* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ + /* MZ_STREAM_ERROR if the stream is bogus. */ + /* MZ_DATA_ERROR if the deflate stream is invalid. */ + /* MZ_PARAM_ERROR if one of the parameters is invalid. */ + /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ + /* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ + MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); + + /* Deinitializes a decompressor. */ + MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); + + /* Single-call decompression. */ + /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ + MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len); +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + + /* Returns a string description of the specified error code, or NULL if the error code is invalid. */ + MINIZ_EXPORT const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + /* See mz_alloc_func */ + typedef void *(*alloc_func)(void *opaque, size_t items, size_t size); + /* See mz_free_func */ + typedef void (*free_func)(void *opaque, void *address); + +#define internal_state mz_internal_state +#define z_stream mz_stream + +#ifndef MINIZ_NO_DEFLATE_APIS + /* Compatiblity with zlib API. See called functions for documentation */ + static MZ_FORCEINLINE int deflateInit(mz_streamp pStream, int level) + { + return mz_deflateInit(pStream, level); + } + static MZ_FORCEINLINE int deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) + { + return mz_deflateInit2(pStream, level, method, window_bits, mem_level, strategy); + } + static MZ_FORCEINLINE int deflateReset(mz_streamp pStream) + { + return mz_deflateReset(pStream); + } + static MZ_FORCEINLINE int deflate(mz_streamp pStream, int flush) + { + return mz_deflate(pStream, flush); + } + static MZ_FORCEINLINE int deflateEnd(mz_streamp pStream) + { + return mz_deflateEnd(pStream); + } + static MZ_FORCEINLINE mz_ulong deflateBound(mz_streamp pStream, mz_ulong source_len) + { + return mz_deflateBound(pStream, source_len); + } + static MZ_FORCEINLINE int compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) + { + return mz_compress(pDest, pDest_len, pSource, source_len); + } + static MZ_FORCEINLINE int compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) + { + return mz_compress2(pDest, pDest_len, pSource, source_len, level); + } + static MZ_FORCEINLINE mz_ulong compressBound(mz_ulong source_len) + { + return mz_compressBound(source_len); + } +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS + /* Compatiblity with zlib API. See called functions for documentation */ + static MZ_FORCEINLINE int inflateInit(mz_streamp pStream) + { + return mz_inflateInit(pStream); + } + + static MZ_FORCEINLINE int inflateInit2(mz_streamp pStream, int window_bits) + { + return mz_inflateInit2(pStream, window_bits); + } + + static MZ_FORCEINLINE int inflateReset(mz_streamp pStream) + { + return mz_inflateReset(pStream); + } + + static MZ_FORCEINLINE int inflate(mz_streamp pStream, int flush) + { + return mz_inflate(pStream, flush); + } + + static MZ_FORCEINLINE int inflateEnd(mz_streamp pStream) + { + return mz_inflateEnd(pStream); + } + + static MZ_FORCEINLINE int uncompress(unsigned char* pDest, mz_ulong* pDest_len, const unsigned char* pSource, mz_ulong source_len) + { + return mz_uncompress(pDest, pDest_len, pSource, source_len); + } + + static MZ_FORCEINLINE int uncompress2(unsigned char* pDest, mz_ulong* pDest_len, const unsigned char* pSource, mz_ulong* pSource_len) + { + return mz_uncompress2(pDest, pDest_len, pSource, pSource_len); + } +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + + static MZ_FORCEINLINE mz_ulong crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len) + { + return mz_crc32(crc, ptr, buf_len); + } + + static MZ_FORCEINLINE mz_ulong adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) + { + return mz_adler32(adler, ptr, buf_len); + } + +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 + + static MZ_FORCEINLINE const char* zError(int err) + { + return mz_error(err); + } +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +#include "miniz_common.h" +#include "miniz_tdef.h" +#include "miniz_tinfl.h" +#include "miniz_zip.h" diff --git a/libs/miniz/miniz_common.h b/libs/miniz/miniz_common.h new file mode 100644 index 0000000..2050d72 --- /dev/null +++ b/libs/miniz/miniz_common.h @@ -0,0 +1,89 @@ +#pragma once +#include +#include +#include +#include + +#include "miniz_export.h" + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef int16_t mz_int16; +typedef uint16_t mz_uint16; +typedef uint32_t mz_uint32; +typedef uint32_t mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + mz_uint32 m_dummy1; + mz_uint32 m_dummy2; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) +#define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj)) +#define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef __cplusplus +extern "C" +{ +#endif + + extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); + extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); + extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#ifdef __cplusplus +} +#endif diff --git a/libs/miniz/miniz_export.h b/libs/miniz/miniz_export.h new file mode 100644 index 0000000..ac40fae --- /dev/null +++ b/libs/miniz/miniz_export.h @@ -0,0 +1,9 @@ +#pragma once +// Stub for miniz_export.h — normally generated by CMake. +// We build miniz as a static source file, so no export macros are needed. +#ifndef MINIZ_EXPORT +#define MINIZ_EXPORT +#endif +#ifndef MINIZ_NO_EXPORT +#define MINIZ_NO_EXPORT +#endif diff --git a/libs/miniz/miniz_tdef.c b/libs/miniz/miniz_tdef.c new file mode 100644 index 0000000..63506f9 --- /dev/null +++ b/libs/miniz/miniz_tdef.c @@ -0,0 +1,1597 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz.h" + +#ifndef MINIZ_NO_DEFLATE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* ------------------- Low-level Compression (independent from all decompression API's) */ + + /* Purposely making these tables static for faster init and thread safety. */ + static const mz_uint16 s_tdefl_len_sym[256] = { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + + static const mz_uint8 s_tdefl_len_extra[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + + static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + + static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + + static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + + static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + + /* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ + typedef struct + { + mz_uint16 m_key, m_sym_index; + } tdefl_sym_freq; + static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) + { + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_ARR(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; + } + + /* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ + static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) + { + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } + } + + /* Limits canonical Huffman code table's max code size. */ + enum + { + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 + }; + static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) + { + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } + } + + static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) + { + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_ARR(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_ARR(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_ARR(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } + } + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + + static const mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + + static void tdefl_start_dynamic_block(tdefl_compressor *d) + { + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } + } + + static void tdefl_start_static_block(tdefl_compressor *d) + { + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); + } + + static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) + { + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0]; + mz_uint match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + memcpy(pOutput_buf, &bit_buffer, sizeof(mz_uint64)); + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); + } +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + + static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) + { + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); + } + + static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + + static int tdefl_flush_block(tdefl_compressor *d, int flush) + { + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + const mz_uint8 cmf = 0x78; + mz_uint8 flg, flevel = 3; + mz_uint header, i, mz_un = sizeof(s_tdefl_num_probes) / sizeof(mz_uint); + + /* Determine compression level by reversing the process in tdefl_create_comp_flags_from_zip_params() */ + for (i = 0; i < mz_un; i++) + if (s_tdefl_num_probes[i] == (d->m_flags & 0xFFF)) + break; + + if (i < 2) + flevel = 0; + else if (i < 6) + flevel = 1; + else if (i == 6) + flevel = 2; + + header = cmf << 8 | (flevel << 6); + header += 31 - (header % 31); + flg = header & 0xFF; + + TDEFL_PUT_BITS(cmf, 8); + TDEFL_PUT_BITS(flg, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; + } + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8 *p) + { + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; + } + static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16 *p) + { + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; + } +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif + static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) + { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } + } +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8 *p) + { + mz_uint32 ret; + memcpy(&ret, p, sizeof(mz_uint32)); + return ret; + } +#else +#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) +#endif + static mz_bool tdefl_compress_fast(tdefl_compressor *d) + { + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); +#else + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; +#endif + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; + } +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + + static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) + { + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; + } + + static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) + { + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; + } + + static mz_bool tdefl_compress_normal(tdefl_compressor *d) + { + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc ? pSrc + num_bytes_to_process : NULL; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; + } + + static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) + { + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; + } + + tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) + { + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_ARR(d->m_hash); + MZ_CLEAR_ARR(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + } + + tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) + { + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); + } + + tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) + { + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_ARR(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + *d->m_pLZ_flags = 0; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_ARR(d->m_dict); + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; + } + + tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) + { + return d->m_prev_return_status; + } + + mz_uint32 tdefl_get_adler32(tdefl_compressor *d) + { + return d->m_adler32; + } + + mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) + { + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; + } + + typedef struct + { + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; + } tdefl_output_buffer; + + static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) + { + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; + } + + void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) + { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; + } + + size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) + { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; + } + + /* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ + mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) + { + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; + } + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + + /* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ + void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) + { + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, + 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x44, 0x41, + 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; + } + void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) + { + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); + } + +#ifndef MINIZ_NO_MALLOC + /* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ + /* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ + /* structure size and allocation mechanism. */ + tdefl_compressor *tdefl_compressor_alloc(void) + { + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + } + + void tdefl_compressor_free(tdefl_compressor *pComp) + { + MZ_FREE(pComp); + } +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ diff --git a/libs/miniz/miniz_tdef.h b/libs/miniz/miniz_tdef.h new file mode 100644 index 0000000..7dc959b --- /dev/null +++ b/libs/miniz/miniz_tdef.h @@ -0,0 +1,199 @@ +#pragma once +#include "miniz_common.h" + +#ifndef MINIZ_NO_DEFLATE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#ifndef TDEFL_LESS_MEMORY +#define TDEFL_LESS_MEMORY 0 +#endif + + /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ + /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ + enum + { + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF + }; + + /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ + /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ + /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ + /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ + /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ + /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ + /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ + /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ + /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ + enum + { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 + }; + + /* High level compression functions: */ + /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ + /* On entry: */ + /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ + /* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ + /* On return: */ + /* Function returns a pointer to the compressed data, or NULL on failure. */ + /* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ + /* The caller must free() the returned block when it's no longer needed. */ + MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + + /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ + /* Returns 0 on failure. */ + MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + + /* Compresses an image to a compressed PNG file in memory. */ + /* On entry: */ + /* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ + /* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ + /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ + /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ + /* On return: */ + /* Function returns a pointer to the compressed data, or NULL on failure. */ + /* *pLen_out will be set to the size of the PNG image file. */ + /* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ + MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); + MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + + /* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ + typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + + /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ + MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + + enum + { + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 + }; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY + enum + { + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS + }; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (mz_uint)((TDEFL_LZ_CODE_BUF_SIZE * 13) / 10), + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + + /* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ + typedef enum + { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 + } tdefl_status; + + /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ + typedef enum + { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 + } tdefl_flush; + + /* tdefl's compression state structure. */ + typedef struct + { + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; + } tdefl_compressor; + + /* Initializes the compressor. */ + /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ + /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ + /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ + /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ + MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + + /* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ + MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + + /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ + /* tdefl_compress_buffer() always consumes the entire input buffer. */ + MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + + MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); + MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + + /* Create tdefl_compress() flags given zlib-style compression parameters. */ + /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ + /* window_bits may be -15 (raw deflate) or 15 (zlib) */ + /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ + MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); + +#ifndef MINIZ_NO_MALLOC + /* Allocate the tdefl_compressor structure in C so that */ + /* non-C language bindings to tdefl_ API don't need to worry about */ + /* structure size and allocation mechanism. */ + MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); + MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ diff --git a/libs/miniz/miniz_tinfl.c b/libs/miniz/miniz_tinfl.c new file mode 100644 index 0000000..a8d2a59 --- /dev/null +++ b/libs/miniz/miniz_tinfl.c @@ -0,0 +1,778 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz.h" + +#ifndef MINIZ_NO_INFLATE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree) \ + do \ + { \ + temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pLookUp, pTree) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + + static void tinfl_clear_tree(tinfl_decompressor *r) + { + if (r->m_type == 0) + MZ_CLEAR_ARR(r->m_tree_0); + else if (r->m_type == 1) + MZ_CLEAR_ARR(r->m_tree_1); + else + MZ_CLEAR_ARR(r->m_tree_2); + } + + tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) + { + static const mz_uint16 s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const mz_uint8 s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const mz_uint16 s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const mz_uint8 s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const mz_uint16 s_min_table_sizes[3] = { 257, 1, 4 }; + + mz_int16 *pTrees[3]; + mz_uint8 *pCode_sizes[3]; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next ? pOut_buf_next + *pOut_buf_size : NULL; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + pTrees[0] = r->m_tree_0; + pTrees[1] = r->m_tree_1; + pTrees[2] = r->m_tree_2; + pCode_sizes[0] = r->m_code_size_0; + pCode_sizes[1] = r->m_code_size_1; + pCode_sizes[2] = r->m_code_size_2; + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)((size_t)1 << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_code_size_0; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_code_size_1, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_ARR(r->m_code_size_2); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_code_size_2[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + mz_int16 *pLookUp; + mz_int16 *pTree; + mz_uint8 *pCode_size; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pLookUp = r->m_look_up[r->m_type]; + pTree = pTrees[r->m_type]; + pCode_size = pCode_sizes[r->m_type]; + MZ_CLEAR_ARR(total_syms); + TINFL_MEMSET(pLookUp, 0, sizeof(r->m_look_up[0])); + tinfl_clear_tree(r); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pCode_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pCode_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pLookUp[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTree[-tree_cur - 1]) + { + pTree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, r->m_look_up[2], r->m_tree_2); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_code_size_0, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_code_size_1, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, r->m_look_up[0], r->m_tree_0); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (code_len == 0) + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + if (code_len == 0) + { + TINFL_CR_RETURN_FOREVER(54, TINFL_STATUS_FAILED); + } + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, r->m_look_up[1], r->m_tree_1); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist == 0 || dist > dist_from_out_buf_start || dist_from_out_buf_start == 0) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32) * 2); +#else + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; +#endif + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + while (counter > 2) + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + counter -= 3; + } + if (counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= ~(~(tinfl_bit_buf_t)0 << num_bits); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + + common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & ~(~(tinfl_bit_buf_t)0 << num_bits); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; + } + + /* Higher level helper functions. */ + void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) + { + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; + } + + size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) + { + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; + } + + int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) + { + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + memset(pDict, 0, TINFL_LZ_DICT_SIZE); + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; + } + +#ifndef MINIZ_NO_MALLOC + tinfl_decompressor *tinfl_decompressor_alloc(void) + { + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; + } + + void tinfl_decompressor_free(tinfl_decompressor *pDecomp) + { + MZ_FREE(pDecomp); + } +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ diff --git a/libs/miniz/miniz_tinfl.h b/libs/miniz/miniz_tinfl.h new file mode 100644 index 0000000..7edca60 --- /dev/null +++ b/libs/miniz/miniz_tinfl.h @@ -0,0 +1,150 @@ +#pragma once +#include "miniz_common.h" +/* ------------------- Low-level Decompression API Definitions */ + +#ifndef MINIZ_NO_INFLATE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif + /* Decompression flags used by tinfl_decompress(). */ + /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ + /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ + /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ + /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ + enum + { + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 + }; + + /* High level decompression functions: */ + /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ + /* On entry: */ + /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ + /* On return: */ + /* Function returns a pointer to the decompressed data, or NULL on failure. */ + /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ + /* The caller must call mz_free() on the returned block when it's no longer needed. */ + MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) + MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + + /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ + /* Returns 1 on success or 0 on failure. */ + typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + + struct tinfl_decompressor_tag; + typedef struct tinfl_decompressor_tag tinfl_decompressor; + +#ifndef MINIZ_NO_MALLOC + /* Allocate the tinfl_decompressor structure in C so that */ + /* non-C language bindings to tinfl_ API don't need to worry about */ + /* structure size and allocation mechanism. */ + MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); + MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); +#endif + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + + /* Return status. */ + typedef enum + { + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 + } tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + + /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ + /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ + MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + + /* Internal/private bits follow. */ + enum + { + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS + }; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + + struct tinfl_decompressor_tag + { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE]; + mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; + mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2]; + mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2]; + mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1]; + mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; + }; + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ diff --git a/libs/miniz/miniz_zip.c b/libs/miniz/miniz_zip.c new file mode 100644 index 0000000..303c732 --- /dev/null +++ b/libs/miniz/miniz_zip.c @@ -0,0 +1,4895 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ +#include "miniz.h" + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) || defined(__MINGW32__) + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef __cplusplus +#define MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS 0 +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +static WCHAR *mz_utf8z_to_widechar(const char *str) +{ + int reqChars = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); + WCHAR *wStr = (WCHAR *)malloc(reqChars * sizeof(WCHAR)); + MultiByteToWideChar(CP_UTF8, 0, str, -1, wStr, reqChars); + return wStr; +} + +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + WCHAR *wFilename = mz_utf8z_to_widechar(pFilename); + WCHAR *wMode = mz_utf8z_to_widechar(pMode); + FILE *pFile = NULL; + errno_t err = _wfopen_s(&pFile, wFilename, wMode); + free(wFilename); + free(wMode); + return err ? NULL : pFile; +} + +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + WCHAR *wPath = mz_utf8z_to_widechar(pPath); + WCHAR *wMode = mz_utf8z_to_widechar(pMode); + FILE *pFile = NULL; + errno_t err = _wfreopen_s(&pFile, wPath, wMode, pStream); + free(wPath); + free(wMode); + return err ? NULL : pFile; +} + +#if defined(__MINGW32__) +static int mz_stat(const char *path, struct _stat *buffer) +{ + WCHAR *wPath = mz_utf8z_to_widechar(path); + int res = _wstat(wPath, buffer); + free(wPath); + return res; +} +#else +static int mz_stat64(const char *path, struct __stat64 *buffer) +{ + WCHAR *wPath = mz_utf8z_to_widechar(path); + int res = _wstat64(wPath, buffer); + free(wPath); + return res; +} +#endif + +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#if defined(__MINGW32__) +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT mz_stat +#else +#define MZ_FILE_STAT_STRUCT _stat64 +#define MZ_FILE_STAT mz_stat64 +#endif +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove + +#elif defined(__WATCOMC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__USE_LARGEFILE64) /* gcc, clang */ +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__APPLE__) || defined(__FreeBSD__) || (defined(__linux__) && defined(__x86_64__)) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + + /* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ + enum + { + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 + }; + + typedef struct + { + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; + } mz_zip_array; + + struct mz_zip_internal_state_tag + { + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + mz_uint32 m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; + }; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) + static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) + { + MZ_ASSERT(index < pArray->m_size); + return index; + } +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + + static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) + { + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; + } + + static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); + } + + static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) + { + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; + } + + static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) + { + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; + } + + static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) + { + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; + } + + static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) + { + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); + } + + static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) + { + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + if (n > 0) + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; + } + +#ifndef MINIZ_NO_TIME + static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) + { + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); + } + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) + { +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); + } +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) + { + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; + } +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + + static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) + { + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); + } +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + + static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) + { + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; + } + + static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) + { + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; + } + + static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) + { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); + } + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + + /* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ + static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) + { + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } + } + + static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) + { + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= ((mz_uint64)(MZ_UINT16_MAX) + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; + } + + static mz_bool mz_zip_reader_eocd64_valid(mz_zip_archive *pZip, uint64_t offset, uint8_t *buf) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, offset, buf, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(buf + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + return MZ_TRUE; + } + } + + return MZ_FALSE; + } + + static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) + { + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0, eocd_ofs = 0, archive_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + eocd_ofs = cur_file_ofs; + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + + if (pZip->m_pState->m_zip64) + { + /* Try locating the EOCD64 right before the EOCD64 locator. This works even + * when the effective start of the zip header is not yet known. */ + if (cur_file_ofs < MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + zip64_end_of_central_dir_ofs = cur_file_ofs - + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE - + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + if (!mz_zip_reader_eocd64_valid(pZip, zip64_end_of_central_dir_ofs, + pZip64_end_of_central_dir)) + { + /* That failed, try reading where the locator tells us to. */ + zip64_end_of_central_dir_ofs = MZ_READ_LE64( + pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + + if (zip64_end_of_central_dir_ofs > + (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_eocd64_valid(pZip, zip64_end_of_central_dir_ofs, + pZip64_end_of_central_dir)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < (mz_uint64)pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (eocd_ofs < cdir_ofs + cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* The end of central dir follows the central dir, unless the zip file has + * some trailing data (e.g. it is appended to an executable file). */ + archive_ofs = eocd_ofs - (cdir_ofs + cdir_size); + if (pZip->m_pState->m_zip64) + { + if (archive_ofs < MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + archive_ofs -= MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Update the archive start position, but only if not specified. */ + if ((pZip->m_zip_type == MZ_ZIP_TYPE_FILE || pZip->m_zip_type == MZ_ZIP_TYPE_CFILE || + pZip->m_zip_type == MZ_ZIP_TYPE_USER) && pZip->m_pState->m_file_archive_start_ofs == 0) + { + pZip->m_pState->m_file_archive_start_ofs = archive_ofs; + pZip->m_archive_size -= archive_ofs; + } + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data; + void *buf = NULL; + + if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) + { + buf = MZ_MALLOC(ext_data_size); + if (buf == NULL) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (mz_uint8 *)buf; + } + else + { + pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + } + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + + MZ_FREE(buf); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; + } + + void mz_zip_zero_struct(mz_zip_archive *pZip) + { + if (pZip) + MZ_CLEAR_PTR(pZip); + } + + static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) + { + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; + } + + mz_bool mz_zip_reader_end(mz_zip_archive *pZip) + { + return mz_zip_reader_end_internal(pZip, MZ_TRUE); + } + mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) + { + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + + static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; + } + + mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) + { + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); + } + + mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) + { + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); + } + + mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) + { + mz_uint64 file_size; + MZ_FILE *pFile; + + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_READ_ALLOW_WRITING ) ? "r+b" : "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + + mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) + { + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + +#endif /* #ifndef MINIZ_NO_STDIO */ + + static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) + { + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + } + + mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) + { + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; + } + + mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) + { + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + + mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) + { + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; + } + + static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) + { + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; + } + + static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) + { + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; + } + + static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) + { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); + } + + static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) + { + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const mz_uint32 size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + mz_uint32 file_index = pIndices[(mz_uint32)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); + } + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) + { + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; + } + + mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) + { + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); + } + + static mz_bool mz_zip_reader_extract_to_mem_no_alloc1(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size, const mz_zip_archive_file_stat *st) + { + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (st) + { + file_stat = *st; + } + else if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += (mz_uint64)(MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; + } + + mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) + { + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size, NULL); + } + + mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) + { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size, NULL); + } + + mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) + { + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, NULL, 0, NULL); + } + + mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) + { + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); + } + + void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) + { + mz_zip_archive_file_stat file_stat; + mz_uint64 alloc_size; + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return NULL; + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, (size_t)alloc_size, flags, NULL, 0, &file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; + } + + void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) + { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); + } + + mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) + { + int status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32 = MZ_CRC32_INIT; +#endif + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += (mz_uint64)(MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; + } + + mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) + { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); + } + + mz_zip_reader_extract_iter_state *mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) + { + mz_zip_reader_extract_iter_state *pState; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += (mz_uint64)(MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else + { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else + { + /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, init decompressor */ + tinfl_init(&pState->inflator); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; + } + + mz_zip_reader_extract_iter_state *mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) + { + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); + } + + size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState, void *pvBuf, size_t buf_size) + { + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data, calc amount to return. */ + copied_to_caller = (size_t)MZ_MIN(buf_size, pState->comp_remaining); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) + { + /* Copy data to caller's buffer */ + memcpy(pvBuf, pState->pRead_buf, copied_to_caller); + pState->pRead_buf = ((mz_uint8 *)pState->pRead_buf) + copied_to_caller; + } + else + { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) + { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else + { + do + { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) + { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) + { + /* Calc read size */ + pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) + { + /* Calc amount to return. */ + size_t to_copy = MZ_MIN((buf_size - copied_to_caller), pState->out_blk_remain); + + /* Copy data to caller's buffer */ + memcpy((mz_uint8 *)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ((copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT))); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; + } + + mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState) + { + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) + { + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); + } + + mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) + { + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; + } + + mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) + { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); + } + + mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) + { + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + } + + mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) + { + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) + { + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; + } + + mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) + { + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + goto handle_failure; + } + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8 *pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + + handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; + } + + mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) + { + mz_zip_internal_state *pState; + mz_uint32 i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; + } + + mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) + { + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; + } + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) + { + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + /* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + + static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) + { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + } + static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) + { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); + } + static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) + { + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); + } + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + + static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; + } + + static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) + { + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; + } + + mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) + { + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) + { + return mz_zip_writer_init_v2(pZip, existing_size, 0); + } + + mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) + { + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) + { + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); + } + + mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) + { + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); + } + + mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) + { + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_ARR(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) + { + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) + { + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE && + !(flags & MZ_ZIP_FLAG_READ_ALLOW_WRITING) ) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) + { + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); + } + + /* TODO: pArchive_name is a terrible name here! */ + mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) + { + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); + } + + typedef struct + { + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; + } mz_zip_writer_add_state; + + static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) + { + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; + } + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) + static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) + { + mz_uint8 *pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); + } + + static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) + { + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) + { + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) + { + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) + { + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + /* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/ + + return MZ_TRUE; + } + + static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) + { + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); + } + + static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) + { + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; + } + + mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) + { + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); + } + + mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) + { + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if (((mz_uint64)buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#else + (void)last_modified; +#endif /* #ifndef MINIZ_NO_TIME */ + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_ARR(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) + { + mz_uint16 gen_flags; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + mz_uint64 file_ofs = 0, cur_archive_header_file_ofs; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) ? 0 : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#else + (void)pFile_time; +#endif + + if (max_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (max_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_ARR(local_dir_header); + if (pState->m_zip64) + { + if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + else + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, NULL, + NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (max_size) + { + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (1) + { + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if (n == 0) + break; + + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + cur_archive_file_ofs += n; + } + uncomp_size = file_ofs; + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + + if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + if (n == 0) + flush = TDEFL_FINISH; + + status = tdefl_compress_buffer(pComp, pRead_buf, n, flush); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + uncomp_size = file_ofs; + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + { + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, + (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size, + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size, + uncomp_crc32, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + cur_archive_header_file_ofs = local_dir_header_ofs; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + if (pExtra_data != NULL) + { + cur_archive_header_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_header_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_header_file_ofs += extra_size; + } + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; + } + +#ifndef MINIZ_NO_STDIO + + static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) + { + MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pSrc_file); + } + + mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) + { + return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size, pFile_time, pComment, comment_size, level_and_flags, + user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len); + } + + mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) + { + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, mz_uint32 ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) + { + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; + } + + /* TODO: This func is now pretty freakin complex due to zip64, split it up? */ + mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) + { + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = src_file_stat.m_comp_size + local_header_filename_size + local_header_extra_len; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + const mz_uint8 *pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint8 *pSrc_descriptor = (const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0); + const mz_uint32 src_crc32 = MZ_READ_LE32(pSrc_descriptor); + const mz_uint64 src_comp_size = MZ_READ_LE32(pSrc_descriptor + sizeof(mz_uint32)); + const mz_uint64 src_uncomp_size = MZ_READ_LE32(pSrc_descriptor + 2 * sizeof(mz_uint32)); + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) + { + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((mz_uint64)pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; + } + + mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) + { + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_end(mz_zip_archive *pZip) + { + return mz_zip_writer_end_internal(pZip, MZ_TRUE); + } + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) + { + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); + } + + mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) + { + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY | MZ_ZIP_FLAG_READ_ALLOW_WRITING, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_READ_ALLOW_WRITING)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; + } + + void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) + { + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; + } + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) + { + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); + } + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + + /* ------------------- Misc utils */ + + mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) + { + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; + } + + mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) + { + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; + } + + mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) + { + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; + } + + mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) + { + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; + } + + mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) + { + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); + } + + mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) + { + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; + } + + const char *mz_zip_get_error_string(mz_zip_error mz_err) + { + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write callback failed"; + case MZ_ZIP_TOTAL_ERRORS: + return "total errors"; + default: + break; + } + + return "unknown error"; + } + + /* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ + mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) + { + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; + } + + size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) + { + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; + } + + mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) + { + return pZip ? pZip->m_total_files : 0; + } + + mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) + { + if (!pZip) + return 0; + return pZip->m_archive_size; + } + + mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) + { + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; + } + + MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) + { + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; + } + + size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) + { + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); + } + + mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) + { + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; + } + + mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) + { + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); + } + + mz_bool mz_zip_end(mz_zip_archive *pZip) + { + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; + } + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ diff --git a/libs/miniz/miniz_zip.h b/libs/miniz/miniz_zip.h new file mode 100644 index 0000000..ccdb990 --- /dev/null +++ b/libs/miniz/miniz_zip.h @@ -0,0 +1,454 @@ + +#pragma once +#include "miniz_common.h" + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" +{ +#endif + + enum + { + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 + }; + + typedef struct + { + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +#ifdef MINIZ_NO_TIME + MZ_TIME_T m_padding; +#else + MZ_TIME_T m_time; +#endif + } mz_zip_archive_file_stat; + + typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); + typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); + + struct mz_zip_internal_state_tag; + typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + + typedef enum + { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 + } mz_zip_mode; + + typedef enum + { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, + /*After adding a compressed file, seek back + to local file header and set the correct sizes*/ + MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000, + MZ_ZIP_FLAG_READ_ALLOW_WRITING = 0x40000 + } mz_zip_flags; + + typedef enum + { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES + } mz_zip_type; + + /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ + typedef enum + { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS + } mz_zip_error; + + typedef struct + { + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + + } mz_zip_archive; + + typedef struct + { + mz_zip_archive *pZip; + mz_uint flags; + + int status; + + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + void *pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +#ifdef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint padding; +#else + mz_uint file_crc32; +#endif + + } mz_zip_reader_extract_iter_state; + + /* -------- ZIP reading */ + + /* Inits a ZIP archive reader. */ + /* These functions read and validate the archive's central directory. */ + MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + + MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO + /* Read a archive from a disk file. */ + /* file_start_ofs is the file offset where the archive actually begins, or 0. */ + /* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ + MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); + MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + + /* Read an archive from an already opened FILE, beginning at the current file position. */ + /* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ + /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ + MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + + /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ + MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + + /* -------- ZIP reading or writing */ + + /* Clears a mz_zip_archive struct to all zeros. */ + /* Important: This must be done before passing the struct to any mz_zip functions. */ + MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); + + MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); + MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + + /* Returns the total number of files in the archive. */ + MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + + MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); + MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); + MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + + /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ + MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + + /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ + /* Note that the m_last_error functionality is not thread safe. */ + MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); + MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); + MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); + MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); + MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); + + /* MZ_TRUE if the archive file entry is a directory entry. */ + MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + + /* MZ_TRUE if the file is encrypted/strong encrypted. */ + MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + + /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ + MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + + /* Retrieves the filename of an archive file entry. */ + /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ + MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + + /* Attempts to locates a file in the archive's central directory. */ + /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ + /* Returns -1 if the file cannot be found. */ + MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + + /* Returns detailed information about an archive file entry. */ + MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + + /* MZ_TRUE if the file is in zip64 format. */ + /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ + MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + + /* Returns the total central directory size in bytes. */ + /* The current max supported size is <= MZ_UINT32_MAX. */ + MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + + /* Extracts a archive file to a memory buffer using no memory allocation. */ + /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ + MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + + /* Extracts a archive file to a memory buffer. */ + MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + + /* Extracts a archive file to a dynamically allocated heap buffer. */ + /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ + /* Returns NULL and sets the last error on failure. */ + MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); + MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + + /* Extracts a archive file using a callback function to output the file's data. */ + MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + + /* Extract a file iteratively */ + MINIZ_EXPORT mz_zip_reader_extract_iter_state *mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + MINIZ_EXPORT mz_zip_reader_extract_iter_state *mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState, void *pvBuf, size_t buf_size); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState); + +#ifndef MINIZ_NO_STDIO + /* Extracts a archive file to a disk file and sets its last accessed and modified times. */ + /* This function only extracts files, not archive directory records. */ + MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + + /* Extracts a archive file starting at the current position in the destination FILE stream. */ + MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + mz_uint64 mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_uint64 mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, mz_uint64 new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + + /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ + /* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ + MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + + /* Validates an entire archive by calling mz_zip_validate_file() on each file. */ + MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + + /* Misc utils/helpers, valid for ZIP reading or writing */ + MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +#ifndef MINIZ_NO_STDIO + MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); +#endif + + /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ + MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); + + /* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + + /* Inits a ZIP archive writer. */ + /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ + /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ + MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); + MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); + + MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO + MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); + MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); + MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + + /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ + /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ + /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ + /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ + /* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ + /* the archive is finalized the file's central directory will be hosed. */ + MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + + /* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ + /* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ + MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + + /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ + /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ + MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + + MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + + /* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ + /* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ + MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +#ifndef MINIZ_NO_STDIO + /* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ + MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ + MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + + /* Adds a file to an archive by fully cloning the data from another archive. */ + /* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ + MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + + /* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ + /* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ + /* An archive must be manually finalized by calling this function for it to be valid. */ + MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + + /* Finalizes a heap archive, returning a pointer to the heap block and its size. */ + /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ + MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + + /* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ + /* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ + MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + + /* -------- Misc. high-level helper functions: */ + + /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ + /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ + /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ + /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ + MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +#ifndef MINIZ_NO_STDIO + /* Reads a single file from an archive into a heap block. */ + /* If pComment is not NULL, only the file with the specified comment will be extracted. */ + /* Returns NULL on failure. */ + MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); + MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); +#endif + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifdef __cplusplus +} +#endif + +#endif /* MINIZ_NO_ARCHIVE_APIS */ diff --git a/libs/qrcode/BitBuffer.cpp b/libs/qrcode/BitBuffer.cpp new file mode 100644 index 0000000..e22e9d3 --- /dev/null +++ b/libs/qrcode/BitBuffer.cpp @@ -0,0 +1,41 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#include +#include "BitBuffer.hpp" + + +namespace qrcodegen { + +BitBuffer::BitBuffer() + : std::vector() {} + + +void BitBuffer::appendBits(std::uint32_t val, int len) { + if (len < 0 || len > 31 || val >> len != 0) + throw std::domain_error("Value out of range"); + for (int i = len - 1; i >= 0; i--) // Append bit by bit + this->push_back(((val >> i) & 1) != 0); +} + +} diff --git a/libs/qrcode/BitBuffer.hpp b/libs/qrcode/BitBuffer.hpp new file mode 100644 index 0000000..f30913a --- /dev/null +++ b/libs/qrcode/BitBuffer.hpp @@ -0,0 +1,52 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#pragma once + +#include +#include + + +namespace qrcodegen { + +/* + * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. + */ +class BitBuffer final : public std::vector { + + /*---- Constructor ----*/ + + // Creates an empty bit buffer (length 0). + public: BitBuffer(); + + + + /*---- Method ----*/ + + // Appends the given number of low-order bits of the given value + // to this buffer. Requires 0 <= len <= 31 and val < 2^len. + public: void appendBits(std::uint32_t val, int len); + +}; + +} diff --git a/libs/qrcode/QrCode.cpp b/libs/qrcode/QrCode.cpp new file mode 100644 index 0000000..0a8b12f --- /dev/null +++ b/libs/qrcode/QrCode.cpp @@ -0,0 +1,620 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "BitBuffer.hpp" +#include "QrCode.hpp" + +using std::int8_t; +using std::uint8_t; +using std::size_t; +using std::vector; + + +namespace qrcodegen { + +int QrCode::getFormatBits(Ecc ecl) { + switch (ecl) { + case Ecc::LOW : return 1; + case Ecc::MEDIUM : return 0; + case Ecc::QUARTILE: return 3; + case Ecc::HIGH : return 2; + default: throw std::logic_error("Assertion error"); + } +} + + +QrCode QrCode::encodeText(const char *text, Ecc ecl) { + vector segs = QrSegment::makeSegments(text); + return encodeSegments(segs, ecl); +} + + +QrCode QrCode::encodeBinary(const vector &data, Ecc ecl) { + vector segs{QrSegment::makeBytes(data)}; + return encodeSegments(segs, ecl); +} + + +QrCode QrCode::encodeSegments(const vector &segs, Ecc ecl, + int minVersion, int maxVersion, int mask, bool boostEcl) { + if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) + throw std::invalid_argument("Invalid value"); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = QrSegment::getTotalBits(segs, version); + if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) // All versions in the range could not fit the given data + throw std::length_error("Data too long"); + } + if (dataUsedBits == -1) + throw std::logic_error("Assertion error"); + + // Increase the error correction level while the data still fits in the current version number + for (Ecc newEcl : vector{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) + ecl = newEcl; + } + + // Concatenate all segments to create the data bit string + BitBuffer bb; + for (const QrSegment &seg : segs) { + bb.appendBits(seg.getMode().getModeBits(), 4); + bb.appendBits(seg.getNumChars(), seg.getMode().numCharCountBits(version)); + bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); + } + if (bb.size() != static_cast(dataUsedBits)) + throw std::logic_error("Assertion error"); + + // Add terminator and pad up to a byte if applicable + size_t dataCapacityBits = getNumDataCodewords(version, ecl) * 8; + if (bb.size() > dataCapacityBits) + throw std::logic_error("Assertion error"); + bb.appendBits(0, std::min(4, dataCapacityBits - bb.size())); + bb.appendBits(0, (8 - bb.size() % 8) % 8); + if (bb.size() % 8 != 0) + throw std::logic_error("Assertion error"); + + // Pad with alternating bytes until data capacity is reached + for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + bb.appendBits(padByte, 8); + + // Pack bits into bytes in big endian + vector dataCodewords(bb.size() / 8); + for (size_t i = 0; i < bb.size(); i++) + dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); + + // Create the QR Code object + return QrCode(version, ecl, dataCodewords, mask); +} + + +QrCode::QrCode(int ver, Ecc ecl, const vector &dataCodewords, int mask) : + // Initialize fields and check arguments + version(ver), + errorCorrectionLevel(ecl) { + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw std::domain_error("Version value out of range"); + if (mask < -1 || mask > 7) + throw std::domain_error("Mask value out of range"); + size = ver * 4 + 17; + modules = vector >(size, vector(size)); // Initially all white + isFunction = vector >(size, vector(size)); + + // Compute ECC, draw modules, do masking + drawFunctionPatterns(); + const vector allCodewords = addEccAndInterleave(dataCodewords); + drawCodewords(allCodewords); + this->mask = handleConstructorMasking(mask); + isFunction.clear(); + isFunction.shrink_to_fit(); +} + + +int QrCode::getVersion() const { + return version; +} + + +int QrCode::getSize() const { + return size; +} + + +QrCode::Ecc QrCode::getErrorCorrectionLevel() const { + return errorCorrectionLevel; +} + + +int QrCode::getMask() const { + return mask; +} + + +bool QrCode::getModule(int x, int y) const { + return 0 <= x && x < size && 0 <= y && y < size && module(x, y); +} + + +std::string QrCode::toSvgString(int border) const { + if (border < 0) + throw std::domain_error("Border must be non-negative"); + if (border > INT_MAX / 2 || border * 2 > INT_MAX - size) + throw std::overflow_error("Border too large"); + + std::ostringstream sb; + sb << "\n"; + sb << "\n"; + sb << "\n"; + sb << "\t\n"; + sb << "\t\n"; + sb << "\n"; + return sb.str(); +} + + +void QrCode::drawFunctionPatterns() { + // Draw horizontal and vertical timing patterns + for (int i = 0; i < size; i++) { + setFunctionModule(6, i, i % 2 == 0); + setFunctionModule(i, 6, i % 2 == 0); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + drawFinderPattern(3, 3); + drawFinderPattern(size - 4, 3); + drawFinderPattern(3, size - 4); + + // Draw numerous alignment patterns + const vector alignPatPos = getAlignmentPatternPositions(); + int numAlign = alignPatPos.size(); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) + drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); + } + } + + // Draw configuration data + drawFormatBits(0); // Dummy mask value; overwritten later in the constructor + drawVersion(); +} + + +void QrCode::drawFormatBits(int mask) { + // Calculate error correction code and pack bits + int data = getFormatBits(errorCorrectionLevel) << 3 | mask; // errCorrLvl is uint2, mask is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + if (bits >> 15 != 0) + throw std::logic_error("Assertion error"); + + // Draw first copy + for (int i = 0; i <= 5; i++) + setFunctionModule(8, i, getBit(bits, i)); + setFunctionModule(8, 7, getBit(bits, 6)); + setFunctionModule(8, 8, getBit(bits, 7)); + setFunctionModule(7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setFunctionModule(14 - i, 8, getBit(bits, i)); + + // Draw second copy + for (int i = 0; i <= 7; i++) + setFunctionModule(size - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setFunctionModule(8, size - 15 + i, getBit(bits, i)); + setFunctionModule(8, size - 8, true); // Always black +} + + +void QrCode::drawVersion() { + if (version < 7) + return; + + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + long bits = (long)version << 12 | rem; // uint18 + if (bits >> 18 != 0) + throw std::logic_error("Assertion error"); + + // Draw two copies + for (int i = 0; i < 18; i++) { + bool bit = getBit(bits, i); + int a = size - 11 + i % 3; + int b = i / 3; + setFunctionModule(a, b, bit); + setFunctionModule(b, a, bit); + } +} + + +void QrCode::drawFinderPattern(int x, int y) { + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm + int xx = x + dx, yy = y + dy; + if (0 <= xx && xx < size && 0 <= yy && yy < size) + setFunctionModule(xx, yy, dist != 2 && dist != 4); + } + } +} + + +void QrCode::drawAlignmentPattern(int x, int y) { + for (int dy = -2; dy <= 2; dy++) { + for (int dx = -2; dx <= 2; dx++) + setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); + } +} + + +void QrCode::setFunctionModule(int x, int y, bool isBlack) { + modules.at(y).at(x) = isBlack; + isFunction.at(y).at(x) = true; +} + + +bool QrCode::module(int x, int y) const { + return modules.at(y).at(x); +} + + +vector QrCode::addEccAndInterleave(const vector &data) const { + if (data.size() != static_cast(getNumDataCodewords(version, errorCorrectionLevel))) + throw std::invalid_argument("Invalid argument"); + + // Calculate parameter numbers + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast(errorCorrectionLevel)][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast(errorCorrectionLevel)][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockLen = rawCodewords / numBlocks; + + // Split data into blocks and append ECC to each block + vector > blocks; + const ReedSolomonGenerator rs(blockEccLen); + for (int i = 0, k = 0; i < numBlocks; i++) { + vector dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); + k += dat.size(); + const vector ecc = rs.getRemainder(dat); + if (i < numShortBlocks) + dat.push_back(0); + dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); + blocks.push_back(std::move(dat)); + } + + // Interleave (not concatenate) the bytes from every block into a single sequence + vector result; + for (size_t i = 0; i < blocks.at(0).size(); i++) { + for (size_t j = 0; j < blocks.size(); j++) { + // Skip the padding byte in short blocks + if (i != static_cast(shortBlockLen - blockEccLen) || j >= static_cast(numShortBlocks)) + result.push_back(blocks.at(j).at(i)); + } + } + if (result.size() != static_cast(rawCodewords)) + throw std::logic_error("Assertion error"); + return result; +} + + +void QrCode::drawCodewords(const vector &data) { + if (data.size() != static_cast(getNumRawDataModules(version) / 8)) + throw std::invalid_argument("Invalid argument"); + + size_t i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < size; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + int x = right - j; // Actual x coordinate + bool upward = ((right + 1) & 2) == 0; + int y = upward ? size - 1 - vert : vert; // Actual y coordinate + if (!isFunction.at(y).at(x) && i < data.size() * 8) { + modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast(i & 7)); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/white by the constructor and are left unchanged by this method + } + } + } + if (i != data.size() * 8) + throw std::logic_error("Assertion error"); +} + + +void QrCode::applyMask(int mask) { + if (mask < 0 || mask > 7) + throw std::domain_error("Mask value out of range"); + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + bool invert; + switch (mask) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: throw std::logic_error("Assertion error"); + } + modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); + } + } +} + + +int QrCode::handleConstructorMasking(int mask) { + if (mask == -1) { // Automatically choose best mask + long minPenalty = LONG_MAX; + for (int i = 0; i < 8; i++) { + drawFormatBits(i); + applyMask(i); + long penalty = getPenaltyScore(); + if (penalty < minPenalty) { + mask = i; + minPenalty = penalty; + } + applyMask(i); // Undoes the mask due to XOR + } + } + if (mask < 0 || mask > 7) + throw std::logic_error("Assertion error"); + drawFormatBits(mask); // Overwrite old format bits + applyMask(mask); // Apply the final choice of mask + return mask; // The caller shall assign this value to the final-declared field +} + + +long QrCode::getPenaltyScore() const { + long result = 0; + + // Adjacent modules in row having same color + for (int y = 0; y < size; y++) { + bool colorX = false; + for (int x = 0, runX = -1; x < size; x++) { + if (x == 0 || module(x, y) != colorX) { + colorX = module(x, y); + runX = 1; + } else { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } + } + } + // Adjacent modules in column having same color + for (int x = 0; x < size; x++) { + bool colorY = false; + for (int y = 0, runY = -1; y < size; y++) { + if (y == 0 || module(x, y) != colorY) { + colorY = module(x, y); + runY = 1; + } else { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } + } + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < size - 1; y++) { + for (int x = 0; x < size - 1; x++) { + bool color = module(x, y); + if ( color == module(x + 1, y) && + color == module(x, y + 1) && + color == module(x + 1, y + 1)) + result += PENALTY_N2; + } + } + + // Finder-like pattern in rows + for (int y = 0; y < size; y++) { + for (int x = 0, bits = 0; x < size; x++) { + bits = ((bits << 1) & 0x7FF) | (module(x, y) ? 1 : 0); + if (x >= 10 && (bits == 0x05D || bits == 0x5D0)) // Needs 11 bits accumulated + result += PENALTY_N3; + } + } + // Finder-like pattern in columns + for (int x = 0; x < size; x++) { + for (int y = 0, bits = 0; y < size; y++) { + bits = ((bits << 1) & 0x7FF) | (module(x, y) ? 1 : 0); + if (y >= 10 && (bits == 0x05D || bits == 0x5D0)) // Needs 11 bits accumulated + result += PENALTY_N3; + } + } + + // Balance of black and white modules + int black = 0; + for (const vector &row : modules) { + for (bool color : row) { + if (color) + black++; + } + } + int total = size * size; // Note that size is odd, so black/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% + int k = static_cast((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1; + result += k * PENALTY_N4; + return result; +} + + +vector QrCode::getAlignmentPatternPositions() const { + if (version == 1) + return vector(); + else { + int numAlign = version / 7 + 2; + int step = (version == 32) ? 26 : + (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; + vector result; + for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) + result.insert(result.begin(), pos); + result.insert(result.begin(), 6); + return result; + } +} + + +int QrCode::getNumRawDataModules(int ver) { + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw std::domain_error("Version number out of range"); + int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + return result; +} + + +int QrCode::getNumDataCodewords(int ver, Ecc ecl) { + return getNumRawDataModules(ver) / 8 + - ECC_CODEWORDS_PER_BLOCK [static_cast(ecl)][ver] + * NUM_ERROR_CORRECTION_BLOCKS[static_cast(ecl)][ver]; +} + + +bool QrCode::getBit(long x, int i) { + return ((x >> i) & 1) != 0; +} + + +/*---- Tables of constants ----*/ + +const int QrCode::PENALTY_N1 = 3; +const int QrCode::PENALTY_N2 = 3; +const int QrCode::PENALTY_N3 = 40; +const int QrCode::PENALTY_N4 = 10; + + +const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low + {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium + {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile + {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High +}; + +const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low + {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium + {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile + {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High +}; + + +QrCode::ReedSolomonGenerator::ReedSolomonGenerator(int degree) : + coefficients() { + if (degree < 1 || degree > 255) + throw std::domain_error("Degree out of range"); + + // Start with the monomial x^0 + coefficients.resize(degree); + coefficients.at(degree - 1) = 1; + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // drop the highest term, and store the rest of the coefficients in order of descending powers. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + uint8_t root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (size_t j = 0; j < coefficients.size(); j++) { + coefficients.at(j) = multiply(coefficients.at(j), root); + if (j + 1 < coefficients.size()) + coefficients.at(j) ^= coefficients.at(j + 1); + } + root = multiply(root, 0x02); + } +} + + +vector QrCode::ReedSolomonGenerator::getRemainder(const vector &data) const { + // Compute the remainder by performing polynomial division + vector result(coefficients.size()); + for (uint8_t b : data) { + uint8_t factor = b ^ result.at(0); + result.erase(result.begin()); + result.push_back(0); + for (size_t j = 0; j < result.size(); j++) + result.at(j) ^= multiply(coefficients.at(j), factor); + } + return result; +} + + +uint8_t QrCode::ReedSolomonGenerator::multiply(uint8_t x, uint8_t y) { + // Russian peasant multiplication + int z = 0; + for (int i = 7; i >= 0; i--) { + z = (z << 1) ^ ((z >> 7) * 0x11D); + z ^= ((y >> i) & 1) * x; + } + if (z >> 8 != 0) + throw std::logic_error("Assertion error"); + return static_cast(z); +} + +} diff --git a/libs/qrcode/QrCode.hpp b/libs/qrcode/QrCode.hpp new file mode 100644 index 0000000..1904844 --- /dev/null +++ b/libs/qrcode/QrCode.hpp @@ -0,0 +1,351 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#pragma once + +#include +#include +#include +#include "QrSegment.hpp" + + +namespace qrcodegen { + +/* + * A QR Code symbol, which is a type of two-dimension barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * Instances of this class represent an immutable square grid of black and white cells. + * The class provides static factory functions to create a QR Code from text or binary data. + * The class covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). + * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). + * - Low level: Custom-make the array of data codeword bytes (including + * segment headers and final padding, excluding error correction codewords), + * supply the appropriate version number, and call the QrCode() constructor. + * (Note that all ways require supplying the desired error correction level.) + */ +class QrCode final { + + /*---- Public helper enumeration ----*/ + + /* + * The error correction level in a QR Code symbol. + */ + public: enum class Ecc { + LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords + MEDIUM , // The QR Code can tolerate about 15% erroneous codewords + QUARTILE, // The QR Code can tolerate about 25% erroneous codewords + HIGH , // The QR Code can tolerate about 30% erroneous codewords + }; + + + // Returns a value in the range 0 to 3 (unsigned 2-bit integer). + private: static int getFormatBits(Ecc ecl); + + + + /*---- Static factory functions (high level) ----*/ + + /* + * Returns a QR Code representing the given Unicode text string at the given error correction level. + * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer + * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible + * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than + * the ecl argument if it can be done without increasing the version. + */ + public: static QrCode encodeText(const char *text, Ecc ecl); + + + /* + * Returns a QR Code representing the given binary data at the given error correction level. + * This function always encodes using the binary segment mode, not any text mode. The maximum number of + * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. + * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. + */ + public: static QrCode encodeBinary(const std::vector &data, Ecc ecl); + + + /*---- Static factory functions (mid level) ----*/ + + /* + * Returns a QR Code representing the given segments with the given encoding parameters. + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask number is either between 0 to 7 (inclusive) to force that + * mask, or -1 to automatically choose an appropriate mask (which may be slow). + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a mid-level API; the high-level API is encodeText() and encodeBinary(). + */ + public: static QrCode encodeSegments(const std::vector &segs, Ecc ecl, + int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters + + + + /*---- Instance fields ----*/ + + // Immutable scalar parameters: + + /* The version number of this QR Code, which is between 1 and 40 (inclusive). + * This determines the size of this barcode. */ + private: int version; + + /* The width and height of this QR Code, measured in modules, between + * 21 and 177 (inclusive). This is equal to version * 4 + 17. */ + private: int size; + + /* The error correction level used in this QR Code. */ + private: Ecc errorCorrectionLevel; + + /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). + * Even if a QR Code is created with automatic masking requested (mask = -1), + * the resulting object still has a mask value between 0 and 7. */ + private: int mask; + + // Private grids of modules/pixels, with dimensions of size*size: + + // The modules of this QR Code (false = white, true = black). + // Immutable after constructor finishes. Accessed through getModule(). + private: std::vector > modules; + + // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. + private: std::vector > isFunction; + + + + /*---- Constructor (low level) ----*/ + + /* + * Creates a new QR Code with the given version number, + * error correction level, data codeword bytes, and mask number. + * This is a low-level API that most users should not use directly. + * A mid-level API is the encodeSegments() function. + */ + public: QrCode(int ver, Ecc ecl, const std::vector &dataCodewords, int mask); + + + + /*---- Public instance methods ----*/ + + /* + * Returns this QR Code's version, in the range [1, 40]. + */ + public: int getVersion() const; + + + /* + * Returns this QR Code's size, in the range [21, 177]. + */ + public: int getSize() const; + + + /* + * Returns this QR Code's error correction level. + */ + public: Ecc getErrorCorrectionLevel() const; + + + /* + * Returns this QR Code's mask, in the range [0, 7]. + */ + public: int getMask() const; + + + /* + * Returns the color of the module (pixel) at the given coordinates, which is false + * for white or true for black. The top left corner has the coordinates (x=0, y=0). + * If the given coordinates are out of bounds, then false (white) is returned. + */ + public: bool getModule(int x, int y) const; + + + /* + * Returns a string of SVG code for an image depicting this QR Code, with the given number + * of border modules. The string always uses Unix newlines (\n), regardless of the platform. + */ + public: std::string toSvgString(int border) const; + + + + /*---- Private helper methods for constructor: Drawing function modules ----*/ + + // Reads this object's version field, and draws and marks all function modules. + private: void drawFunctionPatterns(); + + + // Draws two copies of the format bits (with its own error correction code) + // based on the given mask and this object's error correction level field. + private: void drawFormatBits(int mask); + + + // Draws two copies of the version bits (with its own error correction code), + // based on this object's version field, iff 7 <= version <= 40. + private: void drawVersion(); + + + // Draws a 9*9 finder pattern including the border separator, + // with the center module at (x, y). Modules can be out of bounds. + private: void drawFinderPattern(int x, int y); + + + // Draws a 5*5 alignment pattern, with the center module + // at (x, y). All modules must be in bounds. + private: void drawAlignmentPattern(int x, int y); + + + // Sets the color of a module and marks it as a function module. + // Only used by the constructor. Coordinates must be in bounds. + private: void setFunctionModule(int x, int y, bool isBlack); + + + // Returns the color of the module at the given coordinates, which must be in range. + private: bool module(int x, int y) const; + + + /*---- Private helper methods for constructor: Codewords and masking ----*/ + + // Returns a new byte string representing the given data with the appropriate error correction + // codewords appended to it, based on this object's version and error correction level. + private: std::vector addEccAndInterleave(const std::vector &data) const; + + + // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire + // data area of this QR Code. Function modules need to be marked off before this is called. + private: void drawCodewords(const std::vector &data); + + + // XORs the codeword modules in this QR Code with the given mask pattern. + // The function modules must be marked and the codeword bits must be drawn + // before masking. Due to the arithmetic of XOR, calling applyMask() with + // the same mask value a second time will undo the mask. A final well-formed + // QR Code needs exactly one (not zero, two, etc.) mask applied. + private: void applyMask(int mask); + + + // A messy helper function for the constructors. This QR Code must be in an unmasked state when this + // method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed. + // This method applies and returns the actual mask chosen, from 0 to 7. + private: int handleConstructorMasking(int mask); + + + // Calculates and returns the penalty score based on state of this QR Code's current modules. + // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. + private: long getPenaltyScore() const; + + + + /*---- Private helper functions ----*/ + + // Returns an ascending list of positions of alignment patterns for this version number. + // Each position is in the range [0,177), and are used on both the x and y axes. + // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. + private: std::vector getAlignmentPatternPositions() const; + + + // Returns the number of data bits that can be stored in a QR Code of the given version number, after + // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. + // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. + private: static int getNumRawDataModules(int ver); + + + // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any + // QR Code of the given version number and error correction level, with remainder bits discarded. + // This stateless pure function could be implemented as a (40*4)-cell lookup table. + private: static int getNumDataCodewords(int ver, Ecc ecl); + + + // Returns true iff the i'th bit of x is set to 1. + private: static bool getBit(long x, int i); + + + /*---- Constants and tables ----*/ + + // The minimum version number supported in the QR Code Model 2 standard. + public: static constexpr int MIN_VERSION = 1; + + // The maximum version number supported in the QR Code Model 2 standard. + public: static constexpr int MAX_VERSION = 40; + + + // For use in getPenaltyScore(), when evaluating which mask is best. + private: static const int PENALTY_N1; + private: static const int PENALTY_N2; + private: static const int PENALTY_N3; + private: static const int PENALTY_N4; + + + private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; + private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; + + + + /*---- Private helper class ----*/ + + /* + * Computes the Reed-Solomon error correction codewords for a sequence of data codewords + * at a given degree. Objects are immutable, and the state only depends on the degree. + * This class exists because each data block in a QR Code shares the same the divisor polynomial. + */ + private: class ReedSolomonGenerator final { + + /*-- Immutable field --*/ + + // Coefficients of the divisor polynomial, stored from highest to lowest power, excluding the leading term which + // is always 1. For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + private: std::vector coefficients; + + + /*-- Constructor --*/ + + /* + * Creates a Reed-Solomon ECC generator for the given degree. This could be implemented + * as a lookup table over all possible parameter values, instead of as an algorithm. + */ + public: explicit ReedSolomonGenerator(int degree); + + + /*-- Method --*/ + + /* + * Computes and returns the Reed-Solomon error correction codewords for the given + * sequence of data codewords. The returned object is always a new byte array. + * This method does not alter this object's state (because it is immutable). + */ + public: std::vector getRemainder(const std::vector &data) const; + + + /*-- Static function --*/ + + // Returns the product of the two given field elements modulo GF(2^8/0x11D). + // All inputs are valid. This could be implemented as a 256*256 lookup table. + private: static std::uint8_t multiply(std::uint8_t x, std::uint8_t y); + + }; + +}; + +} diff --git a/libs/qrcode/QrSegment.cpp b/libs/qrcode/QrSegment.cpp new file mode 100644 index 0000000..64d77f7 --- /dev/null +++ b/libs/qrcode/QrSegment.cpp @@ -0,0 +1,225 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#include +#include +#include +#include +#include "QrSegment.hpp" + +using std::uint8_t; +using std::vector; + + +namespace qrcodegen { + +QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : + modeBits(mode) { + numBitsCharCount[0] = cc0; + numBitsCharCount[1] = cc1; + numBitsCharCount[2] = cc2; +} + + +int QrSegment::Mode::getModeBits() const { + return modeBits; +} + + +int QrSegment::Mode::numCharCountBits(int ver) const { + return numBitsCharCount[(ver + 7) / 17]; +} + + +const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); +const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); +const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); +const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); +const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); + + + +QrSegment QrSegment::makeBytes(const vector &data) { + if (data.size() > static_cast(INT_MAX)) + throw std::length_error("Data too long"); + BitBuffer bb; + for (uint8_t b : data) + bb.appendBits(b, 8); + return QrSegment(Mode::BYTE, static_cast(data.size()), std::move(bb)); +} + + +QrSegment QrSegment::makeNumeric(const char *digits) { + BitBuffer bb; + int accumData = 0; + int accumCount = 0; + int charCount = 0; + for (; *digits != '\0'; digits++, charCount++) { + char c = *digits; + if (c < '0' || c > '9') + throw std::domain_error("String contains non-numeric characters"); + accumData = accumData * 10 + (c - '0'); + accumCount++; + if (accumCount == 3) { + bb.appendBits(accumData, 10); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 or 2 digits remaining + bb.appendBits(accumData, accumCount * 3 + 1); + return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); +} + + +QrSegment QrSegment::makeAlphanumeric(const char *text) { + BitBuffer bb; + int accumData = 0; + int accumCount = 0; + int charCount = 0; + for (; *text != '\0'; text++, charCount++) { + const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); + if (temp == nullptr) + throw std::domain_error("String contains unencodable characters in alphanumeric mode"); + accumData = accumData * 45 + (temp - ALPHANUMERIC_CHARSET); + accumCount++; + if (accumCount == 2) { + bb.appendBits(accumData, 11); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 character remaining + bb.appendBits(accumData, 6); + return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); +} + + +vector QrSegment::makeSegments(const char *text) { + // Select the most efficient segment encoding automatically + vector result; + if (*text == '\0'); // Leave result empty + else if (isNumeric(text)) + result.push_back(makeNumeric(text)); + else if (isAlphanumeric(text)) + result.push_back(makeAlphanumeric(text)); + else { + vector bytes; + for (; *text != '\0'; text++) + bytes.push_back(static_cast(*text)); + result.push_back(makeBytes(bytes)); + } + return result; +} + + +QrSegment QrSegment::makeEci(long assignVal) { + BitBuffer bb; + if (assignVal < 0) + throw std::domain_error("ECI assignment value out of range"); + else if (assignVal < (1 << 7)) + bb.appendBits(assignVal, 8); + else if (assignVal < (1 << 14)) { + bb.appendBits(2, 2); + bb.appendBits(assignVal, 14); + } else if (assignVal < 1000000L) { + bb.appendBits(6, 3); + bb.appendBits(assignVal, 21); + } else + throw std::domain_error("ECI assignment value out of range"); + return QrSegment(Mode::ECI, 0, std::move(bb)); +} + + +QrSegment::QrSegment(Mode md, int numCh, const std::vector &dt) : + mode(md), + numChars(numCh), + data(dt) { + if (numCh < 0) + throw std::domain_error("Invalid value"); +} + + +QrSegment::QrSegment(Mode md, int numCh, std::vector &&dt) : + mode(md), + numChars(numCh), + data(std::move(dt)) { + if (numCh < 0) + throw std::domain_error("Invalid value"); +} + + +int QrSegment::getTotalBits(const vector &segs, int version) { + int result = 0; + for (const QrSegment &seg : segs) { + int ccbits = seg.mode.numCharCountBits(version); + if (seg.numChars >= (1L << ccbits)) + return -1; // The segment's length doesn't fit the field's bit width + if (4 + ccbits > INT_MAX - result) + return -1; // The sum will overflow an int type + result += 4 + ccbits; + if (seg.data.size() > static_cast(INT_MAX - result)) + return -1; // The sum will overflow an int type + result += static_cast(seg.data.size()); + } + return result; +} + + +bool QrSegment::isAlphanumeric(const char *text) { + for (; *text != '\0'; text++) { + if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) + return false; + } + return true; +} + + +bool QrSegment::isNumeric(const char *text) { + for (; *text != '\0'; text++) { + char c = *text; + if (c < '0' || c > '9') + return false; + } + return true; +} + + +QrSegment::Mode QrSegment::getMode() const { + return mode; +} + + +int QrSegment::getNumChars() const { + return numChars; +} + + +const std::vector &QrSegment::getData() const { + return data; +} + + +const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +} diff --git a/libs/qrcode/QrSegment.hpp b/libs/qrcode/QrSegment.hpp new file mode 100644 index 0000000..663b8bb --- /dev/null +++ b/libs/qrcode/QrSegment.hpp @@ -0,0 +1,216 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#pragma once + +#include +#include +#include "BitBuffer.hpp" + + +namespace qrcodegen { + +/* + * A segment of character/binary/control data in a QR Code symbol. + * Instances of this class are immutable. + * The mid-level way to create a segment is to take the payload data + * and call a static factory function such as QrSegment::makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and call the QrSegment() constructor with appropriate values. + * This segment class imposes no length restrictions, but QR Codes have restrictions. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + */ +class QrSegment final { + + /*---- Public helper enumeration ----*/ + + /* + * Describes how a segment's data bits are interpreted. Immutable. + */ + public: class Mode final { + + /*-- Constants --*/ + + public: static const Mode NUMERIC; + public: static const Mode ALPHANUMERIC; + public: static const Mode BYTE; + public: static const Mode KANJI; + public: static const Mode ECI; + + + /*-- Fields --*/ + + // The mode indicator bits, which is a uint4 value (range 0 to 15). + private: int modeBits; + + // Number of character count bits for three different version ranges. + private: int numBitsCharCount[3]; + + + /*-- Constructor --*/ + + private: Mode(int mode, int cc0, int cc1, int cc2); + + + /*-- Methods --*/ + + /* + * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). + */ + public: int getModeBits() const; + + /* + * (Package-private) Returns the bit width of the character count field for a segment in + * this mode in a QR Code at the given version number. The result is in the range [0, 16]. + */ + public: int numCharCountBits(int ver) const; + + }; + + + + /*---- Static factory functions (mid level) ----*/ + + /* + * Returns a segment representing the given binary data encoded in + * byte mode. All input byte vectors are acceptable. Any text string + * can be converted to UTF-8 bytes and encoded as a byte mode segment. + */ + public: static QrSegment makeBytes(const std::vector &data); + + + /* + * Returns a segment representing the given string of decimal digits encoded in numeric mode. + */ + public: static QrSegment makeNumeric(const char *digits); + + + /* + * Returns a segment representing the given text string encoded in alphanumeric mode. + * The characters allowed are: 0 to 9, A to Z (uppercase only), space, + * dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ + public: static QrSegment makeAlphanumeric(const char *text); + + + /* + * Returns a list of zero or more segments to represent the given text string. The result + * may use various segment modes and switch modes to optimize the length of the bit stream. + */ + public: static std::vector makeSegments(const char *text); + + + /* + * Returns a segment representing an Extended Channel Interpretation + * (ECI) designator with the given assignment value. + */ + public: static QrSegment makeEci(long assignVal); + + + /*---- Public static helper functions ----*/ + + /* + * Tests whether the given string can be encoded as a segment in alphanumeric mode. + * A string is encodable iff each character is in the following set: 0 to 9, A to Z + * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ + public: static bool isAlphanumeric(const char *text); + + + /* + * Tests whether the given string can be encoded as a segment in numeric mode. + * A string is encodable iff each character is in the range 0 to 9. + */ + public: static bool isNumeric(const char *text); + + + + /*---- Instance fields ----*/ + + /* The mode indicator of this segment. Accessed through getMode(). */ + private: Mode mode; + + /* The length of this segment's unencoded data. Measured in characters for + * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + * Always zero or positive. Not the same as the data's bit length. + * Accessed through getNumChars(). */ + private: int numChars; + + /* The data bits of this segment. Accessed through getData(). */ + private: std::vector data; + + + /*---- Constructors (low level) ----*/ + + /* + * Creates a new QR Code segment with the given attributes and data. + * The character count (numCh) must agree with the mode and the bit buffer length, + * but the constraint isn't checked. The given bit buffer is copied and stored. + */ + public: QrSegment(Mode md, int numCh, const std::vector &dt); + + + /* + * Creates a new QR Code segment with the given parameters and data. + * The character count (numCh) must agree with the mode and the bit buffer length, + * but the constraint isn't checked. The given bit buffer is moved and stored. + */ + public: QrSegment(Mode md, int numCh, std::vector &&dt); + + + /*---- Methods ----*/ + + /* + * Returns the mode field of this segment. + */ + public: Mode getMode() const; + + + /* + * Returns the character count field of this segment. + */ + public: int getNumChars() const; + + + /* + * Returns the data bits of this segment. + */ + public: const std::vector &getData() const; + + + // (Package-private) Calculates the number of bits needed to encode the given segments at + // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a + // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX. + public: static int getTotalBits(const std::vector &segs, int version); + + + /*---- Private constant ----*/ + + /* The set of all legal characters in alphanumeric mode, where + * each character value maps to the index in the string. */ + private: static const char *ALPHANUMERIC_CHARSET; + +}; + +} diff --git a/libs/stb_image.h b/libs/stb_image.h new file mode 100644 index 0000000..9eedabe --- /dev/null +++ b/libs/stb_image.h @@ -0,0 +1,7988 @@ +/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.30 (2024-05-31) avoid erroneous gcc warning + 2.29 (2023-05-xx) optimizations + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two ints fits in a signed short, 0 on overflow. +static int stbi__mul2shorts_valid(int a, int b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * (1 << shift)); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding btis + // to allow us to keep going; if we actually consume any of them + // though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero bits into our bit + // buffer so the decoder can just do its speculative decoding. But if we + // actually consumed any of those bits (which is the case when num_bits < 16), + // the stream actually read past the end so it is malformed. + return stbi__err("unexpected end","Corrupt PNG"); + } + return 1; + } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filter used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +}; + +static int stbi__paeth(int a, int b, int c) +{ + // This formulation looks very different from the reference in the PNG spec, but is + // actually equivalent and has favorable data dependencies and admits straightforward + // generation of branch-free code, which helps performance significantly. + int thresh = c*3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// adds an extra all-255 alpha channel +// dest == src is legal +// img_n must be 1 or 3 +static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n) +{ + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i=x-1; i >= 0; --i) { + dest[i*2+1] = 255; + dest[i*2+0] = src[i]; + } + } else { + STBI_ASSERT(img_n == 3); + for (i=x-1; i >= 0; --i) { + dest[i*4+3] = 255; + dest[i*4+2] = src[i*3+2]; + dest[i*4+1] = src[i*3+1]; + dest[i*4+0] = src[i*3+0]; + } + } +} + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc *filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } + + for (j=0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; + stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; + stbi_uc *dest = a->out + stride*j; + int nk = width * filter_bytes; + int filter = *raw++; + + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter","Corrupt PNG"); + break; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); + break; + } + + raw += nk; + + // expand decoded bits in cur to dest, also adding an extra alpha channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + stbi_uc *in = cur; + stbi_uc *out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x*img_n; + + // expand bits to bytes first + if (depth == 4) { + for (i=0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } else if (depth == 2) { + for (i=0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } + } else { + STBI_ASSERT(depth == 1); + for (i=0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } + } + + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x*img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16 *dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x*img_n; + + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } else { + STBI_ASSERT(img_n+1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } + } + } + } + + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning + tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n && k < 3; ++k) + tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/prebuilt-binaries/dragonxd-linux/.gitkeep b/prebuilt-binaries/dragonxd-linux/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/prebuilt-binaries/dragonxd-mac/.gitkeep b/prebuilt-binaries/dragonxd-mac/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/prebuilt-binaries/dragonxd-win/.gitkeep b/prebuilt-binaries/dragonxd-win/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/prebuilt-binaries/xmrig-hac/.gitkeep b/prebuilt-binaries/xmrig-hac/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/res/ObsidianDragon.rc b/res/ObsidianDragon.rc new file mode 100644 index 0000000..e7670e2 --- /dev/null +++ b/res/ObsidianDragon.rc @@ -0,0 +1,41 @@ +// ObsidianDragon Windows Resource File +// Application icon — shown in Explorer, taskbar, and Alt-Tab +// Path configured by CMake (absolute path for cross-compilation) +// Use numeric ordinal 1 so LoadIcon(hInst, MAKEINTRESOURCE(1)) finds it. +1 ICON "@OBSIDIAN_ICO_PATH@" + +// --------------------------------------------------------------------------- +// VERSIONINFO — sets the description shown in Task Manager, Explorer +// "Details" tab, and other Windows tools. Without this, MinGW-w64 +// fills in its own runtime description ("POSIX WinThreads for Windows"). +// --------------------------------------------------------------------------- +#include + +VS_VERSION_INFO VERSIONINFO + FILEVERSION @DRAGONX_VER_MAJOR@,@DRAGONX_VER_MINOR@,@DRAGONX_VER_PATCH@,0 + PRODUCTVERSION @DRAGONX_VER_MAJOR@,@DRAGONX_VER_MINOR@,@DRAGONX_VER_PATCH@,0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0x0L + FILEOS VOS_NT_WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE VFT2_UNKNOWN +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" // US-English, Unicode + BEGIN + VALUE "CompanyName", "The Hush Developers\0" + VALUE "FileDescription", "ObsidianDragon Wallet\0" + VALUE "FileVersion", "@DRAGONX_VERSION@\0" + VALUE "InternalName", "ObsidianDragon\0" + VALUE "LegalCopyright", "Copyright 2024-2026 The Hush Developers. GPLv3.\0" + VALUE "OriginalFilename", "ObsidianDragon.exe\0" + VALUE "ProductName", "ObsidianDragon\0" + VALUE "ProductVersion", "@DRAGONX_VERSION@\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 // US-English, Unicode + END +END diff --git a/res/fonts/MaterialIcons-Regular.ttf b/res/fonts/MaterialIcons-Regular.ttf new file mode 100644 index 0000000..9d09b0f Binary files /dev/null and b/res/fonts/MaterialIcons-Regular.ttf differ diff --git a/res/fonts/Ubuntu-Light.ttf b/res/fonts/Ubuntu-Light.ttf new file mode 100644 index 0000000..6a84adc Binary files /dev/null and b/res/fonts/Ubuntu-Light.ttf differ diff --git a/res/fonts/Ubuntu-Medium.ttf b/res/fonts/Ubuntu-Medium.ttf new file mode 100644 index 0000000..c6f048e Binary files /dev/null and b/res/fonts/Ubuntu-Medium.ttf differ diff --git a/res/fonts/Ubuntu-R.ttf b/res/fonts/Ubuntu-R.ttf new file mode 100644 index 0000000..d748728 Binary files /dev/null and b/res/fonts/Ubuntu-R.ttf differ diff --git a/res/img/ObsidianDragon.ico b/res/img/ObsidianDragon.ico new file mode 100644 index 0000000..13a0f9c Binary files /dev/null and b/res/img/ObsidianDragon.ico differ diff --git a/res/img/backgrounds/gradient/dark_gradient.png b/res/img/backgrounds/gradient/dark_gradient.png new file mode 100644 index 0000000..f18d0a3 Binary files /dev/null and b/res/img/backgrounds/gradient/dark_gradient.png differ diff --git a/res/img/backgrounds/gradient/gradient_dark_bg.png b/res/img/backgrounds/gradient/gradient_dark_bg.png new file mode 100644 index 0000000..5876e80 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_dark_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_drgx_bg.png b/res/img/backgrounds/gradient/gradient_drgx_bg.png new file mode 100644 index 0000000..76559a2 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_drgx_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_dune_bg.png b/res/img/backgrounds/gradient/gradient_dune_bg.png new file mode 100644 index 0000000..4bb652b Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_dune_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_iridescent_bg.png b/res/img/backgrounds/gradient/gradient_iridescent_bg.png new file mode 100644 index 0000000..937eb4c Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_iridescent_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_light_bg.png b/res/img/backgrounds/gradient/gradient_light_bg.png new file mode 100644 index 0000000..0520c9e Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_light_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_marble_bg.png b/res/img/backgrounds/gradient/gradient_marble_bg.png new file mode 100644 index 0000000..11ddff3 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_marble_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_obsidian_bg.png b/res/img/backgrounds/gradient/gradient_obsidian_bg.png new file mode 100644 index 0000000..0610ee1 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_obsidian_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_pop-dark_bg.png b/res/img/backgrounds/gradient/gradient_pop-dark_bg.png new file mode 100644 index 0000000..f18d0a3 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_pop-dark_bg.png differ diff --git a/res/img/backgrounds/gradient/gradient_pop-light_bg.png b/res/img/backgrounds/gradient/gradient_pop-light_bg.png new file mode 100644 index 0000000..ecb9f06 Binary files /dev/null and b/res/img/backgrounds/gradient/gradient_pop-light_bg.png differ diff --git a/res/img/backgrounds/gradient/light_gradient.png b/res/img/backgrounds/gradient/light_gradient.png new file mode 100644 index 0000000..969bf90 Binary files /dev/null and b/res/img/backgrounds/gradient/light_gradient.png differ diff --git a/res/img/backgrounds/texture/dark_bg.png b/res/img/backgrounds/texture/dark_bg.png new file mode 100644 index 0000000..ad79ad6 Binary files /dev/null and b/res/img/backgrounds/texture/dark_bg.png differ diff --git a/res/img/backgrounds/texture/drgx_bg.png b/res/img/backgrounds/texture/drgx_bg.png new file mode 100644 index 0000000..085466b Binary files /dev/null and b/res/img/backgrounds/texture/drgx_bg.png differ diff --git a/res/img/backgrounds/texture/dune_bg.png b/res/img/backgrounds/texture/dune_bg.png new file mode 100644 index 0000000..61cff9e Binary files /dev/null and b/res/img/backgrounds/texture/dune_bg.png differ diff --git a/res/img/backgrounds/texture/iridescent_bg.png b/res/img/backgrounds/texture/iridescent_bg.png new file mode 100644 index 0000000..e175ad7 Binary files /dev/null and b/res/img/backgrounds/texture/iridescent_bg.png differ diff --git a/res/img/backgrounds/texture/light_bg.png b/res/img/backgrounds/texture/light_bg.png new file mode 100644 index 0000000..740a9bf Binary files /dev/null and b/res/img/backgrounds/texture/light_bg.png differ diff --git a/res/img/backgrounds/texture/marble_bg.png b/res/img/backgrounds/texture/marble_bg.png new file mode 100644 index 0000000..ad2b9ef Binary files /dev/null and b/res/img/backgrounds/texture/marble_bg.png differ diff --git a/res/img/backgrounds/texture/obsidian_bg.png b/res/img/backgrounds/texture/obsidian_bg.png new file mode 100644 index 0000000..7270b25 Binary files /dev/null and b/res/img/backgrounds/texture/obsidian_bg.png differ diff --git a/res/img/backgrounds/texture/pop-dark_bg.png b/res/img/backgrounds/texture/pop-dark_bg.png new file mode 100644 index 0000000..deb41e1 Binary files /dev/null and b/res/img/backgrounds/texture/pop-dark_bg.png differ diff --git a/res/img/backgrounds/texture/pop-light_bg.png b/res/img/backgrounds/texture/pop-light_bg.png new file mode 100644 index 0000000..db06f96 Binary files /dev/null and b/res/img/backgrounds/texture/pop-light_bg.png differ diff --git a/res/img/logos/logo_ObsidianDragon.png b/res/img/logos/logo_ObsidianDragon.png new file mode 100644 index 0000000..9935231 Binary files /dev/null and b/res/img/logos/logo_ObsidianDragon.png differ diff --git a/res/img/logos/logo_ObsidianDragon_dark.png b/res/img/logos/logo_ObsidianDragon_dark.png new file mode 100644 index 0000000..2c4a160 Binary files /dev/null and b/res/img/logos/logo_ObsidianDragon_dark.png differ diff --git a/res/img/logos/logo_ObsidianDragon_light.png b/res/img/logos/logo_ObsidianDragon_light.png new file mode 100644 index 0000000..0bb0be0 Binary files /dev/null and b/res/img/logos/logo_ObsidianDragon_light.png differ diff --git a/res/img/logos/logo_dragonx_128.png b/res/img/logos/logo_dragonx_128.png new file mode 100644 index 0000000..adc8eda Binary files /dev/null and b/res/img/logos/logo_dragonx_128.png differ diff --git a/res/lang/de.json b/res/lang/de.json new file mode 100644 index 0000000..66f8e16 --- /dev/null +++ b/res/lang/de.json @@ -0,0 +1,139 @@ +{ + "balance": "Kontostand", + "send": "Senden", + "receive": "Empfangen", + "transactions": "Transaktionen", + "mining": "Mining", + "peers": "Knoten", + "market": "Markt", + "settings": "Einstellungen", + + "summary": "Übersicht", + "shielded": "Geschützt", + "transparent": "Transparent", + "total": "Gesamt", + "unconfirmed": "Unbestätigt", + "your_addresses": "Ihre Adressen", + "z_addresses": "Z-Adressen", + "t_addresses": "T-Adressen", + "no_addresses": "Keine Adressen gefunden. Erstellen Sie eine mit den Schaltflächen oben.", + "new_z_address": "Neue Z-Adresse", + "new_t_address": "Neue T-Adresse", + "type": "Typ", + "address": "Adresse", + "copy_address": "Vollständige Adresse kopieren", + "send_from_this_address": "Von dieser Adresse senden", + "export_private_key": "Privaten Schlüssel exportieren", + "export_viewing_key": "Ansichtsschlüssel exportieren", + "show_qr_code": "QR-Code anzeigen", + "not_connected": "Nicht mit Daemon verbunden...", + + "pay_from": "Zahlen von", + "send_to": "Senden an", + "amount": "Betrag", + "memo": "Memo (optional, verschlüsselt)", + "miner_fee": "Miner-Gebühr", + "fee": "Gebühr", + "send_transaction": "Transaktion senden", + "clear": "Löschen", + "select_address": "Adresse auswählen...", + "paste": "Einfügen", + "max": "Max", + "available": "Verfügbar", + "invalid_address": "Ungültiges Adressformat", + "memo_z_only": "Hinweis: Memos sind nur beim Senden an geschützte (z) Adressen verfügbar", + "characters": "Zeichen", + "from": "Von", + "to": "An", + "sending": "Transaktion wird gesendet", + "confirm_send": "Senden bestätigen", + "confirm_transaction": "Transaktion bestätigen", + "confirm_and_send": "Bestätigen & Senden", + "cancel": "Abbrechen", + + "receiving_addresses": "Ihre Empfangsadressen", + "new_z_shielded": "Neue z-Adresse (geschützt)", + "new_t_transparent": "Neue t-Adresse (transparent)", + "address_details": "Adressdetails", + "view_on_explorer": "Im Explorer ansehen", + "qr_code": "QR-Code", + "request_payment": "Zahlung anfordern", + + "date": "Datum", + "status": "Status", + "confirmations": "Bestätigungen", + "confirmed": "Bestätigt", + "pending": "Ausstehend", + "sent": "gesendet", + "received": "empfangen", + "mined": "geschürft", + + "mining_control": "Mining-Steuerung", + "start_mining": "Mining starten", + "stop_mining": "Mining stoppen", + "mining_threads": "Mining-Threads", + "mining_statistics": "Mining-Statistiken", + "local_hashrate": "Lokale Hashrate", + "network_hashrate": "Netzwerk-Hashrate", + "difficulty": "Schwierigkeit", + "est_time_to_block": "Gesch. Zeit bis Block", + "mining_off": "Mining ist AUS", + "mining_on": "Mining ist AN", + + "connected_peers": "Verbundene Knoten", + "banned_peers": "Gesperrte Knoten", + "ip_address": "IP-Adresse", + "version": "Version", + "height": "Höhe", + "ping": "Ping", + "ban": "Sperren", + "unban": "Entsperren", + "clear_all_bans": "Alle Sperren aufheben", + + "price_chart": "Preisdiagramm", + "current_price": "Aktueller Preis", + "24h_change": "24h-Änderung", + "24h_volume": "24h-Volumen", + "market_cap": "Marktkapitalisierung", + + "general": "Allgemein", + "display": "Anzeige", + "network": "Netzwerk", + "theme": "Design", + "language": "Sprache", + "dragonx_green": "DragonX (Grün)", + "dark": "Dunkel", + "light": "Hell", + "allow_custom_fees": "Benutzerdefinierte Gebühren erlauben", + "use_embedded_daemon": "Integrierten dragonxd verwenden", + "save": "Speichern", + "close": "Schließen", + + "file": "Datei", + "edit": "Bearbeiten", + "view": "Ansicht", + "help": "Hilfe", + "import_private_key": "Privaten Schlüssel importieren...", + "backup_wallet": "Wallet sichern...", + "exit": "Beenden", + "about_dragonx": "Über ObsidianDragon", + "refresh_now": "Jetzt aktualisieren", + + "about": "Über", + "import": "Importieren", + "export": "Exportieren", + "copy_to_clipboard": "In Zwischenablage kopieren", + + "connected": "Verbunden", + "disconnected": "Getrennt", + "connecting": "Verbinde...", + "syncing": "Synchronisiere...", + "block": "Block", + "no_addresses_available": "Keine Adressen verfügbar", + + "error": "Fehler", + "success": "Erfolg", + "warning": "Warnung", + "amount_exceeds_balance": "Betrag übersteigt Kontostand", + "transaction_sent": "Transaktion erfolgreich gesendet" +} diff --git a/res/lang/es.json b/res/lang/es.json new file mode 100644 index 0000000..bdbd57d --- /dev/null +++ b/res/lang/es.json @@ -0,0 +1,139 @@ +{ + "balance": "Saldo", + "send": "Enviar", + "receive": "Recibir", + "transactions": "Transacciones", + "mining": "Minería", + "peers": "Nodos", + "market": "Mercado", + "settings": "Configuración", + + "summary": "Resumen", + "shielded": "Protegido", + "transparent": "Transparente", + "total": "Total", + "unconfirmed": "Sin Confirmar", + "your_addresses": "Tus Direcciones", + "z_addresses": "Direcciones-Z", + "t_addresses": "Direcciones-T", + "no_addresses": "No se encontraron direcciones. Crea una usando los botones de arriba.", + "new_z_address": "Nueva Dir-Z", + "new_t_address": "Nueva Dir-T", + "type": "Tipo", + "address": "Dirección", + "copy_address": "Copiar Dirección Completa", + "send_from_this_address": "Enviar Desde Esta Dirección", + "export_private_key": "Exportar Clave Privada", + "export_viewing_key": "Exportar Clave de Vista", + "show_qr_code": "Mostrar Código QR", + "not_connected": "No conectado al daemon...", + + "pay_from": "Pagar Desde", + "send_to": "Enviar A", + "amount": "Cantidad", + "memo": "Memo (opcional, encriptado)", + "miner_fee": "Comisión de Minero", + "fee": "Comisión", + "send_transaction": "Enviar Transacción", + "clear": "Limpiar", + "select_address": "Seleccionar dirección...", + "paste": "Pegar", + "max": "Máximo", + "available": "Disponible", + "invalid_address": "Formato de dirección inválido", + "memo_z_only": "Nota: Los memos solo están disponibles al enviar a direcciones protegidas (z)", + "characters": "caracteres", + "from": "Desde", + "to": "A", + "sending": "Enviando transacción", + "confirm_send": "Confirmar Envío", + "confirm_transaction": "Confirmar Transacción", + "confirm_and_send": "Confirmar y Enviar", + "cancel": "Cancelar", + + "receiving_addresses": "Tus Direcciones de Recepción", + "new_z_shielded": "Nueva Dirección-z (Protegida)", + "new_t_transparent": "Nueva Dirección-t (Transparente)", + "address_details": "Detalles de Dirección", + "view_on_explorer": "Ver en Explorador", + "qr_code": "Código QR", + "request_payment": "Solicitar Pago", + + "date": "Fecha", + "status": "Estado", + "confirmations": "Confirmaciones", + "confirmed": "Confirmada", + "pending": "Pendiente", + "sent": "enviado", + "received": "recibido", + "mined": "minado", + + "mining_control": "Control de Minería", + "start_mining": "Iniciar Minería", + "stop_mining": "Detener Minería", + "mining_threads": "Hilos de Minería", + "mining_statistics": "Estadísticas de Minería", + "local_hashrate": "Tasa Hash Local", + "network_hashrate": "Tasa Hash de Red", + "difficulty": "Dificultad", + "est_time_to_block": "Tiempo Est. al Bloque", + "mining_off": "Minería APAGADA", + "mining_on": "Minería ENCENDIDA", + + "connected_peers": "Nodos Conectados", + "banned_peers": "Nodos Bloqueados", + "ip_address": "Dirección IP", + "version": "Versión", + "height": "Altura", + "ping": "Ping", + "ban": "Bloquear", + "unban": "Desbloquear", + "clear_all_bans": "Limpiar Todos los Bloqueos", + + "price_chart": "Gráfico de Precio", + "current_price": "Precio Actual", + "24h_change": "Cambio 24h", + "24h_volume": "Volumen 24h", + "market_cap": "Cap. de Mercado", + + "general": "General", + "display": "Pantalla", + "network": "Red", + "theme": "Tema", + "language": "Idioma", + "dragonx_green": "DragonX (Verde)", + "dark": "Oscuro", + "light": "Claro", + "allow_custom_fees": "Permitir comisiones personalizadas", + "use_embedded_daemon": "Usar dragonxd integrado", + "save": "Guardar", + "close": "Cerrar", + + "file": "Archivo", + "edit": "Editar", + "view": "Ver", + "help": "Ayuda", + "import_private_key": "Importar Clave Privada...", + "backup_wallet": "Respaldar Cartera...", + "exit": "Salir", + "about_dragonx": "Acerca de DragonX", + "refresh_now": "Actualizar Ahora", + + "about": "Acerca de", + "import": "Importar", + "export": "Exportar", + "copy_to_clipboard": "Copiar al Portapapeles", + + "connected": "Conectado", + "disconnected": "Desconectado", + "connecting": "Conectando...", + "syncing": "Sincronizando...", + "block": "Bloque", + "no_addresses_available": "No hay direcciones disponibles", + + "error": "Error", + "success": "Éxito", + "warning": "Advertencia", + "amount_exceeds_balance": "La cantidad excede el saldo", + "transaction_sent": "Transacción enviada exitosamente" +} diff --git a/res/lang/fr.json b/res/lang/fr.json new file mode 100644 index 0000000..6c0ab7a --- /dev/null +++ b/res/lang/fr.json @@ -0,0 +1,139 @@ +{ + "balance": "Solde", + "send": "Envoyer", + "receive": "Recevoir", + "transactions": "Transactions", + "mining": "Minage", + "peers": "Nœuds", + "market": "Marché", + "settings": "Paramètres", + + "summary": "Résumé", + "shielded": "Protégé", + "transparent": "Transparent", + "total": "Total", + "unconfirmed": "Non confirmé", + "your_addresses": "Vos adresses", + "z_addresses": "Adresses-Z", + "t_addresses": "Adresses-T", + "no_addresses": "Aucune adresse trouvée. Créez-en une avec les boutons ci-dessus.", + "new_z_address": "Nouvelle adresse-Z", + "new_t_address": "Nouvelle adresse-T", + "type": "Type", + "address": "Adresse", + "copy_address": "Copier l'adresse complète", + "send_from_this_address": "Envoyer depuis cette adresse", + "export_private_key": "Exporter la clé privée", + "export_viewing_key": "Exporter la clé de visualisation", + "show_qr_code": "Afficher le QR code", + "not_connected": "Non connecté au démon...", + + "pay_from": "Payer depuis", + "send_to": "Envoyer à", + "amount": "Montant", + "memo": "Mémo (optionnel, chiffré)", + "miner_fee": "Frais de mineur", + "fee": "Frais", + "send_transaction": "Envoyer la transaction", + "clear": "Effacer", + "select_address": "Sélectionner une adresse...", + "paste": "Coller", + "max": "Max", + "available": "Disponible", + "invalid_address": "Format d'adresse invalide", + "memo_z_only": "Note : les mémos ne sont disponibles qu'en envoyant vers des adresses protégées (z)", + "characters": "caractères", + "from": "De", + "to": "À", + "sending": "Envoi de la transaction", + "confirm_send": "Confirmer l'envoi", + "confirm_transaction": "Confirmer la transaction", + "confirm_and_send": "Confirmer et envoyer", + "cancel": "Annuler", + + "receiving_addresses": "Vos adresses de réception", + "new_z_shielded": "Nouvelle adresse-z (protégée)", + "new_t_transparent": "Nouvelle adresse-t (transparente)", + "address_details": "Détails de l'adresse", + "view_on_explorer": "Voir sur l'explorateur", + "qr_code": "QR Code", + "request_payment": "Demander un paiement", + + "date": "Date", + "status": "Statut", + "confirmations": "Confirmations", + "confirmed": "Confirmée", + "pending": "En attente", + "sent": "envoyé", + "received": "reçu", + "mined": "miné", + + "mining_control": "Contrôle du minage", + "start_mining": "Démarrer le minage", + "stop_mining": "Arrêter le minage", + "mining_threads": "Threads de minage", + "mining_statistics": "Statistiques de minage", + "local_hashrate": "Hashrate local", + "network_hashrate": "Hashrate du réseau", + "difficulty": "Difficulté", + "est_time_to_block": "Temps est. avant bloc", + "mining_off": "Minage DÉSACTIVÉ", + "mining_on": "Minage ACTIVÉ", + + "connected_peers": "Nœuds connectés", + "banned_peers": "Nœuds bannis", + "ip_address": "Adresse IP", + "version": "Version", + "height": "Hauteur", + "ping": "Ping", + "ban": "Bannir", + "unban": "Débannir", + "clear_all_bans": "Lever tous les bannissements", + + "price_chart": "Graphique des prix", + "current_price": "Prix actuel", + "24h_change": "Variation 24h", + "24h_volume": "Volume 24h", + "market_cap": "Capitalisation", + + "general": "Général", + "display": "Affichage", + "network": "Réseau", + "theme": "Thème", + "language": "Langue", + "dragonx_green": "DragonX (Vert)", + "dark": "Sombre", + "light": "Clair", + "allow_custom_fees": "Autoriser les frais personnalisés", + "use_embedded_daemon": "Utiliser le dragonxd intégré", + "save": "Enregistrer", + "close": "Fermer", + + "file": "Fichier", + "edit": "Édition", + "view": "Affichage", + "help": "Aide", + "import_private_key": "Importer une clé privée...", + "backup_wallet": "Sauvegarder le portefeuille...", + "exit": "Quitter", + "about_dragonx": "À propos d'ObsidianDragon", + "refresh_now": "Actualiser maintenant", + + "about": "À propos", + "import": "Importer", + "export": "Exporter", + "copy_to_clipboard": "Copier dans le presse-papiers", + + "connected": "Connecté", + "disconnected": "Déconnecté", + "connecting": "Connexion...", + "syncing": "Synchronisation...", + "block": "Bloc", + "no_addresses_available": "Aucune adresse disponible", + + "error": "Erreur", + "success": "Succès", + "warning": "Avertissement", + "amount_exceeds_balance": "Le montant dépasse le solde", + "transaction_sent": "Transaction envoyée avec succès" +} diff --git a/res/lang/ja.json b/res/lang/ja.json new file mode 100644 index 0000000..b31d129 --- /dev/null +++ b/res/lang/ja.json @@ -0,0 +1,139 @@ +{ + "balance": "残高", + "send": "送金", + "receive": "受取", + "transactions": "取引履歴", + "mining": "マイニング", + "peers": "ノード", + "market": "マーケット", + "settings": "設定", + + "summary": "概要", + "shielded": "シールド", + "transparent": "トランスパレント", + "total": "合計", + "unconfirmed": "未確認", + "your_addresses": "アドレス一覧", + "z_addresses": "Z-アドレス", + "t_addresses": "T-アドレス", + "no_addresses": "アドレスが見つかりません。上のボタンで作成してください。", + "new_z_address": "新規 Z-アドレス", + "new_t_address": "新規 T-アドレス", + "type": "タイプ", + "address": "アドレス", + "copy_address": "アドレスをコピー", + "send_from_this_address": "このアドレスから送金", + "export_private_key": "秘密鍵をエクスポート", + "export_viewing_key": "閲覧鍵をエクスポート", + "show_qr_code": "QRコードを表示", + "not_connected": "デーモンに未接続...", + + "pay_from": "支払元", + "send_to": "送金先", + "amount": "金額", + "memo": "メモ(任意、暗号化)", + "miner_fee": "マイナー手数料", + "fee": "手数料", + "send_transaction": "送金する", + "clear": "クリア", + "select_address": "アドレスを選択...", + "paste": "貼り付け", + "max": "最大", + "available": "利用可能", + "invalid_address": "無効なアドレス形式", + "memo_z_only": "注:メモはシールド(z)アドレスへの送金時のみ利用可能です", + "characters": "文字", + "from": "送金元", + "to": "送金先", + "sending": "送金中", + "confirm_send": "送金確認", + "confirm_transaction": "取引確認", + "confirm_and_send": "確認して送金", + "cancel": "キャンセル", + + "receiving_addresses": "受取アドレス", + "new_z_shielded": "新規 z-アドレス(シールド)", + "new_t_transparent": "新規 t-アドレス(トランスパレント)", + "address_details": "アドレス詳細", + "view_on_explorer": "エクスプローラーで表示", + "qr_code": "QRコード", + "request_payment": "支払いを要求", + + "date": "日付", + "status": "ステータス", + "confirmations": "確認数", + "confirmed": "確認済み", + "pending": "保留中", + "sent": "送金済", + "received": "受取済", + "mined": "採掘済", + + "mining_control": "マイニング制御", + "start_mining": "マイニング開始", + "stop_mining": "マイニング停止", + "mining_threads": "マイニングスレッド", + "mining_statistics": "マイニング統計", + "local_hashrate": "ローカルハッシュレート", + "network_hashrate": "ネットワークハッシュレート", + "difficulty": "難易度", + "est_time_to_block": "推定ブロック発見時間", + "mining_off": "マイニング停止中", + "mining_on": "マイニング稼働中", + + "connected_peers": "接続中のノード", + "banned_peers": "ブロック済みノード", + "ip_address": "IPアドレス", + "version": "バージョン", + "height": "ブロック高", + "ping": "Ping", + "ban": "ブロック", + "unban": "ブロック解除", + "clear_all_bans": "すべてのブロックを解除", + + "price_chart": "価格チャート", + "current_price": "現在価格", + "24h_change": "24時間変動", + "24h_volume": "24時間取引量", + "market_cap": "時価総額", + + "general": "一般", + "display": "表示", + "network": "ネットワーク", + "theme": "テーマ", + "language": "言語", + "dragonx_green": "DragonX(グリーン)", + "dark": "ダーク", + "light": "ライト", + "allow_custom_fees": "カスタム手数料を許可", + "use_embedded_daemon": "内蔵 dragonxd を使用", + "save": "保存", + "close": "閉じる", + + "file": "ファイル", + "edit": "編集", + "view": "表示", + "help": "ヘルプ", + "import_private_key": "秘密鍵をインポート...", + "backup_wallet": "ウォレットをバックアップ...", + "exit": "終了", + "about_dragonx": "ObsidianDragonについて", + "refresh_now": "今すぐ更新", + + "about": "このアプリについて", + "import": "インポート", + "export": "エクスポート", + "copy_to_clipboard": "クリップボードにコピー", + + "connected": "接続済み", + "disconnected": "切断", + "connecting": "接続中...", + "syncing": "同期中...", + "block": "ブロック", + "no_addresses_available": "利用可能なアドレスがありません", + + "error": "エラー", + "success": "成功", + "warning": "警告", + "amount_exceeds_balance": "金額が残高を超えています", + "transaction_sent": "送金が完了しました" +} diff --git a/res/lang/ko.json b/res/lang/ko.json new file mode 100644 index 0000000..9fb31b7 --- /dev/null +++ b/res/lang/ko.json @@ -0,0 +1,139 @@ +{ + "balance": "잔액", + "send": "보내기", + "receive": "받기", + "transactions": "거래 내역", + "mining": "채굴", + "peers": "노드", + "market": "시장", + "settings": "설정", + + "summary": "요약", + "shielded": "차폐됨", + "transparent": "투명", + "total": "합계", + "unconfirmed": "미확인", + "your_addresses": "내 주소", + "z_addresses": "Z-주소", + "t_addresses": "T-주소", + "no_addresses": "주소를 찾을 수 없습니다. 위의 버튼을 사용하여 생성하세요.", + "new_z_address": "새 Z-주소", + "new_t_address": "새 T-주소", + "type": "유형", + "address": "주소", + "copy_address": "전체 주소 복사", + "send_from_this_address": "이 주소에서 보내기", + "export_private_key": "개인키 내보내기", + "export_viewing_key": "조회키 내보내기", + "show_qr_code": "QR 코드 표시", + "not_connected": "데몬에 연결되지 않음...", + + "pay_from": "출금 주소", + "send_to": "받는 주소", + "amount": "금액", + "memo": "메모 (선택사항, 암호화됨)", + "miner_fee": "채굴자 수수료", + "fee": "수수료", + "send_transaction": "거래 보내기", + "clear": "지우기", + "select_address": "주소 선택...", + "paste": "붙여넣기", + "max": "최대", + "available": "사용 가능", + "invalid_address": "잘못된 주소 형식", + "memo_z_only": "참고: 메모는 차폐(z) 주소로 보낼 때만 사용할 수 있습니다", + "characters": "글자", + "from": "보낸 사람", + "to": "받는 사람", + "sending": "거래 전송 중", + "confirm_send": "보내기 확인", + "confirm_transaction": "거래 확인", + "confirm_and_send": "확인 및 보내기", + "cancel": "취소", + + "receiving_addresses": "수신 주소", + "new_z_shielded": "새 z-주소 (차폐)", + "new_t_transparent": "새 t-주소 (투명)", + "address_details": "주소 상세", + "view_on_explorer": "탐색기에서 보기", + "qr_code": "QR 코드", + "request_payment": "결제 요청", + + "date": "날짜", + "status": "상태", + "confirmations": "확인 수", + "confirmed": "확인됨", + "pending": "대기 중", + "sent": "보냄", + "received": "받음", + "mined": "채굴됨", + + "mining_control": "채굴 제어", + "start_mining": "채굴 시작", + "stop_mining": "채굴 중지", + "mining_threads": "채굴 스레드", + "mining_statistics": "채굴 통계", + "local_hashrate": "로컬 해시레이트", + "network_hashrate": "네트워크 해시레이트", + "difficulty": "난이도", + "est_time_to_block": "예상 블록 발견 시간", + "mining_off": "채굴 꺼짐", + "mining_on": "채굴 켜짐", + + "connected_peers": "연결된 노드", + "banned_peers": "차단된 노드", + "ip_address": "IP 주소", + "version": "버전", + "height": "블록 높이", + "ping": "핑", + "ban": "차단", + "unban": "차단 해제", + "clear_all_bans": "모든 차단 해제", + + "price_chart": "가격 차트", + "current_price": "현재 가격", + "24h_change": "24시간 변동", + "24h_volume": "24시간 거래량", + "market_cap": "시가총액", + + "general": "일반", + "display": "화면", + "network": "네트워크", + "theme": "테마", + "language": "언어", + "dragonx_green": "DragonX (녹색)", + "dark": "다크", + "light": "라이트", + "allow_custom_fees": "사용자 수수료 허용", + "use_embedded_daemon": "내장 dragonxd 사용", + "save": "저장", + "close": "닫기", + + "file": "파일", + "edit": "편집", + "view": "보기", + "help": "도움말", + "import_private_key": "개인키 가져오기...", + "backup_wallet": "지갑 백업...", + "exit": "종료", + "about_dragonx": "ObsidianDragon 정보", + "refresh_now": "지금 새로고침", + + "about": "정보", + "import": "가져오기", + "export": "내보내기", + "copy_to_clipboard": "클립보드에 복사", + + "connected": "연결됨", + "disconnected": "연결 끊김", + "connecting": "연결 중...", + "syncing": "동기화 중...", + "block": "블록", + "no_addresses_available": "사용 가능한 주소 없음", + + "error": "오류", + "success": "성공", + "warning": "경고", + "amount_exceeds_balance": "금액이 잔액을 초과합니다", + "transaction_sent": "거래가 성공적으로 전송되었습니다" +} diff --git a/res/lang/pt.json b/res/lang/pt.json new file mode 100644 index 0000000..775d315 --- /dev/null +++ b/res/lang/pt.json @@ -0,0 +1,139 @@ +{ + "balance": "Saldo", + "send": "Enviar", + "receive": "Receber", + "transactions": "Transações", + "mining": "Mineração", + "peers": "Nós", + "market": "Mercado", + "settings": "Configurações", + + "summary": "Resumo", + "shielded": "Protegido", + "transparent": "Transparente", + "total": "Total", + "unconfirmed": "Não confirmado", + "your_addresses": "Seus endereços", + "z_addresses": "Endereços-Z", + "t_addresses": "Endereços-T", + "no_addresses": "Nenhum endereço encontrado. Crie um usando os botões acima.", + "new_z_address": "Novo endereço-Z", + "new_t_address": "Novo endereço-T", + "type": "Tipo", + "address": "Endereço", + "copy_address": "Copiar endereço completo", + "send_from_this_address": "Enviar deste endereço", + "export_private_key": "Exportar chave privada", + "export_viewing_key": "Exportar chave de visualização", + "show_qr_code": "Mostrar código QR", + "not_connected": "Não conectado ao daemon...", + + "pay_from": "Pagar de", + "send_to": "Enviar para", + "amount": "Valor", + "memo": "Memo (opcional, criptografado)", + "miner_fee": "Taxa do minerador", + "fee": "Taxa", + "send_transaction": "Enviar transação", + "clear": "Limpar", + "select_address": "Selecionar endereço...", + "paste": "Colar", + "max": "Máx.", + "available": "Disponível", + "invalid_address": "Formato de endereço inválido", + "memo_z_only": "Nota: memos só estão disponíveis ao enviar para endereços protegidos (z)", + "characters": "caracteres", + "from": "De", + "to": "Para", + "sending": "Enviando transação", + "confirm_send": "Confirmar envio", + "confirm_transaction": "Confirmar transação", + "confirm_and_send": "Confirmar e enviar", + "cancel": "Cancelar", + + "receiving_addresses": "Seus endereços de recebimento", + "new_z_shielded": "Novo endereço-z (protegido)", + "new_t_transparent": "Novo endereço-t (transparente)", + "address_details": "Detalhes do endereço", + "view_on_explorer": "Ver no explorador", + "qr_code": "Código QR", + "request_payment": "Solicitar pagamento", + + "date": "Data", + "status": "Status", + "confirmations": "Confirmações", + "confirmed": "Confirmada", + "pending": "Pendente", + "sent": "enviado", + "received": "recebido", + "mined": "minerado", + + "mining_control": "Controle de mineração", + "start_mining": "Iniciar mineração", + "stop_mining": "Parar mineração", + "mining_threads": "Threads de mineração", + "mining_statistics": "Estatísticas de mineração", + "local_hashrate": "Hashrate local", + "network_hashrate": "Hashrate da rede", + "difficulty": "Dificuldade", + "est_time_to_block": "Tempo est. até o bloco", + "mining_off": "Mineração DESLIGADA", + "mining_on": "Mineração LIGADA", + + "connected_peers": "Nós conectados", + "banned_peers": "Nós banidos", + "ip_address": "Endereço IP", + "version": "Versão", + "height": "Altura", + "ping": "Ping", + "ban": "Banir", + "unban": "Desbanir", + "clear_all_bans": "Remover todos os banimentos", + + "price_chart": "Gráfico de preço", + "current_price": "Preço atual", + "24h_change": "Variação 24h", + "24h_volume": "Volume 24h", + "market_cap": "Cap. de mercado", + + "general": "Geral", + "display": "Exibição", + "network": "Rede", + "theme": "Tema", + "language": "Idioma", + "dragonx_green": "DragonX (Verde)", + "dark": "Escuro", + "light": "Claro", + "allow_custom_fees": "Permitir taxas personalizadas", + "use_embedded_daemon": "Usar dragonxd embutido", + "save": "Salvar", + "close": "Fechar", + + "file": "Arquivo", + "edit": "Editar", + "view": "Exibir", + "help": "Ajuda", + "import_private_key": "Importar chave privada...", + "backup_wallet": "Fazer backup da carteira...", + "exit": "Sair", + "about_dragonx": "Sobre ObsidianDragon", + "refresh_now": "Atualizar agora", + + "about": "Sobre", + "import": "Importar", + "export": "Exportar", + "copy_to_clipboard": "Copiar para área de transferência", + + "connected": "Conectado", + "disconnected": "Desconectado", + "connecting": "Conectando...", + "syncing": "Sincronizando...", + "block": "Bloco", + "no_addresses_available": "Nenhum endereço disponível", + + "error": "Erro", + "success": "Sucesso", + "warning": "Aviso", + "amount_exceeds_balance": "Valor excede o saldo", + "transaction_sent": "Transação enviada com sucesso" +} diff --git a/res/lang/ru.json b/res/lang/ru.json new file mode 100644 index 0000000..63bbf39 --- /dev/null +++ b/res/lang/ru.json @@ -0,0 +1,139 @@ +{ + "balance": "Баланс", + "send": "Отправить", + "receive": "Получить", + "transactions": "Транзакции", + "mining": "Майнинг", + "peers": "Узлы", + "market": "Рынок", + "settings": "Настройки", + + "summary": "Сводка", + "shielded": "Защищённый", + "transparent": "Прозрачный", + "total": "Итого", + "unconfirmed": "Неподтверждённые", + "your_addresses": "Ваши адреса", + "z_addresses": "Z-адреса", + "t_addresses": "T-адреса", + "no_addresses": "Адреса не найдены. Создайте адрес с помощью кнопок выше.", + "new_z_address": "Новый Z-адрес", + "new_t_address": "Новый T-адрес", + "type": "Тип", + "address": "Адрес", + "copy_address": "Копировать полный адрес", + "send_from_this_address": "Отправить с этого адреса", + "export_private_key": "Экспорт приватного ключа", + "export_viewing_key": "Экспорт ключа просмотра", + "show_qr_code": "Показать QR-код", + "not_connected": "Не подключён к демону...", + + "pay_from": "Оплата с", + "send_to": "Отправить на", + "amount": "Сумма", + "memo": "Примечание (необязательно, зашифровано)", + "miner_fee": "Комиссия майнера", + "fee": "Комиссия", + "send_transaction": "Отправить транзакцию", + "clear": "Очистить", + "select_address": "Выберите адрес...", + "paste": "Вставить", + "max": "Макс.", + "available": "Доступно", + "invalid_address": "Неверный формат адреса", + "memo_z_only": "Примечания доступны только при отправке на защищённые (z) адреса", + "characters": "символов", + "from": "От", + "to": "Кому", + "sending": "Отправка транзакции", + "confirm_send": "Подтвердить отправку", + "confirm_transaction": "Подтвердить транзакцию", + "confirm_and_send": "Подтвердить и отправить", + "cancel": "Отмена", + + "receiving_addresses": "Ваши адреса для получения", + "new_z_shielded": "Новый z-адрес (защищённый)", + "new_t_transparent": "Новый t-адрес (прозрачный)", + "address_details": "Детали адреса", + "view_on_explorer": "Открыть в обозревателе", + "qr_code": "QR-код", + "request_payment": "Запросить платёж", + + "date": "Дата", + "status": "Статус", + "confirmations": "Подтверждения", + "confirmed": "Подтверждена", + "pending": "Ожидание", + "sent": "отправлено", + "received": "получено", + "mined": "добыто", + + "mining_control": "Управление майнингом", + "start_mining": "Начать майнинг", + "stop_mining": "Остановить майнинг", + "mining_threads": "Потоки майнинга", + "mining_statistics": "Статистика майнинга", + "local_hashrate": "Локальный хешрейт", + "network_hashrate": "Хешрейт сети", + "difficulty": "Сложность", + "est_time_to_block": "Ожидаемое время до блока", + "mining_off": "Майнинг ВЫКЛЮЧЕН", + "mining_on": "Майнинг ВКЛЮЧЁН", + + "connected_peers": "Подключённые узлы", + "banned_peers": "Заблокированные узлы", + "ip_address": "IP-адрес", + "version": "Версия", + "height": "Высота", + "ping": "Пинг", + "ban": "Блокировать", + "unban": "Разблокировать", + "clear_all_bans": "Снять все блокировки", + + "price_chart": "График цены", + "current_price": "Текущая цена", + "24h_change": "Изменение за 24ч", + "24h_volume": "Объём за 24ч", + "market_cap": "Рыночная кап.", + + "general": "Основные", + "display": "Отображение", + "network": "Сеть", + "theme": "Тема", + "language": "Язык", + "dragonx_green": "DragonX (зелёный)", + "dark": "Тёмная", + "light": "Светлая", + "allow_custom_fees": "Разрешить пользовательские комиссии", + "use_embedded_daemon": "Встроенный dragonxd", + "save": "Сохранить", + "close": "Закрыть", + + "file": "Файл", + "edit": "Редактировать", + "view": "Вид", + "help": "Помощь", + "import_private_key": "Импорт приватного ключа...", + "backup_wallet": "Резервное копирование кошелька...", + "exit": "Выход", + "about_dragonx": "О программе ObsidianDragon", + "refresh_now": "Обновить сейчас", + + "about": "О программе", + "import": "Импорт", + "export": "Экспорт", + "copy_to_clipboard": "Копировать в буфер обмена", + + "connected": "Подключён", + "disconnected": "Отключён", + "connecting": "Подключение...", + "syncing": "Синхронизация...", + "block": "Блок", + "no_addresses_available": "Нет доступных адресов", + + "error": "Ошибка", + "success": "Успешно", + "warning": "Предупреждение", + "amount_exceeds_balance": "Сумма превышает баланс", + "transaction_sent": "Транзакция успешно отправлена" +} diff --git a/res/lang/zh.json b/res/lang/zh.json new file mode 100644 index 0000000..a9d6bbe --- /dev/null +++ b/res/lang/zh.json @@ -0,0 +1,139 @@ +{ + "balance": "余额", + "send": "发送", + "receive": "接收", + "transactions": "交易记录", + "mining": "挖矿", + "peers": "节点", + "market": "市场", + "settings": "设置", + + "summary": "概览", + "shielded": "隐私地址", + "transparent": "透明地址", + "total": "总计", + "unconfirmed": "未确认", + "your_addresses": "您的地址", + "z_addresses": "Z-地址", + "t_addresses": "T-地址", + "no_addresses": "未找到地址。请使用上方按钮创建。", + "new_z_address": "新建 Z-地址", + "new_t_address": "新建 T-地址", + "type": "类型", + "address": "地址", + "copy_address": "复制完整地址", + "send_from_this_address": "从此地址发送", + "export_private_key": "导出私钥", + "export_viewing_key": "导出查看密钥", + "show_qr_code": "显示二维码", + "not_connected": "未连接到守护进程...", + + "pay_from": "付款地址", + "send_to": "收款地址", + "amount": "金额", + "memo": "备注(可选,已加密)", + "miner_fee": "矿工手续费", + "fee": "手续费", + "send_transaction": "发送交易", + "clear": "清除", + "select_address": "选择地址...", + "paste": "粘贴", + "max": "最大", + "available": "可用", + "invalid_address": "地址格式无效", + "memo_z_only": "注意:备注仅在发送到隐私(z)地址时可用", + "characters": "字符", + "from": "发送方", + "to": "接收方", + "sending": "正在发送交易", + "confirm_send": "确认发送", + "confirm_transaction": "确认交易", + "confirm_and_send": "确认并发送", + "cancel": "取消", + + "receiving_addresses": "您的接收地址", + "new_z_shielded": "新建 z-地址(隐私)", + "new_t_transparent": "新建 t-地址(透明)", + "address_details": "地址详情", + "view_on_explorer": "在浏览器查看", + "qr_code": "二维码", + "request_payment": "请求付款", + + "date": "日期", + "status": "状态", + "confirmations": "确认数", + "confirmed": "已确认", + "pending": "待确认", + "sent": "已发送", + "received": "已接收", + "mined": "已挖出", + + "mining_control": "挖矿控制", + "start_mining": "开始挖矿", + "stop_mining": "停止挖矿", + "mining_threads": "挖矿线程", + "mining_statistics": "挖矿统计", + "local_hashrate": "本地算力", + "network_hashrate": "全网算力", + "difficulty": "难度", + "est_time_to_block": "预计出块时间", + "mining_off": "挖矿已关闭", + "mining_on": "挖矿已开启", + + "connected_peers": "已连接节点", + "banned_peers": "已封禁节点", + "ip_address": "IP 地址", + "version": "版本", + "height": "高度", + "ping": "延迟", + "ban": "封禁", + "unban": "解封", + "clear_all_bans": "清除所有封禁", + + "price_chart": "价格图表", + "current_price": "当前价格", + "24h_change": "24小时涨跌", + "24h_volume": "24小时成交量", + "market_cap": "市值", + + "general": "通用", + "display": "显示", + "network": "网络", + "theme": "主题", + "language": "语言", + "dragonx_green": "DragonX(绿色)", + "dark": "深色", + "light": "浅色", + "allow_custom_fees": "允许自定义手续费", + "use_embedded_daemon": "使用内置 dragonxd", + "save": "保存", + "close": "关闭", + + "file": "文件", + "edit": "编辑", + "view": "查看", + "help": "帮助", + "import_private_key": "导入私钥...", + "backup_wallet": "备份钱包...", + "exit": "退出", + "about_dragonx": "关于 ObsidianDragon", + "refresh_now": "立即刷新", + + "about": "关于", + "import": "导入", + "export": "导出", + "copy_to_clipboard": "复制到剪贴板", + + "connected": "已连接", + "disconnected": "已断开", + "connecting": "连接中...", + "syncing": "同步中...", + "block": "区块", + "no_addresses_available": "暂无可用地址", + + "error": "错误", + "success": "成功", + "warning": "警告", + "amount_exceeds_balance": "金额超出余额", + "transaction_sent": "交易发送成功" +} diff --git a/res/themes/color-pop-dark.toml b/res/themes/color-pop-dark.toml new file mode 100644 index 0000000..c100911 --- /dev/null +++ b/res/themes/color-pop-dark.toml @@ -0,0 +1,161 @@ +[theme] +name = "Color Pop Dark" +author = "The Hush Developers" +dark = true +elevation = { --elevation-0 = "#121218", --elevation-1 = "#1C1C24", --elevation-2 = "#26262E", --elevation-3 = "#303038", --elevation-4 = "#3A3A44" } +images = { background_image = "backgrounds/texture/pop-dark_bg.png", logo = "logos/logo_ObsidianDragon_dark.png" } + +[theme.palette] +--primary = "#7C6CFF" +--primary-variant = "#5B4AE6" +--primary-light = "#A89CFF" +--secondary = "#FF6EC7" +--secondary-variant = "#E050A8" +--secondary-light = "#FF9CDC" +--background = "#0E0E14" +--surface = "#161620" +--surface-variant = "#20202C" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#E8E6F0" +--on-surface = "#E8E6F0" +--on-surface-medium = "rgba(232,230,240,0.72)" +--on-surface-disabled = "rgba(232,230,240,0.40)" +--error = "#FF5C72" +--on-error = "#000000" +--success = "#3DE8A0" +--on-success = "#000000" +--warning = "#FFB740" +--on-warning = "#000000" +--divider = "rgba(200,190,240,0.12)" +--outline = "rgba(200,190,240,0.14)" +--scrim = "rgba(0,0,0,0.55)" +--surface-hover = "rgba(200,190,240,0.06)" +--surface-alt = "rgba(200,190,240,0.03)" +--surface-active = "rgba(200,190,240,0.10)" +--glass-button = "rgba(124,108,255,0.08)" +--glass-button-hover = "rgba(124,108,255,0.16)" +--card-border = "rgba(200,190,240,0.10)" +--text-shadow = "rgba(0,0,0,0.45)" +--input-overlay-text = "rgba(232,230,240,0.25)" +--slider-text = "rgba(232,230,240,0.82)" +--thumb-fill = "rgba(124,108,255,0.18)" +--thumb-border = "rgba(124,108,255,0.50)" +--disabled-label = "rgba(200,190,240,0.18)" +--chart-grid = "rgba(200,190,240,0.05)" +--chart-crosshair = "rgba(200,190,240,0.14)" +--chart-hover-ring = "rgba(124,108,255,0.35)" +--tooltip-bg = "rgba(14,14,22,0.94)" +--tooltip-border = "rgba(124,108,255,0.18)" +--glass-fill = "rgba(200,190,240,0.06)" +--glass-border = "rgba(200,190,240,0.10)" +--glass-noise-tint = "rgba(124,108,255,0.03)" +--tactile-top = "rgba(200,190,240,0.07)" +--tactile-bottom = "rgba(200,190,240,0.0)" +--hover-overlay = "rgba(124,108,255,0.05)" +--active-overlay = "rgba(124,108,255,0.10)" +--rim-light = "rgba(124,108,255,0.10)" +--status-divider = "rgba(200,190,240,0.06)" +--sidebar-hover = "rgba(124,108,255,0.10)" +--sidebar-icon = "rgba(232,230,240,0.45)" +--sidebar-badge = "rgba(232,230,240,1.0)" +--sidebar-divider = "rgba(200,190,240,0.05)" +--chart-line = "rgba(124,108,255,0.12)" +--window-control = "rgba(232,230,240,0.72)" +--window-control-hover = "rgba(124,108,255,0.12)" +--window-close-hover = "rgba(255,92,114,0.75)" +--spinner-track = "rgba(200,190,240,0.08)" +--spinner-active = "rgba(124,108,255,0.85)" +--shutdown-panel-bg = "rgba(12,12,18,0.92)" +--shutdown-panel-border = "rgba(124,108,255,0.10)" +--ram-bar-app = "#7C6CFF" +--ram-bar-system = "rgba(255,255,255,0.12)" +--accent-total = "#7C6CFF" +--accent-shielded = "#3DE8A0" +--accent-transparent = "#FFB740" +--accent-action = "#FF6EC7" +--accent-market = "#00E5FF" +--accent-portfolio = "#A89CFF" +--toast-info-accent = "#7C6CFF" +--toast-info-text = "#A89CFF" +--toast-success-accent = "rgba(61,232,160,1.0)" +--toast-success-text = "rgba(120,255,190,1.0)" +--toast-warning-accent = "rgba(255,183,64,1.0)" +--toast-warning-text = "rgba(255,215,130,1.0)" +--toast-error-accent = "rgba(255,92,114,1.0)" +--toast-error-text = "rgba(255,160,170,1.0)" +--snackbar-bg = "rgba(30,30,42,0.95)" +--snackbar-text = "rgba(232,230,240,0.87)" +--snackbar-action = "rgba(124,108,255,1.0)" +--snackbar-action-hover = "rgba(168,156,255,1.0)" +--switch-track-off = "rgba(200,190,240,0.12)" +--switch-track-on = "rgba(124,108,255,0.45)" +--switch-thumb-off = "#A0A0B0" +--switch-thumb-on = "#E0DCFF" +--control-shadow = "rgba(0,0,0,0.28)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(0,0,0,0.22)" + +[backdrop] +base-color-top = "rgba(16,16,24,210)" +base-color-bottom = "rgba(10,10,16,210)" +texture-tint-alpha = 100 +gradient-top-r = 14 +gradient-top-g = 14 +gradient-top-b = 22 +gradient-top-a = 80 +gradient-bottom-r = 8 +gradient-bottom-g = 8 +gradient-bottom-b = 14 +gradient-bottom-a = 60 +background-alpha = 0.52 +surface-alpha = 0.58 +frame-alpha = 0.78 +surface-inline-alpha = 0.60 +background-inline-alpha = 0.45 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Color Pop Dark (soft neon under-glow) +# Neon purple/pink hue-cycling and prismatic borders, but no shimmer sweep. +# The glow breathes slowly like a neon sign warming up. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 1.0 } +hue-cycle-speed = { size = 0.08 } +hue-cycle-saturation = { size = 0.70 } +hue-cycle-value = { size = 0.88 } +hue-cycle-range = { size = 0.35 } +hue-cycle-offset = { size = 0.72 } + +rainbow-border-enabled = { size = 1.0 } +rainbow-border-speed = { size = 0.06 } +rainbow-border-alpha = { size = 0.22 } +rainbow-border-stop-0 = { color = "#7C6CFF" } +rainbow-border-stop-1 = { color = "#FF6EC7" } +rainbow-border-stop-2 = { color = "#00E5FF" } + +shimmer-enabled = { size = 0.0 } + +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 0.0 } + +edge-trace-enabled = { size = 0.0 } + +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — neon color bleed +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.10 } +viewport-wash-tl = { color = "#7C6CFF" } +viewport-wash-tr = { color = "#FF6EC7" } +viewport-wash-bl = { color = "#00E5FF" } +viewport-wash-br = { color = "#FF3D71" } +viewport-wash-rotate = { size = 0.0 } +viewport-wash-pulse = { size = 0.2 } +viewport-wash-pulse-depth = { size = 0.4 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#0A0020" } +viewport-vignette-radius = { size = 0.20 } +viewport-vignette-alpha = { size = 0.25 } diff --git a/res/themes/color-pop-light.toml b/res/themes/color-pop-light.toml new file mode 100644 index 0000000..6e11d66 --- /dev/null +++ b/res/themes/color-pop-light.toml @@ -0,0 +1,161 @@ +[theme] +name = "Color Pop Light" +author = "The Hush Developers" +dark = false +elevation = { --elevation-0 = "#FAFAFE", --elevation-1 = "#F2F2FA", --elevation-2 = "#EAEAF4", --elevation-3 = "#DDDDE8", --elevation-4 = "#CCCCD8" } +images = { background_image = "backgrounds/texture/pop-light_bg.png", logo = "logos/logo_ObsidianDragon_light.png" } + +[theme.palette] +--primary = "#6040E0" +--primary-variant = "#4A28CC" +--primary-light = "#8B72F0" +--secondary = "#E040A0" +--secondary-variant = "#C42888" +--secondary-light = "#F070BC" +--background = "#F8F8FE" +--surface = "#FFFFFF" +--surface-variant = "#F4F4FC" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#1E1E2A" +--on-surface = "#1E1E2A" +--on-surface-medium = "rgba(30,30,42,0.72)" +--on-surface-disabled = "rgba(30,30,42,0.38)" +--error = "#E0304A" +--on-error = "#FFFFFF" +--success = "#18A860" +--on-success = "#FFFFFF" +--warning = "#E09020" +--on-warning = "#000000" +--divider = "rgba(30,30,60,0.12)" +--outline = "rgba(30,30,60,0.15)" +--scrim = "rgba(0,0,0,0.45)" +--surface-hover = "rgba(96,64,224,0.05)" +--surface-alt = "rgba(96,64,224,0.02)" +--surface-active = "rgba(96,64,224,0.10)" +--glass-button = "rgba(96,64,224,0.06)" +--glass-button-hover = "rgba(96,64,224,0.12)" +--card-border = "rgba(30,30,60,0.08)" +--text-shadow = "rgba(0,0,0,0.08)" +--input-overlay-text = "rgba(30,30,42,0.26)" +--slider-text = "rgba(30,30,42,0.76)" +--thumb-fill = "rgba(96,64,224,0.14)" +--thumb-border = "rgba(96,64,224,0.40)" +--disabled-label = "rgba(30,30,60,0.22)" +--chart-grid = "rgba(30,30,60,0.06)" +--chart-crosshair = "rgba(30,30,60,0.18)" +--chart-hover-ring = "rgba(96,64,224,0.30)" +--tooltip-bg = "rgba(36,34,52,0.94)" +--tooltip-border = "rgba(96,64,224,0.16)" +--glass-fill = "rgba(255,255,255,0.55)" +--glass-border = "rgba(30,30,60,0.10)" +--glass-noise-tint = "rgba(96,64,224,0.02)" +--tactile-top = "rgba(255,255,255,0.40)" +--tactile-bottom = "rgba(255,255,255,0.05)" +--hover-overlay = "rgba(96,64,224,0.04)" +--active-overlay = "rgba(96,64,224,0.08)" +--rim-light = "rgba(96,64,224,0.06)" +--status-divider = "rgba(30,30,60,0.08)" +--sidebar-hover = "rgba(96,64,224,0.07)" +--sidebar-icon = "rgba(30,30,42,0.50)" +--sidebar-badge = "rgba(30,30,42,0.85)" +--sidebar-divider = "rgba(30,30,60,0.06)" +--chart-line = "rgba(96,64,224,0.10)" +--window-control = "rgba(30,30,42,0.65)" +--window-control-hover = "rgba(96,64,224,0.08)" +--window-close-hover = "rgba(224,48,74,0.80)" +--spinner-track = "rgba(30,30,60,0.10)" +--spinner-active = "rgba(96,64,224,0.85)" +--shutdown-panel-bg = "rgba(248,248,254,0.95)" +--shutdown-panel-border = "rgba(96,64,224,0.10)" +--ram-bar-app = "#6040E0" +--ram-bar-system = "rgba(30,30,60,0.15)" +--accent-total = "#6040E0" +--accent-shielded = "#18A860" +--accent-transparent = "#E09020" +--accent-action = "#E040A0" +--accent-market = "#00B8D4" +--accent-portfolio = "#8B72F0" +--toast-info-accent = "#6040E0" +--toast-info-text = "#4A28CC" +--toast-success-accent = "rgba(24,168,96,1.0)" +--toast-success-text = "rgba(12,130,68,1.0)" +--toast-warning-accent = "rgba(224,144,32,1.0)" +--toast-warning-text = "rgba(180,108,10,1.0)" +--toast-error-accent = "rgba(224,48,74,1.0)" +--toast-error-text = "rgba(180,28,50,1.0)" +--snackbar-bg = "rgba(40,38,56,0.95)" +--snackbar-text = "rgba(245,244,252,0.87)" +--snackbar-action = "rgba(139,114,240,1.0)" +--snackbar-action-hover = "rgba(168,148,255,1.0)" +--switch-track-off = "rgba(30,30,60,0.24)" +--switch-track-on = "rgba(96,64,224,0.38)" +--switch-thumb-off = "#F8F8FC" +--switch-thumb-on = "#FFFFFF" +--control-shadow = "rgba(0,0,0,0.18)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(0,0,0,0.08)" + +[backdrop] +base-color-top = "rgba(252,252,255,255)" +base-color-bottom = "rgba(244,244,252,255)" +texture-tint-alpha = 80 +gradient-top-r = 250 +gradient-top-g = 250 +gradient-top-b = 255 +gradient-top-a = 240 +gradient-bottom-r = 242 +gradient-bottom-g = 242 +gradient-bottom-b = 252 +gradient-bottom-a = 220 +background-alpha = 0.97 +surface-alpha = 0.97 +frame-alpha = 0.94 +surface-inline-alpha = 0.95 +background-inline-alpha = 0.94 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Color Pop Light (gentle neon) +# Softer neon hue-cycling and rainbow borders on a light background. +# Lower saturation and slower speeds keep it elegant. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 1.0 } +hue-cycle-speed = { size = 0.04 } +hue-cycle-saturation = { size = 0.50 } +hue-cycle-value = { size = 0.78 } +hue-cycle-range = { size = 0.35 } +hue-cycle-offset = { size = 0.72 } + +rainbow-border-enabled = { size = 1.0 } +rainbow-border-speed = { size = 0.05 } +rainbow-border-alpha = { size = 0.38 } +rainbow-border-stop-0 = { color = "#7C6CFF" } +rainbow-border-stop-1 = { color = "#FF6EC7" } +rainbow-border-stop-2 = { color = "#00E5FF" } + +shimmer-enabled = { size = 0.0 } + +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 0.0 } + +edge-trace-enabled = { size = 0.0 } + +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — soft neon tint +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.06 } +viewport-wash-tl = { color = "#7C6CFF" } +viewport-wash-tr = { color = "#FF6EC7" } +viewport-wash-bl = { color = "#00E5FF" } +viewport-wash-br = { color = "#FF3D71" } +viewport-wash-rotate = { size = 0.0 } +viewport-wash-pulse = { size = 0.15 } +viewport-wash-pulse-depth = { size = 0.25 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#20182A" } +viewport-vignette-radius = { size = 0.18 } +viewport-vignette-alpha = { size = 0.12 } diff --git a/res/themes/dark.toml b/res/themes/dark.toml new file mode 100644 index 0000000..6b00125 --- /dev/null +++ b/res/themes/dark.toml @@ -0,0 +1,142 @@ +[theme] +name = "Dark" +author = "The Hush Developers" +dark = true +elevation = { --elevation-0 = "#161618", --elevation-1 = "#222224", --elevation-2 = "#2C2C2E", --elevation-3 = "#363638", --elevation-4 = "#404044" } +images = { background_image = "backgrounds/texture/dark_bg.png", logo = "logos/logo_ObsidianDragon_dark.png" } + +[theme.palette] +--primary = "#9AAFC8" +--primary-variant = "#7B92B0" +--primary-light = "#B8CCE0" +--secondary = "#7DABA3" +--secondary-variant = "#5D8A82" +--secondary-light = "#9DC5BE" +--background = "#141416" +--surface = "#1A1A1C" +--surface-variant = "#262628" +--on-primary = "#000000" +--on-secondary = "#000000" +--on-background = "#D0D0D4" +--on-surface = "#D0D0D4" +--on-surface-medium = "rgba(208,208,212,0.75)" +--on-surface-disabled = "rgba(208,208,212,0.45)" +--error = "#B07080" +--on-error = "#000000" +--success = "#7AAE7C" +--on-success = "#000000" +--warning = "#C4A870" +--on-warning = "#000000" +--divider = "rgba(220,220,225,0.14)" +--outline = "rgba(220,220,225,0.14)" +--scrim = "rgba(0,0,0,0.5)" +--surface-hover = "rgba(220,220,225,0.06)" +--surface-alt = "rgba(220,220,225,0.04)" +--surface-active = "rgba(220,220,225,0.08)" +--glass-button = "rgba(220,220,225,0.05)" +--glass-button-hover = "rgba(220,220,225,0.10)" +--card-border = "rgba(220,220,225,0.12)" +--text-shadow = "rgba(0,0,0,0.40)" +--input-overlay-text = "rgba(208,208,212,0.28)" +--slider-text = "rgba(208,208,212,0.85)" +--thumb-fill = "rgba(220,220,225,0.14)" +--thumb-border = "rgba(220,220,225,0.45)" +--disabled-label = "rgba(220,220,225,0.18)" +--chart-grid = "rgba(220,220,225,0.04)" +--chart-crosshair = "rgba(220,220,225,0.14)" +--chart-hover-ring = "rgba(220,220,225,0.28)" +--tooltip-bg = "rgba(18,18,22,0.92)" +--tooltip-border = "rgba(220,220,225,0.10)" +--glass-fill = "rgba(220,220,225,0.07)" +--glass-border = "rgba(220,220,225,0.12)" +--glass-noise-tint = "rgba(220,220,225,0.03)" +--tactile-top = "rgba(220,220,225,0.06)" +--tactile-bottom = "rgba(220,220,225,0.0)" +--hover-overlay = "rgba(220,220,225,0.04)" +--active-overlay = "rgba(220,220,225,0.08)" +--rim-light = "rgba(220,220,225,0.08)" +--status-divider = "rgba(220,220,225,0.06)" +--sidebar-hover = "rgba(220,220,225,0.08)" +--sidebar-icon = "rgba(220,220,225,0.40)" +--sidebar-badge = "rgba(208,208,212,1.0)" +--sidebar-divider = "rgba(220,220,225,0.05)" +--chart-line = "rgba(220,220,225,0.08)" +--window-control = "rgba(208,208,212,0.75)" +--window-control-hover = "rgba(220,220,225,0.10)" +--window-close-hover = "rgba(200,50,60,0.70)" +--spinner-track = "rgba(220,220,225,0.08)" +--spinner-active = "rgba(154,175,200,0.85)" +--shutdown-panel-bg = "rgba(14,14,18,0.88)" +--shutdown-panel-border = "rgba(220,220,225,0.06)" +--ram-bar-app = "#5C9CE6" +--ram-bar-system = "rgba(255,255,255,0.15)" +--accent-total = "#B8CCE0" +--accent-shielded = "#7DABA3" +--accent-transparent = "#C4A870" +--accent-action = "#9AAFC8" +--accent-market = "#7DABA3" +--accent-portfolio = "#B8CCE0" +--toast-info-accent = "#9AAFC8" +--toast-info-text = "#B8CCE0" +--toast-success-accent = "rgba(80,155,85,1.0)" +--toast-success-text = "rgba(180,230,180,1.0)" +--toast-warning-accent = "rgba(180,150,75,1.0)" +--toast-warning-text = "rgba(235,215,140,1.0)" +--toast-error-accent = "rgba(175,75,80,1.0)" +--toast-error-text = "rgba(235,160,160,1.0)" +--snackbar-bg = "rgba(45,45,48,0.95)" +--snackbar-text = "rgba(208,208,212,0.87)" +--snackbar-action = "rgba(154,175,200,1.0)" +--snackbar-action-hover = "rgba(184,204,224,1.0)" +--switch-track-off = "rgba(220,220,225,0.10)" +--switch-track-on = "rgba(154,175,200,0.40)" +--switch-thumb-off = "#A0A0A4" +--switch-thumb-on = "#D8D8DC" +--control-shadow = "rgba(0,0,0,0.22)" +--checkbox-check = "#000000" +--app-bar-shadow = "rgba(0,0,0,0.18)" + +[backdrop] +base-color-top = "rgba(20,22,28,200)" +base-color-bottom = "rgba(10,11,16,200)" +texture-tint-alpha = 120 +gradient-top-r = 14 +gradient-top-g = 15 +gradient-top-b = 20 +gradient-top-a = 80 +gradient-bottom-r = 8 +gradient-bottom-g = 9 +gradient-bottom-b = 13 +gradient-bottom-a = 60 +background-alpha = 0.52 +surface-alpha = 0.58 +frame-alpha = 0.78 +surface-inline-alpha = 0.60 +background-inline-alpha = 0.45 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Dark (minimal, clean) +# Near-static soft glow behind active button. Professional and understated. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 0.0 } +rainbow-border-enabled = { size = 0.0 } +shimmer-enabled = { size = 0.0 } +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 1.0 } +glow-pulse-speed = { size = 0.25 } +glow-pulse-min-alpha = { size = 0.02 } +glow-pulse-max-alpha = { size = 0.04 } +glow-pulse-radius = { size = 2.0 } +glow-pulse-color = { color = "var(--primary)" } + +edge-trace-enabled = { size = 0.0 } +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — subtle neutral vignette +viewport-wash-enabled = { size = 0.0 } +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#000000" } +viewport-vignette-radius = { size = 0.20 } +viewport-vignette-alpha = { size = 0.08 } diff --git a/res/themes/dune.toml b/res/themes/dune.toml new file mode 100644 index 0000000..9e5589c --- /dev/null +++ b/res/themes/dune.toml @@ -0,0 +1,180 @@ +[theme] +name = "Dune" +author = "The Hush Developers" +dark = false +images = { background_image = "backgrounds/texture/dune_bg.png", logo = "logos/logo_ObsidianDragon_light.png" } +elevation = { --elevation-0 = "#FDF8F0", --elevation-1 = "#F5EDE0", --elevation-2 = "#EDE3D4", --elevation-3 = "#E0D5C4", --elevation-4 = "#D0C4B0" } + +[theme.palette] +# Dune: warm desert tones — amber, sand, terracotta, sage +--primary = "#B07840" +--primary-variant = "#8E5E2E" +--primary-light = "#D4A06C" +--secondary = "#8A9A6C" +--secondary-variant = "#6B7E50" +--secondary-light = "#A8B890" +--background = "#FAF5ED" +--surface = "#FFFFF8" +--surface-variant = "#F5EDE0" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#3A2E22" +--on-surface = "#3A2E22" +--on-surface-medium = "rgba(58,46,34,0.68)" +--on-surface-disabled = "rgba(58,46,34,0.38)" +--error = "#A0524A" +--on-error = "#FFFFFF" +--success = "#6A8A5C" +--on-success = "#FFFFFF" +--warning = "#C08840" +--on-warning = "#000000" +--divider = "rgba(140,110,70,0.14)" +--outline = "rgba(140,110,70,0.16)" +--scrim = "rgba(30,20,10,0.45)" +--surface-hover = "rgba(176,120,64,0.06)" +--surface-alt = "rgba(176,120,64,0.03)" +--surface-active = "rgba(176,120,64,0.10)" +--glass-button = "rgba(176,120,64,0.06)" +--glass-button-hover = "rgba(176,120,64,0.12)" +--card-border = "rgba(176,120,64,0.12)" +--text-shadow = "rgba(80,50,20,0.08)" +--input-overlay-text = "rgba(58,46,34,0.28)" +--slider-text = "rgba(58,46,34,0.78)" +--thumb-fill = "rgba(176,120,64,0.12)" +--thumb-border = "rgba(176,120,64,0.35)" +--disabled-label = "rgba(58,46,34,0.22)" +--chart-grid = "rgba(176,120,64,0.07)" +--chart-crosshair = "rgba(176,120,64,0.18)" +--chart-hover-ring = "rgba(176,120,64,0.28)" +--tooltip-bg = "rgba(50,38,24,0.94)" +--tooltip-border = "rgba(176,120,64,0.12)" +--glass-fill = "rgba(255,252,245,0.58)" +--glass-border = "rgba(176,120,64,0.14)" +--glass-noise-tint = "rgba(180,140,80,0.03)" +--tactile-top = "rgba(255,255,248,0.50)" +--tactile-bottom = "rgba(255,255,248,0.08)" +--hover-overlay = "rgba(176,120,64,0.05)" +--active-overlay = "rgba(176,120,64,0.10)" +--rim-light = "rgba(212,160,108,0.10)" +--status-divider = "rgba(176,120,64,0.10)" +--sidebar-hover = "rgba(176,120,64,0.08)" +--sidebar-icon = "rgba(58,46,34,0.50)" +--sidebar-badge = "rgba(58,46,34,0.85)" +--sidebar-divider = "rgba(176,120,64,0.08)" +--chart-line = "rgba(176,120,64,0.10)" +--window-control = "rgba(58,46,34,0.65)" +--window-control-hover = "rgba(176,120,64,0.10)" +--window-close-hover = "rgba(160,82,74,0.78)" +--spinner-track = "rgba(176,120,64,0.12)" +--spinner-active = "rgba(176,120,64,0.85)" +--shutdown-panel-bg = "rgba(250,245,237,0.96)" +--shutdown-panel-border = "rgba(176,120,64,0.10)" +# RAM bar: desert gold +--ram-bar-app = "#B07840" +--ram-bar-system = "rgba(58,46,34,0.14)" +# Accent strips: desert palette — amber, sage, terracotta, gold, olive, sand +--accent-total = "#B07840" +--accent-shielded = "#8A9A6C" +--accent-transparent = "#C4786A" +--accent-action = "#B07840" +--accent-market = "#6B7E50" +--accent-portfolio = "#C08840" +# Toasts: warm desert tones +--toast-info-accent = "#B07840" +--toast-info-text = "#8E5E2E" +--toast-success-accent = "rgba(106,138,92,1.0)" +--toast-success-text = "rgba(80,112,66,1.0)" +--toast-warning-accent = "rgba(192,136,64,1.0)" +--toast-warning-text = "rgba(160,108,40,1.0)" +--toast-error-accent = "rgba(160,82,74,1.0)" +--toast-error-text = "rgba(130,58,50,1.0)" +# Snackbar +--snackbar-bg = "rgba(50,38,24,0.95)" +--snackbar-text = "rgba(255,252,245,0.87)" +--snackbar-action = "rgba(212,160,108,1.0)" +--snackbar-action-hover = "rgba(236,190,140,1.0)" +# Controls +--switch-track-off = "rgba(58,46,34,0.22)" +--switch-track-on = "rgba(176,120,64,0.40)" +--switch-thumb-off = "#F5EDE0" +--switch-thumb-on = "#FFFFFF" +--control-shadow = "rgba(80,50,20,0.16)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(80,50,20,0.08)" + +[backdrop] +base-color-top = "rgba(253,248,240,255)" +base-color-bottom = "rgba(240,228,208,255)" +texture-tint-alpha = 100 +gradient-top-r = 252 +gradient-top-g = 246 +gradient-top-b = 235 +gradient-top-a = 240 +gradient-bottom-r = 238 +gradient-bottom-g = 222 +gradient-bottom-b = 198 +gradient-bottom-a = 230 +background-alpha = 0.96 +surface-alpha = 0.96 +frame-alpha = 0.93 +surface-inline-alpha = 0.94 +background-inline-alpha = 0.93 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Dune (desert sandstorm) +# Wind-driven sand particles with heat shimmer and warm atmosphere. +# The sandstorm effect creates directional particles blowing across +# the viewport with motion streaks, gusts, and dust puffs. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 0.0 } +rainbow-border-enabled = { size = 0.0 } + +# Slow, wide warm shimmer — like heat mirage on sand +shimmer-enabled = { size = 1.0 } +shimmer-speed = { size = 0.025 } +shimmer-width = { size = 200.0 } +shimmer-alpha = { size = 0.06 } +shimmer-angle = { size = 15.0 } +shimmer-color = { color = "rgba(212,170,108,1.0)" } + +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 1.0 } +glow-pulse-speed = { size = 0.15 } +glow-pulse-min-alpha = { size = 0.02 } +glow-pulse-max-alpha = { size = 0.08 } +glow-pulse-radius = { size = 2.5 } +glow-pulse-color = { color = "#B07840" } + +edge-trace-enabled = { size = 0.0 } +ember-rise-enabled = { size = 0.0 } +gradient-border-enabled = { size = 0.0 } + +# === Sandstorm: wind-driven sand particles === +sandstorm-enabled = { size = 1.0 } +sandstorm-count = { size = 90.0 } +sandstorm-speed = { size = 0.25 } +sandstorm-wind-angle = { size = 12.0 } +sandstorm-particle-size = { size = 2.4 } +sandstorm-alpha = { size = 0.55 } +sandstorm-color = { color = "#8B6914" } +sandstorm-gust-speed = { size = 0.06 } +sandstorm-gust-strength = { size = 0.45 } +sandstorm-streak-length = { size = 4.0 } + +# Warm desert atmosphere — orange-gold heat haze +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.10 } +viewport-wash-tl = { color = "#C89050" } +viewport-wash-tr = { color = "#A0784C" } +viewport-wash-bl = { color = "#8A6A40" } +viewport-wash-br = { color = "#D4A060" } +viewport-wash-rotate = { size = 0.01 } +viewport-wash-pulse = { size = 0.06 } +viewport-wash-pulse-depth = { size = 0.35 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#1A1008" } +viewport-vignette-radius = { size = 0.22 } +viewport-vignette-alpha = { size = 0.10 } diff --git a/res/themes/iridescent.toml b/res/themes/iridescent.toml new file mode 100644 index 0000000..ba2fd7f --- /dev/null +++ b/res/themes/iridescent.toml @@ -0,0 +1,177 @@ +[theme] +name = "Iridescent" +author = "The Hush Developers" +dark = false +images = { background_image = "backgrounds/texture/iridescent_bg.png", logo = "logos/logo_ObsidianDragon_light.png" } +elevation = { --elevation-0 = "#FDFBFF", --elevation-1 = "#F5F0FA", --elevation-2 = "#EDE6F4", --elevation-3 = "#E0D8EC", --elevation-4 = "#D0C8DC" } + +[theme.palette] +# Iridescent: opalescent pastels — shifting pink ↔ lavender ↔ teal +--primary = "#8E6BAF" +--primary-variant = "#6A3D9A" +--primary-light = "#C9A8E8" +--secondary = "#4DB6AC" +--secondary-variant = "#00897B" +--secondary-light = "#80CBC4" +--background = "#FAF8FF" +--surface = "#FFFFFF" +--surface-variant = "#F3EFF8" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#1C1525" +--on-surface = "#1C1525" +--on-surface-medium = "rgba(28,21,37,0.72)" +--on-surface-disabled = "rgba(28,21,37,0.40)" +--error = "#C62828" +--on-error = "#FFFFFF" +--success = "#2E7D32" +--on-success = "#FFFFFF" +--warning = "#E65100" +--on-warning = "#000000" +--divider = "rgba(120,80,160,0.12)" +--outline = "rgba(120,80,160,0.14)" +--scrim = "rgba(20,10,30,0.45)" +--surface-hover = "rgba(140,107,175,0.06)" +--surface-alt = "rgba(140,107,175,0.03)" +--surface-active = "rgba(140,107,175,0.10)" +--glass-button = "rgba(140,107,175,0.06)" +--glass-button-hover = "rgba(140,107,175,0.12)" +--card-border = "rgba(140,107,175,0.12)" +--text-shadow = "rgba(80,40,120,0.08)" +--input-overlay-text = "rgba(28,21,37,0.28)" +--slider-text = "rgba(28,21,37,0.78)" +--thumb-fill = "rgba(140,107,175,0.12)" +--thumb-border = "rgba(140,107,175,0.35)" +--disabled-label = "rgba(28,21,37,0.22)" +--chart-grid = "rgba(140,107,175,0.07)" +--chart-crosshair = "rgba(140,107,175,0.18)" +--chart-hover-ring = "rgba(140,107,175,0.28)" +--tooltip-bg = "rgba(32,24,48,0.94)" +--tooltip-border = "rgba(140,107,175,0.12)" +--glass-fill = "rgba(255,255,255,0.55)" +--glass-border = "rgba(140,107,175,0.14)" +--glass-noise-tint = "rgba(180,140,220,0.03)" +--tactile-top = "rgba(255,255,255,0.50)" +--tactile-bottom = "rgba(255,255,255,0.08)" +--hover-overlay = "rgba(140,107,175,0.05)" +--active-overlay = "rgba(140,107,175,0.10)" +--rim-light = "rgba(180,140,255,0.10)" +--status-divider = "rgba(140,107,175,0.10)" +--sidebar-hover = "rgba(140,107,175,0.08)" +--sidebar-icon = "rgba(28,21,37,0.50)" +--sidebar-badge = "rgba(28,21,37,0.85)" +--sidebar-divider = "rgba(140,107,175,0.08)" +--chart-line = "rgba(140,107,175,0.10)" +--window-control = "rgba(28,21,37,0.65)" +--window-control-hover = "rgba(140,107,175,0.10)" +--window-close-hover = "rgba(220,30,50,0.78)" +--spinner-track = "rgba(140,107,175,0.12)" +--spinner-active = "rgba(142,107,175,0.85)" +--shutdown-panel-bg = "rgba(248,244,255,0.96)" +--shutdown-panel-border = "rgba(140,107,175,0.10)" +# RAM bar: iridescent violet accent +--ram-bar-app = "#8E6BAF" +--ram-bar-system = "rgba(28,21,37,0.14)" +# Accent strips: opalescent palette — pink, teal, coral, violet, sea-green, lavender +--accent-total = "#B06AB3" +--accent-shielded = "#4DB6AC" +--accent-transparent = "#F48FB1" +--accent-action = "#7E57C2" +--accent-market = "#26A69A" +--accent-portfolio = "#AB47BC" +# Toasts: soft iridescent tones +--toast-info-accent = "#8E6BAF" +--toast-info-text = "#5E35B1" +--toast-success-accent = "rgba(46,125,50,1.0)" +--toast-success-text = "rgba(27,94,32,1.0)" +--toast-warning-accent = "rgba(230,81,0,1.0)" +--toast-warning-text = "rgba(191,54,12,1.0)" +--toast-error-accent = "rgba(198,40,40,1.0)" +--toast-error-text = "rgba(183,28,28,1.0)" +# Snackbar +--snackbar-bg = "rgba(40,30,55,0.95)" +--snackbar-text = "rgba(255,255,255,0.87)" +--snackbar-action = "rgba(206,147,216,1.0)" +--snackbar-action-hover = "rgba(225,190,255,1.0)" +# Controls +--switch-track-off = "rgba(28,21,37,0.22)" +--switch-track-on = "rgba(142,107,175,0.40)" +--switch-thumb-off = "#F5F0FA" +--switch-thumb-on = "#FFFFFF" +--control-shadow = "rgba(80,40,120,0.16)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(80,40,120,0.08)" + +[backdrop] +base-color-top = "rgba(253,248,255,255)" +base-color-bottom = "rgba(240,232,252,255)" +texture-tint-alpha = 90 +gradient-top-r = 252 +gradient-top-g = 248 +gradient-top-b = 255 +gradient-top-a = 240 +gradient-bottom-r = 235 +gradient-bottom-g = 225 +gradient-bottom-b = 248 +gradient-bottom-a = 230 +background-alpha = 0.97 +surface-alpha = 0.97 +frame-alpha = 0.94 +surface-inline-alpha = 0.95 +background-inline-alpha = 0.94 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Iridescent (opalescent color-shifting) +# The signature rainbow theme — gentle prismatic borders, slow pastel +# hue-cycling, and a wide ethereal sheen like light through an opal. +# All effects enabled but softened for a dreamy rather than flashy look. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 1.0 } +hue-cycle-speed = { size = 0.06 } +hue-cycle-saturation = { size = 0.50 } +hue-cycle-value = { size = 0.82 } +hue-cycle-range = { size = 1.0 } +hue-cycle-offset = { size = 0.83 } + +rainbow-border-enabled = { size = 1.0 } +rainbow-border-speed = { size = 0.05 } +rainbow-border-alpha = { size = 0.40 } +rainbow-border-stop-0 = { color = "#FF6B9D" } +rainbow-border-stop-1 = { color = "#C084FC" } +rainbow-border-stop-2 = { color = "#67E8F9" } +rainbow-border-stop-3 = { color = "#FCA5A5" } + +shimmer-enabled = { size = 1.0 } +shimmer-speed = { size = 0.04 } +shimmer-width = { size = 150.0 } +shimmer-alpha = { size = 0.05 } +shimmer-angle = { size = 20.0 } +shimmer-color = { color = "rgba(255,240,255,1.0)" } + +positional-hue-enabled = { size = 1.0 } +positional-hue-top = { color = "#E088B8" } +positional-hue-bottom = { color = "#60B8B4" } +positional-hue-strength = { size = 0.35 } + +glow-pulse-enabled = { size = 0.0 } + +edge-trace-enabled = { size = 0.0 } + +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — prismatic chromatic shift +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.08 } +viewport-wash-tl = { color = "#FF6B9D" } +viewport-wash-tr = { color = "#C084FC" } +viewport-wash-bl = { color = "#FCA5A5" } +viewport-wash-br = { color = "#67E8F9" } +viewport-wash-rotate = { size = 0.02 } +viewport-wash-pulse = { size = 0.0 } +viewport-wash-pulse-depth = { size = 0.0 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#1A1020" } +viewport-vignette-radius = { size = 0.18 } +viewport-vignette-alpha = { size = 0.10 } diff --git a/res/themes/light.toml b/res/themes/light.toml new file mode 100644 index 0000000..03acbaf --- /dev/null +++ b/res/themes/light.toml @@ -0,0 +1,142 @@ +[theme] +name = "Light" +author = "The Hush Developers" +dark = false +images = { background_image = "backgrounds/texture/light_bg.png", logo = "logos/logo_ObsidianDragon_light.png" } +elevation = { --elevation-0 = "#FAFAFA", --elevation-1 = "#F2F3F5", --elevation-2 = "#EAEBEE", --elevation-3 = "#DDDEE2", --elevation-4 = "#CDCED3" } + +[theme.palette] +--primary = "#5A6A7A" +--primary-variant = "#475868" +--primary-light = "#8494A4" +--secondary = "#607870" +--secondary-variant = "#4D655D" +--secondary-light = "#7E9690" +--background = "#F6F7F8" +--surface = "#FAFAFA" +--surface-variant = "#F0F1F3" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#2A2C30" +--on-surface = "#2A2C30" +--on-surface-medium = "rgba(42,44,48,0.68)" +--on-surface-disabled = "rgba(42,44,48,0.38)" +--error = "#8C5A62" +--on-error = "#FFFFFF" +--success = "#5A7E5C" +--on-success = "#FFFFFF" +--warning = "#8A7A52" +--on-warning = "#000000" +--divider = "rgba(42,44,48,0.12)" +--outline = "rgba(42,44,48,0.14)" +--scrim = "rgba(0,0,0,0.42)" +--surface-hover = "rgba(42,44,48,0.04)" +--surface-alt = "rgba(42,44,48,0.02)" +--surface-active = "rgba(42,44,48,0.08)" +--glass-button = "rgba(42,44,48,0.04)" +--glass-button-hover = "rgba(42,44,48,0.08)" +--card-border = "rgba(42,44,48,0.08)" +--text-shadow = "rgba(0,0,0,0.06)" +--input-overlay-text = "rgba(42,44,48,0.24)" +--slider-text = "rgba(42,44,48,0.72)" +--thumb-fill = "rgba(42,44,48,0.10)" +--thumb-border = "rgba(42,44,48,0.28)" +--disabled-label = "rgba(42,44,48,0.20)" +--chart-grid = "rgba(42,44,48,0.06)" +--chart-crosshair = "rgba(42,44,48,0.16)" +--chart-hover-ring = "rgba(42,44,48,0.24)" +--tooltip-bg = "rgba(50,52,58,0.92)" +--tooltip-border = "rgba(42,44,48,0.10)" +--glass-fill = "rgba(255,255,255,0.55)" +--glass-border = "rgba(42,44,48,0.10)" +--glass-noise-tint = "rgba(42,44,48,0.015)" +--tactile-top = "rgba(255,255,255,0.35)" +--tactile-bottom = "rgba(255,255,255,0.04)" +--hover-overlay = "rgba(42,44,48,0.04)" +--active-overlay = "rgba(42,44,48,0.08)" +--rim-light = "rgba(42,44,48,0.06)" +--status-divider = "rgba(42,44,48,0.08)" +--sidebar-hover = "rgba(42,44,48,0.05)" +--sidebar-icon = "rgba(42,44,48,0.45)" +--sidebar-badge = "rgba(42,44,48,0.80)" +--sidebar-divider = "rgba(42,44,48,0.06)" +--chart-line = "rgba(42,44,48,0.08)" +--window-control = "rgba(42,44,48,0.62)" +--window-control-hover = "rgba(42,44,48,0.06)" +--window-close-hover = "rgba(140,90,98,0.75)" +--spinner-track = "rgba(42,44,48,0.08)" +--spinner-active = "rgba(90,106,122,0.80)" +--shutdown-panel-bg = "rgba(242,243,245,0.94)" +--shutdown-panel-border = "rgba(42,44,48,0.08)" +--ram-bar-app = "#5A6A7A" +--ram-bar-system = "rgba(42,44,48,0.14)" +--accent-total = "#5A6A7A" +--accent-shielded = "#607870" +--accent-transparent = "#8A7A52" +--accent-action = "#5A6A7A" +--accent-market = "#607870" +--accent-portfolio = "#5A6A7A" +--toast-info-accent = "#5A6A7A" +--toast-info-text = "#475868" +--toast-success-accent = "rgba(90,126,92,1.0)" +--toast-success-text = "rgba(62,98,64,1.0)" +--toast-warning-accent = "rgba(138,122,82,1.0)" +--toast-warning-text = "rgba(110,96,56,1.0)" +--toast-error-accent = "rgba(140,90,98,1.0)" +--toast-error-text = "rgba(112,62,70,1.0)" +--snackbar-bg = "rgba(50,52,58,0.94)" +--snackbar-text = "rgba(235,236,238,0.87)" +--snackbar-action = "rgba(132,148,164,1.0)" +--snackbar-action-hover = "rgba(158,172,186,1.0)" +--switch-track-off = "rgba(42,44,48,0.22)" +--switch-track-on = "rgba(90,106,122,0.35)" +--switch-thumb-off = "#F5F5F5" +--switch-thumb-on = "#FAFAFA" +--control-shadow = "rgba(0,0,0,0.16)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(0,0,0,0.07)" + +[backdrop] +base-color-top = "rgba(250,250,252,255)" +base-color-bottom = "rgba(240,241,245,255)" +texture-tint-alpha = 80 +gradient-top-r = 248 +gradient-top-g = 249 +gradient-top-b = 252 +gradient-top-a = 240 +gradient-bottom-r = 238 +gradient-bottom-g = 239 +gradient-bottom-b = 244 +gradient-bottom-a = 220 +background-alpha = 0.97 +surface-alpha = 0.97 +frame-alpha = 0.94 +surface-inline-alpha = 0.95 +background-inline-alpha = 0.94 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Light (barely perceptible) +# Whisper-soft glow on active button. Clean and airy — effects stay invisible. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 0.0 } +rainbow-border-enabled = { size = 0.0 } +shimmer-enabled = { size = 0.0 } +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 1.0 } +glow-pulse-speed = { size = 0.2 } +glow-pulse-min-alpha = { size = 0.01 } +glow-pulse-max-alpha = { size = 0.03 } +glow-pulse-radius = { size = 2.0 } +glow-pulse-color = { color = "var(--primary)" } + +edge-trace-enabled = { size = 0.0 } +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — very subtle warm vignette +viewport-wash-enabled = { size = 0.0 } +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#0A0500" } +viewport-vignette-radius = { size = 0.18 } +viewport-vignette-alpha = { size = 0.04 } diff --git a/res/themes/marble.toml b/res/themes/marble.toml new file mode 100644 index 0000000..3f99e8d --- /dev/null +++ b/res/themes/marble.toml @@ -0,0 +1,160 @@ +[theme] +name = "Marble" +author = "The Hush Developers" +dark = false +images = { background_image = "backgrounds/texture/marble_bg.png", logo = "logos/logo_ObsidianDragon_light.png" } +elevation = { --elevation-0 = "#FAFAF8", --elevation-1 = "#F0EEEC", --elevation-2 = "#E8E4E0", --elevation-3 = "#DCD6D0", --elevation-4 = "#CEC6BE" } + +[theme.palette] +# Marble: cool stone tones — slate, charcoal, warm gray, aged gold accents +--primary = "#6E7580" +--primary-variant = "#555D68" +--primary-light = "#94999F" +--secondary = "#8A7D6C" +--secondary-variant = "#706454" +--secondary-light = "#A89E90" +--background = "#F8F6F4" +--surface = "#FEFEFE" +--surface-variant = "#F2EFEC" +--on-primary = "#FFFFFF" +--on-secondary = "#FFFFFF" +--on-background = "#2C2A28" +--on-surface = "#2C2A28" +--on-surface-medium = "rgba(44,42,40,0.68)" +--on-surface-disabled = "rgba(44,42,40,0.38)" +--error = "#8C5250" +--on-error = "#FFFFFF" +--success = "#5C7A62" +--on-success = "#FFFFFF" +--warning = "#8A7A4C" +--on-warning = "#000000" +--divider = "rgba(80,75,68,0.12)" +--outline = "rgba(80,75,68,0.14)" +--scrim = "rgba(20,18,16,0.42)" +--surface-hover = "rgba(110,117,128,0.05)" +--surface-alt = "rgba(110,117,128,0.025)" +--surface-active = "rgba(110,117,128,0.08)" +--glass-button = "rgba(110,117,128,0.05)" +--glass-button-hover = "rgba(110,117,128,0.10)" +--card-border = "rgba(110,117,128,0.10)" +--text-shadow = "rgba(0,0,0,0.05)" +--input-overlay-text = "rgba(44,42,40,0.24)" +--slider-text = "rgba(44,42,40,0.72)" +--thumb-fill = "rgba(110,117,128,0.10)" +--thumb-border = "rgba(110,117,128,0.28)" +--disabled-label = "rgba(44,42,40,0.20)" +--chart-grid = "rgba(110,117,128,0.06)" +--chart-crosshair = "rgba(110,117,128,0.16)" +--chart-hover-ring = "rgba(110,117,128,0.24)" +--tooltip-bg = "rgba(44,42,40,0.94)" +--tooltip-border = "rgba(110,117,128,0.10)" +--glass-fill = "rgba(255,255,254,0.62)" +--glass-border = "rgba(110,117,128,0.10)" +--glass-noise-tint = "rgba(80,75,68,0.02)" +--tactile-top = "rgba(255,255,255,0.45)" +--tactile-bottom = "rgba(255,255,255,0.06)" +--hover-overlay = "rgba(110,117,128,0.04)" +--active-overlay = "rgba(110,117,128,0.08)" +--rim-light = "rgba(180,175,168,0.10)" +--status-divider = "rgba(110,117,128,0.08)" +--sidebar-hover = "rgba(110,117,128,0.06)" +--sidebar-icon = "rgba(44,42,40,0.48)" +--sidebar-badge = "rgba(44,42,40,0.82)" +--sidebar-divider = "rgba(110,117,128,0.06)" +--chart-line = "rgba(110,117,128,0.08)" +--window-control = "rgba(44,42,40,0.62)" +--window-control-hover = "rgba(110,117,128,0.08)" +--window-close-hover = "rgba(140,82,80,0.75)" +--spinner-track = "rgba(110,117,128,0.10)" +--spinner-active = "rgba(110,117,128,0.80)" +--shutdown-panel-bg = "rgba(248,246,244,0.96)" +--shutdown-panel-border = "rgba(110,117,128,0.08)" +# RAM bar: slate +--ram-bar-app = "#6E7580" +--ram-bar-system = "rgba(44,42,40,0.14)" +# Accent strips: stone palette — slate, taupe, aged gold, charcoal, olive, warm gray +--accent-total = "#6E7580" +--accent-shielded = "#8A7D6C" +--accent-transparent = "#8A7A4C" +--accent-action = "#6E7580" +--accent-market = "#5C7A62" +--accent-portfolio = "#706454" +# Toasts: warm stone +--toast-info-accent = "#6E7580" +--toast-info-text = "#555D68" +--toast-success-accent = "rgba(92,122,98,1.0)" +--toast-success-text = "rgba(66,96,72,1.0)" +--toast-warning-accent = "rgba(138,122,76,1.0)" +--toast-warning-text = "rgba(110,96,52,1.0)" +--toast-error-accent = "rgba(140,82,80,1.0)" +--toast-error-text = "rgba(112,56,54,1.0)" +# Snackbar +--snackbar-bg = "rgba(44,42,40,0.95)" +--snackbar-text = "rgba(248,246,244,0.87)" +--snackbar-action = "rgba(148,153,159,1.0)" +--snackbar-action-hover = "rgba(180,185,190,1.0)" +# Controls +--switch-track-off = "rgba(44,42,40,0.22)" +--switch-track-on = "rgba(110,117,128,0.35)" +--switch-thumb-off = "#F0EEEC" +--switch-thumb-on = "#FEFEFE" +--control-shadow = "rgba(0,0,0,0.14)" +--checkbox-check = "#FFFFFF" +--app-bar-shadow = "rgba(0,0,0,0.06)" + +[backdrop] +base-color-top = "rgba(250,250,248,255)" +base-color-bottom = "rgba(238,234,228,255)" +texture-tint-alpha = 85 +gradient-top-r = 248 +gradient-top-g = 248 +gradient-top-b = 245 +gradient-top-a = 240 +gradient-bottom-r = 235 +gradient-bottom-g = 230 +gradient-bottom-b = 224 +gradient-bottom-a = 230 +background-alpha = 0.97 +surface-alpha = 0.97 +frame-alpha = 0.94 +surface-inline-alpha = 0.95 +background-inline-alpha = 0.94 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Marble (polished stone) +# Minimal, elegant. Faint cool shimmer like light gliding across +# polished stone. No particles, no color shifting — pure restraint. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 0.0 } +rainbow-border-enabled = { size = 0.0 } + +# Very slow, very wide, very faint — like a reflection on polished marble +shimmer-enabled = { size = 1.0 } +shimmer-speed = { size = 0.018 } +shimmer-width = { size = 250.0 } +shimmer-alpha = { size = 0.015 } +shimmer-angle = { size = 10.0 } +shimmer-color = { color = "rgba(200,195,188,1.0)" } + +positional-hue-enabled = { size = 0.0 } + +# Gentle active-element glow — warm stone highlight +glow-pulse-enabled = { size = 1.0 } +glow-pulse-speed = { size = 0.18 } +glow-pulse-min-alpha = { size = 0.008 } +glow-pulse-max-alpha = { size = 0.025 } +glow-pulse-radius = { size = 2.0 } +glow-pulse-color = { color = "#8A7D6C" } + +edge-trace-enabled = { size = 0.0 } +ember-rise-enabled = { size = 0.0 } +gradient-border-enabled = { size = 0.0 } + +# No viewport wash — marble is clean and quiet +viewport-wash-enabled = { size = 0.0 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#100E0C" } +viewport-vignette-radius = { size = 0.16 } +viewport-vignette-alpha = { size = 0.04 } diff --git a/res/themes/obsidian.toml b/res/themes/obsidian.toml new file mode 100644 index 0000000..3c2fed0 --- /dev/null +++ b/res/themes/obsidian.toml @@ -0,0 +1,166 @@ +[theme] +name = "Obsidian" +author = "The Hush Developers" +dark = true +elevation = { --elevation-0 = "#0E0B14", --elevation-1 = "#17121E", --elevation-2 = "#1C1625", --elevation-3 = "#211A2C", --elevation-4 = "#261E33" } +images = { background_image = "backgrounds/texture/obsidian_bg.png", logo = "logos/logo_ObsidianDragon_dark.png" } + +[theme.palette] +--primary = "#AB47BC" +--primary-variant = "#8E24AA" +--primary-light = "#CE93D8" +--secondary = "#B388FF" +--secondary-variant = "#7C4DFF" +--secondary-light = "#D1C4E9" +--background = "#0A0810" +--surface = "#110E18" +--surface-variant = "#1C1625" +--on-primary = "#FFFFFF" +--on-secondary = "#000000" +--on-background = "#E8E0F0" +--on-surface = "#E8E0F0" +--on-surface-medium = "rgba(232,224,240,0.75)" +--on-surface-disabled = "rgba(232,224,240,0.45)" +--error = "#CF6679" +--on-error = "#000000" +--success = "#81C784" +--on-success = "#000000" +--warning = "#FFB74D" +--on-warning = "#000000" +--divider = "rgba(200,180,255,0.14)" +--outline = "rgba(200,180,255,0.16)" +--scrim = "rgba(0,0,0,0.6)" +--surface-hover = "rgba(200,180,255,0.07)" +--surface-alt = "rgba(200,180,255,0.05)" +--surface-active = "rgba(200,180,255,0.10)" +--glass-button = "rgba(200,180,255,0.06)" +--glass-button-hover = "rgba(200,180,255,0.12)" +--card-border = "rgba(200,180,255,0.14)" +--text-shadow = "rgba(0,0,0,0.50)" +--input-overlay-text = "rgba(232,224,240,0.30)" +--slider-text = "rgba(232,224,240,0.85)" +--thumb-fill = "rgba(200,180,255,0.15)" +--thumb-border = "rgba(200,180,255,0.50)" +--disabled-label = "rgba(200,180,255,0.18)" +--chart-grid = "rgba(200,180,255,0.05)" +--chart-crosshair = "rgba(200,180,255,0.15)" +--chart-hover-ring = "rgba(200,180,255,0.30)" +--tooltip-bg = "rgba(14,11,20,0.92)" +--tooltip-border = "rgba(200,180,255,0.12)" +--glass-fill = "rgba(200,180,255,0.08)" +--glass-border = "rgba(200,180,255,0.14)" +--glass-noise-tint = "rgba(200,180,255,0.03)" +--tactile-top = "rgba(200,180,255,0.06)" +--tactile-bottom = "rgba(200,180,255,0.0)" +--hover-overlay = "rgba(200,180,255,0.05)" +--active-overlay = "rgba(200,180,255,0.10)" +--rim-light = "rgba(200,180,255,0.08)" +--status-divider = "rgba(200,180,255,0.08)" +--sidebar-hover = "rgba(200,180,255,0.10)" +--sidebar-icon = "rgba(200,180,255,0.42)" +--sidebar-badge = "rgba(232,224,240,1.0)" +--sidebar-divider = "rgba(200,180,255,0.06)" +--chart-line = "rgba(200,180,255,0.10)" +--window-control = "rgba(232,224,240,0.78)" +--window-control-hover = "rgba(200,180,255,0.12)" +--window-close-hover = "rgba(232,17,35,0.78)" +--spinner-track = "rgba(200,180,255,0.10)" +--spinner-active = "rgba(179,136,255,0.85)" +--shutdown-panel-bg = "rgba(10,8,16,0.90)" +--shutdown-panel-border = "rgba(200,180,255,0.07)" +--ram-bar-app = "#AB47BC" +--ram-bar-system = "rgba(255,255,255,0.18)" +--accent-total = "#CE93D8" +--accent-shielded = "#80CBC4" +--accent-transparent = "#FFAB91" +--accent-action = "#AB47BC" +--accent-market = "#80CBC4" +--accent-portfolio = "#B388FF" +--toast-info-accent = "#AB47BC" +--toast-info-text = "#CE93D8" +--toast-success-accent = "rgba(50,180,80,1.0)" +--toast-success-text = "rgba(180,255,180,1.0)" +--toast-warning-accent = "rgba(204,166,50,1.0)" +--toast-warning-text = "rgba(255,230,130,1.0)" +--toast-error-accent = "rgba(204,64,64,1.0)" +--toast-error-text = "rgba(255,153,153,1.0)" +--snackbar-bg = "rgba(40,35,55,0.95)" +--snackbar-text = "rgba(232,224,240,0.87)" +--snackbar-action = "rgba(179,136,255,1.0)" +--snackbar-action-hover = "rgba(206,147,216,1.0)" +--switch-track-off = "rgba(200,180,255,0.12)" +--switch-track-on = "rgba(171,71,188,0.50)" +--switch-thumb-off = "#B0A0C0" +--switch-thumb-on = "#E8E0F0" +--control-shadow = "rgba(0,0,0,0.24)" +--checkbox-check = "#000000" +--app-bar-shadow = "rgba(0,0,0,0.25)" + +[backdrop] +base-color-top = "rgba(22,14,40,210)" +base-color-bottom = "rgba(10,6,22,210)" +texture-tint-alpha = 130 +gradient-top-r = 18 +gradient-top-g = 10 +gradient-top-b = 35 +gradient-top-a = 90 +gradient-bottom-r = 8 +gradient-bottom-g = 4 +gradient-bottom-b = 18 +gradient-bottom-a = 70 +background-alpha = 0.42 +surface-alpha = 0.52 +frame-alpha = 0.74 +surface-inline-alpha = 0.55 +background-inline-alpha = 0.38 + +# --------------------------------------------------------------------------- +# Theme Visual Effects — Obsidian (volcanic glass sheen) +# Specular glare highlights drift slowly across panels like light +# reflecting off polished volcanic glass — mysterious, restrained. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 0.0 } +rainbow-border-enabled = { size = 0.0 } + +# No shimmer sweep — replaced by specular glare +shimmer-enabled = { size = 0.0 } + +positional-hue-enabled = { size = 0.0 } + +glow-pulse-enabled = { size = 0.0 } +edge-trace-enabled = { size = 0.0 } + +# Specular glare — soft blurred obsidian highlights +specular-glare-enabled = { size = 1.0 } +specular-glare-speed = { size = 0.018 } +specular-glare-intensity = { size = 0.008 } +specular-glare-radius = { size = 0.65 } +specular-glare-count = { size = 1.0 } +specular-glare-color = { color = "rgba(200,180,240,1.0)" } + +# Gem-like color-shifting border on active sidebar button +gradient-border-enabled = { size = 1.0 } +gradient-border-speed = { size = 0.12 } +gradient-border-thickness = { size = 1.5 } +gradient-border-alpha = { size = 0.55 } +gradient-border-color-a = { color = "#CE93D8" } +gradient-border-color-b = { color = "#3F51B5" } + +ember-rise-enabled = { size = 0.0 } + +# Shader-like viewport overlay — deep indigo crystal atmosphere +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.05 } +viewport-wash-tl = { color = "#4A148C" } +viewport-wash-tr = { color = "#1A237E" } +viewport-wash-bl = { color = "#311B92" } +viewport-wash-br = { color = "#6A1B9A" } +viewport-wash-rotate = { size = 0.015 } +viewport-wash-pulse = { size = 0.0 } +viewport-wash-pulse-depth = { size = 0.0 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#0D0015" } +viewport-vignette-radius = { size = 0.22 } +viewport-vignette-alpha = { size = 0.15 } diff --git a/res/themes/ui.toml b/res/themes/ui.toml new file mode 100644 index 0000000..be061e1 --- /dev/null +++ b/res/themes/ui.toml @@ -0,0 +1,1564 @@ +# === DragonX Wallet Theme File === +# Copy this entire folder into the 'themes' folder to use it. +# The folder name becomes the theme ID. + +# === Images === +# Place image files in the 'img' subfolder. +# Specify custom filenames below, or use the defaults: +# backgrounds/gradient/dark_gradient.png - background gradient overlay +# logos/logo_ObsidianDragon_dark.png - sidebar logo (128x128 recommended) + +# === Colors === +# Colors use CSS-style formats: #RRGGBB, #RRGGBBAA, or rgba(r,g,b,a) +# Palette variables can be referenced elsewhere with var(--name) + +spacing = { section = 16.0, item = 8.0, label-value = 4.0, separator = 20.0 } +input = { min-width = 150.0, width-md = 200.0, width-lg = 300.0, search-width-ratio = 0.3 } +spacing-tokens = { xs = 2.0, sm = 4.0, md = 8.0, lg = 12.0, xl = 16.0, xxl = 24.0 } + +[theme] +name = "DragonX" +author = "DanS" +dark = true +elevation = { --elevation-0 = "#120A08", --elevation-1 = "#1A0F0C", --elevation-2 = "#201410", --elevation-3 = "#261914", --elevation-4 = "#2C1E18" } +images = { background_image = "backgrounds/texture/drgx_bg.png", logo = "logos/logo_ObsidianDragon_dark.png" } + +[theme.palette] +--primary = "#D32F2F" +--primary-variant = "#B71C1C" +--primary-light = "#EF5350" +--secondary = "#FF6D00" +--secondary-variant = "#E65100" +--secondary-light = "#FF9E40" +--background = "#0C0606" +--surface = "#120A08" +--surface-variant = "#201410" +--on-primary = "#FFFFFF" +--on-secondary = "#000000" +--on-background = "#F0E0D8" +--on-surface = "#F0E0D8" +--on-surface-medium = "rgba(240,224,216,0.7)" +--on-surface-disabled = "rgba(240,224,216,0.44)" +--error = "#FF5252" +--on-error = "#000000" +--success = "#81C784" +--on-success = "#000000" +--warning = "#FFD54F" +--on-warning = "#000000" +--divider = "rgba(255,180,140,0.13)" +--outline = "rgba(255,180,140,0.15)" +--scrim = "rgba(0,0,0,0.55)" +--surface-hover = "rgba(255,180,140,0.07)" +--surface-alt = "rgba(255,180,140,0.05)" +--surface-active = "rgba(255,180,140,0.10)" +--glass-button = "rgba(255,180,140,0.06)" +--glass-button-hover = "rgba(255,180,140,0.12)" +--card-border = "rgba(255,180,140,0.14)" +--text-shadow = "rgba(0,0,0,0.50)" +--input-overlay-text = "rgba(240,224,216,0.30)" +--slider-text = "rgba(240,224,216,0.86)" +--thumb-fill = "rgba(255,180,140,0.15)" +--thumb-border = "rgba(255,180,140,0.50)" +--disabled-label = "rgba(255,180,140,0.18)" +--chart-grid = "rgba(255,180,140,0.05)" +--chart-crosshair = "rgba(255,180,140,0.15)" +--chart-hover-ring = "rgba(255,180,140,0.30)" +--tooltip-bg = "rgba(12,8,6,0.92)" +--tooltip-border = "rgba(255,180,140,0.12)" +--glass-fill = "rgba(255,180,140,0.08)" +--glass-border = "rgba(255,180,140,0.13)" +--glass-noise-tint = "rgba(255,180,140,0.03)" +--tactile-top = "rgba(255,180,140,0.06)" +--tactile-bottom = "rgba(255,180,140,0.0)" +--hover-overlay = "rgba(255,180,140,0.05)" +--active-overlay = "rgba(255,180,140,0.10)" +--rim-light = "rgba(255,180,140,0.08)" +--status-divider = "rgba(255,180,140,0.08)" +--sidebar-hover = "rgba(255,180,140,0.10)" +--sidebar-icon = "rgba(255,180,140,0.36)" +--sidebar-badge = "rgba(240,224,216,1.0)" +--sidebar-divider = "rgba(255,180,140,0.06)" +--chart-line = "rgba(255,180,140,0.10)" +--window-control = "rgba(240,224,216,0.78)" +--window-control-hover = "rgba(255,180,140,0.12)" +--window-close-hover = "rgba(232,17,35,0.78)" +--spinner-track = "rgba(255,180,140,0.10)" +--spinner-active = "rgba(255,109,0,0.85)" +--shutdown-panel-bg = "rgba(10,6,4,0.88)" +--shutdown-panel-border = "rgba(255,180,140,0.07)" +--ram-bar-app = "#EF5350" +--ram-bar-system = "rgba(255,255,255,0.18)" +--accent-total = "#EF5350" +--accent-shielded = "#81C784" +--accent-transparent = "#FFD54F" +--accent-action = "#D32F2F" +--accent-market = "#81C784" +--accent-portfolio = "#FF6D00" +--toast-info-accent = "#D32F2F" +--toast-info-text = "#EF5350" +--toast-success-accent = "rgba(50,180,80,1.0)" +--toast-success-text = "rgba(180,255,180,1.0)" +--toast-warning-accent = "rgba(255,158,64,1.0)" +--toast-warning-text = "rgba(255,230,170,1.0)" +--toast-error-accent = "rgba(211,47,47,1.0)" +--toast-error-text = "rgba(255,138,128,1.0)" +--snackbar-bg = "rgba(45,30,25,0.95)" +--snackbar-text = "rgba(240,224,216,0.87)" +--snackbar-action = "rgba(255,109,0,1.0)" +--snackbar-action-hover = "rgba(255,158,64,1.0)" +--switch-track-off = "rgba(255,180,140,0.12)" +--switch-track-on = "rgba(211,47,47,0.45)" +--switch-thumb-off = "#C0A8A0" +--switch-thumb-on = "#F0E0D8" +--control-shadow = "rgba(0,0,0,0.28)" +--checkbox-check = "#000000" +--app-bar-shadow = "rgba(0,0,0,0.22)" + +[fonts] +scale = 1.0 +h1 = 20.0 +h2 = 18.0 +h3 = 16.0 +h4 = 16.0 +h5 = 14.0 +h6 = 14.0 +subtitle1 = 16.0 +subtitle2 = 14.0 +body1 = 14.0 +body2 = 15.0 +button = 12.0 +button-sm = 10.0 +button-lg = 14.0 +caption = 12.0 +overline = 14.0 + +[typography] +h1 = { letter-spacing = -1.0, line-height = 1.167, text-transform = "none" } +h2 = { letter-spacing = -0.5, line-height = 1.2, text-transform = "none" } +h3 = { letter-spacing = 0.0, line-height = 1.167, text-transform = "none" } +h4 = { letter-spacing = 0.25, line-height = 1.235, text-transform = "none" } +h5 = { letter-spacing = 0.0, line-height = 1.334, text-transform = "none" } +h6 = { letter-spacing = 0.15, line-height = 1.6, text-transform = "none" } +subtitle1 = { letter-spacing = 0.15, line-height = 1.75, text-transform = "none" } +subtitle2 = { letter-spacing = 0.1, line-height = 1.57, text-transform = "none" } +body1 = { letter-spacing = 0.5, line-height = 1.5, text-transform = "none" } +body2 = { letter-spacing = 0.25, line-height = 1.43, text-transform = "none" } +button = { letter-spacing = 1.25, line-height = 1.75, text-transform = "uppercase" } +caption = { letter-spacing = 0.4, line-height = 1.66, text-transform = "none" } +overline = { letter-spacing = 1.5, line-height = 2.66, text-transform = "uppercase" } + +[breakpoints] +compact = { max-width = 500.0, max-height = 400.0 } +expanded = { min-width = 900.0, min-height = 700.0 } + +[globals] +label = { font = "body2", color = "var(--on-surface)" } +checkbox = { font = "body2", check-color = "var(--primary)" } +table = { header-font = "caption", cell-font = "body2", border-color = "var(--divider)", row-height = 22 } +menu = { font = "body2" } + +[globals.button] +font = "button" +padding = [10, 6] +color = "var(--on-primary)" +background = "var(--primary)" +border-radius = 8 +opacity = 1.0 +min-width = 0 + +[globals.input] +font = "body1" +padding = [10, 6] +color = "var(--on-surface)" +background = "var(--surface-variant)" +border-radius = 8 +border-width = 1 +border-color = "var(--outline)" +border-color-focus = "var(--primary)" +placeholder-color = "var(--on-surface-disabled)" + +[globals.separator] +color = "var(--divider)" +thickness = 1 +margin = [0, 8] + +[globals.window] +background = "var(--surface)" +border-radius = 6 +padding = [12, 12] + +[tabs] + +[tabs.balance] +connection-status-height = 100.0 +address-button-width = 110.0 +address-button-gap = 8.0 +type-column-width = 50.0 +balance-column-width = 150.0 +address-trunc-len = 32 +address-button = { width = 160, gap = 8, font = "button-sm" } +action-button = { width = 140, font = "button" } +search-input = { width-ratio = 0.3, max-width = 250 } +balance-label = { font = "h4", color = "var(--on-surface)" } +sync-bar = { height = 3, color = "var(--primary)" } +balance-lerp-speed = { size = 8.0 } +hero-pad-top = { size = 0.0 } +hero-pad-bottom = { size = 8.0 } +card-min-height = { size = 70.0 } +recent-tx-row-height = { size = 22.0 } +button-row-right-margin = { size = 16.0 } +connection-status = { height = 100 } +sparkline-min-height = { size = 20.0 } +sparkline-height = { size = 30.0 } +min-buttons-position = { size = 160.0 } +buttons-position = { size = 200.0 } +recent-tx-row-min-height = { size = 18.0 } +address-icon-min-size = { size = 3.5 } +address-icon-size = { size = 5.0 } +recent-tx-icon-min-size = { size = 3.5 } +recent-tx-icon-size = { size = 5.0 } +amount-right-min-margin = { size = 50.0 } +amount-right-margin = { size = 70.0 } +recent-tx-header-height = { size = 56.0 } +row-hover-rounding = { size = 4.0 } +status-pill-rounding = { size = 3.0 } +recent-tx-reserve-ratio = { size = 0.18 } +addr-list-min-height = { size = 34.0 } +recent-tx-addr-offset = { size = 65.0 } +recent-tx-addr-trunc = { size = 20 } +recent-tx-time-margin = { size = 4.0 } +overline-value-gap = { size = 6.0 } +value-caption-gap = { size = 4.0 } +card-stat-min-height = { size = 60.0 } +accent-inset-ratio = { size = 0.6 } +accent-left-offset = { size = 0.0 } +accent-width = { size = 4.0 } +accent-rounding = { size = 1.5 } +hover-glow-alpha = { size = 40 } +hover-glow-thickness = { size = 1.5 } +compact-hero-pad = { size = 8.0 } +empty-state-btn-width = { size = 180.0 } +empty-state-btn-height = { size = 36.0 } + +[tabs.balance.layouts] +default = "classic" +selected = "classic" + +[[tabs.balance.layouts.options]] +id = "classic" +name = "Classic" +enabled = true + +[[tabs.balance.layouts.options]] +id = "donut" +name = "Donut Chart" +enabled = false + +[[tabs.balance.layouts.options]] +id = "consolidated" +name = "Consolidated Card" +enabled = true + +[[tabs.balance.layouts.options]] +id = "dashboard" +name = "Dashboard Tiles" +enabled = true + +[[tabs.balance.layouts.options]] +id = "vertical-stack" +name = "Vertical Stack" +enabled = true + +[[tabs.balance.layouts.options]] +id = "vertical-2x2" +name = "Vertical 2×2" +enabled = true + +[[tabs.balance.layouts.options]] +id = "shield" +name = "Privacy Shield" +enabled = false + +[[tabs.balance.layouts.options]] +id = "timeline" +name = "Balance Timeline" +enabled = true + +[[tabs.balance.layouts.options]] +id = "two-row" +name = "Two-Row Compact" +enabled = true + +[[tabs.balance.layouts.options]] +id = "minimal" +name = "Minimal" +enabled = true + +[tabs.balance.window] +padding = [12, 12] + +[tabs.balance.address-table] + +[tabs.balance.address-table.columns] +type = { width = 50 } +balance = { width = 150 } +address = { truncate = 32 } + +[tabs.balance.classic] +top-margin = { size = 0 } +card-padding = { size = -1 } +address-table-height = { size = 340 } +card-height = { size = 80 } +card-min-height = { size = 72.0 } +sparkline-gap = { size = 12.0 } +logo-opacity = { size = 180 } +mining-dot-radius = { size = 3.0 } +unconfirmed-badge-padding = { size = 4.0 } +unconfirmed-badge-rounding = { size = 4.0 } +ticker-gap = { size = 4.0 } +card-num-cols = { size = 4 } +card-compact-cols = { size = 2 } +card-narrow-cols = { size = 1 } +card-narrow-width = { size = 400.0 } + +[tabs.balance.donut] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = -1 } +card-height = { size = -1 } +hero-pad-ratio = { size = 8.0 } +panel-min-height = { size = 80.0 } +panel-height-ratio = { size = 0.2 } +outer-radius-ratio = { size = 0.4 } +inner-radius-ratio = { size = 0.6 } +max-radius-ratio = { size = 0.12 } +legend-dot-radius = { size = 4.0 } +legend-x-offset = { size = 14 } +legend-line-gap = { size = 6 } +legend-section-gap = { size = 10 } + +[tabs.balance.consolidated] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 298 } +card-height = { size = 120 } +card-min-height = { size = 80.0 } +card-height-ratio = { size = 0.22 } +divider-y-ratio = { size = 0.55 } +bar-min-height = { size = 5.0 } +bar-base-height = { size = 10.0 } +divider-alpha = { size = 20 } +divider-thickness = { size = 1.0 } + +[tabs.balance.dashboard] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 318 } +card-height = { size = 60 } +hero-height = { size = -1 } +compact-cutoff = { size = 500.0 } +tile-min-height = { size = 70.0 } +tile-height-ratio = { size = 0.16 } +tile-num-cols = { size = 4 } +tile-compact-cols = { size = 2 } + +[tabs.balance.vertical-stack] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 262 } +card-height = { size = 120 } +stack-min-height = { size = 72.0 } +stack-height-ratio = { size = 0.16 } +row-gap = { size = 0.0 } +row-min-height = { size = 20.0 } +row-bg-alpha = { size = 8 } +bar-width-ratio = { size = 0.15 } +bar-min-height = { size = 3.0 } +bar-height-ratio = { size = 0.15 } +accent-inset = { size = 2.0 } +sparkline-gap = { size = 12.0 } +sparkline-pad = { size = 4.0 } + +[tabs.balance.vertical-2x2] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 336 } +card-height = { size = -1 } +stack-min-height = { size = 54.0 } +stack-height-ratio = { size = 0.12 } +row-gap = { size = 2.0 } +col-gap = { size = 8.0 } +row-min-height = { size = 24.0 } +row-bg-alpha = { size = 8 } +bar-width-ratio = { size = 0.12 } +bar-min-height = { size = 3.0 } +bar-height-ratio = { size = 0.15 } +accent-inset = { size = 2.0 } +sparkline-gap = { size = 12.0 } +sparkline-pad = { size = 4.0 } + +[tabs.balance.shield] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = -1 } +card-height = { size = -1 } +gauge-min-height = { size = 72.0 } +gauge-height-ratio = { size = 0.18 } +gauge-radius-ratio = { size = 0.55 } +gauge-max-radius-ratio = { size = 0.15 } +gauge-inner-ratio = { size = 0.7 } +gauge-center-y-ratio = { size = 0.7 } +needle-thickness = { size = 2.0 } +good-threshold = { size = 80.0 } +medium-threshold = { size = 50.0 } +gauge-bg-alpha = { size = 20 } + +[tabs.balance.timeline] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 157 } +chart-height = { size = 100 } +chart-min-height = { size = 72.0 } +chart-height-ratio = { size = 0.2 } +summary-card-height = { size = 46 } +summary-min-height = { size = 40.0 } +summary-height-ratio = { size = 0.08 } +sparkline-alpha = { size = 120 } + +[tabs.balance.two-row] +top-margin = { size = -1 } +card-padding = { size = -1 } +address-table-height = { size = 348 } +card-height = { size = -1 } +mini-min-height = { size = 28.0 } +mini-base-height = { size = 36.0 } +action-btn-width = { size = 80.0 } +mini-rounding-ratio = { size = 0.5 } +mini-rounding-min = { size = 4.0 } +indicator-radius = { size = 3.0 } +sync-gap = { size = 2.0 } +balance-decimals = { size = 4 } +sparkline-gap = { size = 6.0 } +sparkline-pad = { size = 4.0 } + +[tabs.balance.minimal] +top-margin = { size = -1 } +address-table-height = { size = 370 } +dash-length = { size = 6.0 } +dash-gap = { size = 4.0 } +separator-alpha = { size = 25 } +separator-thickness = { size = 1.0 } + +[tabs.send] +address-input-right-pad = 100.0 +paste-button-width = 90.0 +amount-input-width = 200.0 +usd-equiv-position = 350.0 +memo-height = 60.0 +fee-input-width = 150.0 +total-label-position = 100.0 +send-button-width = 180.0 +send-button-height = 40.0 +clear-button-width = 100.0 +clear-button-height = 40.0 +confirm-button-width = 140.0 +cancel-button-width = 100.0 +address-trunc-len = 40 +from-dropdown-trunc-len = 30 +confirm-trunc-len = 50 +address-input = { width = -100 } +paste-button = { width = 90, font = "button-sm" } +amount-input = { width = 200 } +usd-equiv-label = { position = 350 } +memo-input = { lines = 3, height = 60 } +fee-input = { width = 150 } +total-label = { position = 100 } +clear-button = { width = 100, height = 40, font = "button", background = "var(--surface-variant)" } +confirm-button = { width = 140, font = "button", background = "var(--success)", color = "var(--on-success)" } +cancel-button = { width = 100, font = "button", background = "var(--error)", color = "var(--on-error)" } +address-label = { truncate = 40 } +from-combo = { truncate = 30 } +confirm-label = { truncate = 50 } +suggestion-row-height = { size = 22.0 } +suggestion-max-height = { size = 114.0 } +suggestion-trunc-len = { size = 50 } +fee-rounding = { size = 10.0 } +amount-bar-max-btn-width = { size = 80.0 } +amount-bar-height = { size = 22.0 } +confirm-popup-max-width = { size = 420.0 } +confirm-addr-card-height = { size = 28.0 } +confirm-amount-card-height = { size = 70.0 } +confirm-row-step = { size = 16.0 } +confirm-val-col-x = { size = 90.0 } +confirm-usd-col-x = { size = 80.0 } +progress-card-height = { size = 36.0 } +progress-card-height-txid = { size = 52.0 } +progress-card-pad-x = { size = 12.0 } +progress-card-pad-y = { size = 8.0 } +cta-height = { size = 80.0 } +cta-button-width = { size = 150.0 } +cta-button-height = { size = 30.0 } +action-btn-height = { size = 30.0 } +cancel-btn-min-width = { size = 80.0 } +clear-confirm-yes-width = { size = 100.0 } +clear-confirm-keep-width = { size = 80.0 } +toggle-currency-width = { size = 80.0 } +memo-min-height = { size = 22.0 } +memo-base-height = { size = 41.0 } +confirm-btn-min-height = { size = 28.0 } +confirm-btn-base-height = { size = 36.0 } +sync-banner-min-height = { size = 22.0 } +sync-banner-height = { size = 28.0 } +progress-bar-min-width = { size = 80.0 } +error-btn-min-height = { size = 22.0 } +error-btn-height = { size = 26.0 } +error-icon-inset = { size = 20.0 } +error-btn-rounding = { size = 4.0 } +progress-glass-rounding-ratio = { size = 0.75 } +confirm-addr-card-min-height = { size = 24.0 } +confirm-val-col-min-x = { size = 70.0 } +confirm-usd-col-min-x = { size = 60.0 } +confirm-amount-card-min-height = { size = 54.0 } +confirm-row-step-min = { size = 12.0 } +action-btn-min-height = { size = 26.0 } +recent-icon-min-size = { size = 3.5 } +recent-icon-size = { size = 5.0 } +paste-btn-min-width = { size = 70.0 } +paste-btn-width-ratio = { size = 0.12 } +amount-input-min-width = { size = 100.0 } +swap-icon-width = { size = 12.0 } +swap-icon-gap = { size = 4.0 } +row-hover-rounding = { size = 4.0 } +status-pill-rounding = { size = 3.0 } +fee-row-padding = { size = 2.0 } +right-col-width-ratio = { size = 0.35 } +sync-banner-bg-color = { color = "rgba(153,102,0,0.15)" } +addr-preview-trunc-min = { size = 20.0 } +addr-preview-trunc-divisor = { size = 16.0 } +addr-dropdown-trunc-min = { size = 15.0 } +addr-dropdown-trunc-divisor = { size = 14.0 } +default-addr-trunc-len = { size = 40 } +max-suggestions = { size = 5 } +suggestion-bg-color = { color = "rgba(26,26,38,0.9)" } +suggestion-list-padding = { size = 4.0 } +suggestion-trunc-fallback = { size = 50 } +fee-tier-gap = { size = 4.0 } +fee-tier-active-bg-alpha = { size = 25 } +amount-bar-track-alpha = { size = 15 } +progress-threshold-ok = { size = 0.6 } +progress-threshold-warn = { size = 0.9 } +progress-fill-alpha = { size = 180 } +progress-pct-text-alpha = { size = 220 } +thumb-fill-alpha = { size = 40 } +thumb-border-alpha = { size = 130 } +thumb-border-thickness = { size = 1.5 } +tx-success-timeout = { size = 10.0 } +error-accent-bar-width = { size = 3.0 } +error-icon-x-offset = { size = 2.0 } +error-text-x-offset = { size = 24.0 } +error-btn-area-padding = { size = 8.0 } +error-btn-bg-alpha = { size = 15 } +error-btn-hover-alpha = { size = 30 } +progress-icon-text-gap = { size = 6.0 } +txid-y-offset = { size = 4.0 } +txid-display-threshold = { size = 32 } +txid-trunc-len = { size = 14 } +txid-label-x-offset = { size = 20.0 } +txid-copy-btn-right-offset = { size = 50.0 } +txid-copy-btn-y-offset = { size = 2.0 } +confirm-popup-width-ratio = { size = 0.85 } +confirm-glass-rounding-ratio = { size = 0.75 } +confirm-addr-trunc-len = { size = 48 } +confirm-divider-thickness = { size = 1.0 } +confirm-usd-y-offset = { size = 2.0 } +cancel-btn-width-ratio = { size = 0.28 } +disabled-btn-bg-alpha = { size = 20 } +cancel-btn-hover-alpha = { size = 15 } +cancel-btn-border-size = { size = 1.0 } +undo-btn-bg-alpha = { size = 40 } +undo-btn-hover-alpha = { size = 80 } +divider-thickness = { size = 1.0 } +paste-preview-alpha = { size = 0.3 } +paste-preview-max-chars = { size = 80 } +input-overlay-text-alpha = { size = 80 } +right-col-min-height = { size = 72.0 } +memo-label-gap = { size = 2.0 } +max-recent-sends = { size = 4 } +recent-green-alpha = { size = 140 } +row-hover-alpha = { size = 15 } +row-divider-alpha = { size = 15 } +recent-addr-trunc-len = { size = 20 } +text-shadow-offset-x = { size = 1.0 } +text-shadow-offset-y = { size = 1.0 } +text-shadow-alpha = { size = 120 } +status-min-x-ratio = { size = 0.25 } +status-pill-bg-alpha = { size = 30 } +status-pill-y-offset = { size = 1 } +confirmed-threshold = { size = 10 } + +[tabs.send.send-button] +width = 180 +height = 40 +font = "button-lg" +background = "var(--primary)" +color = "var(--on-primary)" +"@compact" = { width = 140, height = 36 } + +[tabs.receive] +left-panel-min-width = 280.0 +left-panel-max-width = 450.0 +left-panel-width-ratio = 0.4 +copy-button-width = 120.0 +explorer-button-width = 140.0 +qr-code-size = 200.0 +label-position = 100.0 +amount-input-width = 150.0 +address-trunc-len = 35 +left-panel = { width-ratio = 0.4, min-width = 280, max-width = 450 } +copy-button = { width = 120, font = "button" } +explorer-button = { width = 140, font = "button" } +qr-code = { size = 200 } +label-column = { position = 100 } +amount-input = { width = 150 } +address-label = { truncate = 35 } +toggle-gap = { size = 2.0 } +toggle-rounding = { size = 4.0 } +qr-col-width-ratio = { size = 0.35 } +currency-icon-width = { size = 12.0 } +currency-icon-gap = { size = 4.0 } +chip-rounding = { size = 12.0 } +chip-gap = { size = 4.0 } +chip-height = { size = 26.0 } +sync-banner-min-height = { size = 22.0 } +sync-banner-height = { size = 28.0 } +toggle-btn-min-width = { size = 30.0 } +toggle-btn-width = { size = 36.0 } +copy-btn-min-width = { size = 60.0 } +copy-btn-width = { size = 75.0 } +new-btn-min-width = { size = 60.0 } +new-btn-width = { size = 75.0 } +recent-icon-min-size = { size = 3.5 } +recent-icon-size = { size = 5.0 } +empty-state-min-height = { size = 54.0 } +empty-state-height = { size = 120.0 } +memo-input-min-height = { size = 24.0 } +memo-input-height = { size = 50.0 } +action-btn-min-height = { size = 26.0 } +action-btn-height = { size = 30.0 } +row-hover-rounding = { size = 4.0 } +status-pill-rounding = { size = 3.0 } +skeleton-rounding = { size = 4.0 } +sync-banner-bg-color = { color = "rgba(153,102,0,0.15)" } +default-addr-trunc-len = { size = 40 } +toggle-active-text-alpha = { size = 255 } +toggle-inactive-bg-alpha = { size = 15 } +addr-preview-trunc-min = { size = 20.0 } +addr-preview-trunc-divisor = { size = 16.0 } +addr-dropdown-trunc-min = { size = 15.0 } +addr-dropdown-trunc-divisor = { size = 14.0 } +new-badge-timeout = { size = 10.0 } +currency-toggle-width = { size = 70.0 } +amount-input-min-width = { size = 100.0 } +input-overlay-text-alpha = { size = 80 } +swap-icon-arrow-gap = { size = 2.5 } +swap-icon-arrow-length-ratio = { size = 0.85 } +swap-icon-arrowhead-size = { size = 2.5 } +swap-icon-line-thickness = { size = 1.5 } +chip-active-bg-alpha = { size = 25 } +memo-label-gap = { size = 2.0 } +memo-max-display-chars = { size = 256 } +clear-btn-hover-alpha = { size = 15 } +qr-max-size = { size = 280.0 } +qr-min-size = { size = 100.0 } +qr-glass-rounding-ratio = { size = 0.75 } +qr-glass-fill-alpha = { size = 12 } +qr-glass-border-alpha = { size = 25 } +qr-unavailable-text-offset = { size = 50.0 } +action-btn-min-width = { size = 90.0 } +action-btn-width-ratio = { size = 0.16 } +btn-hover-alpha = { size = 15 } +explorer-btn-border-size = { size = 1.0 } +divider-thickness = { size = 1.0 } +empty-state-subtitle-gap = { size = 8.0 } +skeleton-height = { size = 100.0 } +skeleton-bar1-height = { size = 16.0 } +skeleton-bar1-width-ratio = { size = 0.6 } +skeleton-bar2-top = { size = 24.0 } +skeleton-bar2-bottom = { size = 36.0 } +skeleton-bar2-width-ratio = { size = 0.4 } +skeleton-text-bottom-offset = { size = 24.0 } +max-recent-receives = { size = 4 } +recent-green-alpha = { size = 140 } +row-hover-alpha = { size = 15 } +row-divider-alpha = { size = 15 } +recent-addr-trunc-len = { size = 20 } +text-shadow-offset-x = { size = 1.0 } +text-shadow-offset-y = { size = 1.0 } +text-shadow-alpha = { size = 120 } +status-min-x-ratio = { size = 0.25 } +status-pill-bg-alpha = { size = 30 } +status-pill-y-offset = { size = 1 } +confirmed-threshold = { size = 10 } + +[tabs.transactions] +search-max-width = 300.0 +search-width-ratio = 0.3 +type-combo-width = 120.0 +table-bottom-reserve = 30.0 +type-column-width = 80.0 +date-column-width = 150.0 +amount-column-width = 150.0 +confirmations-column-width = 100.0 +txid-column-width = 150.0 +address-trunc-len = 20 +txid-trunc-len = 12 +search-input = { max-width = 300, width-ratio = 0.3 } +filter-combo = { width = 120 } +filter-gap = { size = 20.0 } +address-label = { truncate = 20 } +txid-label = { truncate = 12 } +summary-icon-size = { size = 6.0 } +row-icon-size = { size = 5.0 } +row-accent-width = { size = 3.0 } +detail-btn-rounding = { size = 4.0 } +bottom-reserve-min = { size = 20.0 } +bottom-reserve-base = { size = 30.0 } +list-min-height = { size = 60.0 } +list-base-height = { size = 80.0 } +row-hover-rounding = { size = 4.0 } +status-pill-rounding = { size = 3.0 } +accent-bar-rounding = { size = 2.0 } +rows-per-page = { size = 50.0 } + +[tabs.transactions.transaction-table] +bottom-reserve = 30 + +[tabs.transactions.transaction-table.columns] +type = { width = 80 } +date = { width = 150 } +amount = { width = 150, align = "right" } +confirmations = { width = 100 } +txid = { width = 150 } + +[tabs.mining] +thread-slider-width = 300.0 +start-button-width = 200.0 +start-button-height = 50.0 +label-column-width = 250.0 +thread-slider = { width = 300 } +start-button = { width = 200, height = 50, font = "button-lg" } +label-column = { position = 250 } +btn-max-width-ratio = { size = 0.35 } +cell-size = { size = 26.0 } +cell-min-size = { size = 18.0 } +cell-max-size = { size = 42.0 } +cell-rounding = { size = 4.0 } +active-dot-radius = { size = 3.0 } +stats-left-width-ratio = { size = 0.55 } +stats-min-line-height = { size = 14.0 } +recent-row-height = { size = 24.0 } +recent-row-min-height = { size = 18.0 } +card-budget-min = { size = 200.0 } +button-max-width-clamp = { size = 120.0 } +cell-gap-min = { size = 2.0 } +cell-gap-ratio = { size = 0.2 } +control-card-min-height = { size = 60.0 } +active-cell-border-thickness = { size = 1.5 } +cell-border-thickness = { size = 1.0 } +button-icon-y-ratio = { size = 0.42 } +button-label-y-ratio = { size = 0.78 } +chart-line-thickness = { size = 1.5 } +details-card-min-height = { size = 50.0 } +ram-bar = { height = 6.0, rounding = 3.0, opacity = 0.65 } +stats-col1-value-x-ratio = { size = 0.12 } +stats-col2-x-ratio = { size = 0.14 } +mode-toggle-width = { size = 80.0 } +mode-toggle-height = { size = 32.0 } +mode-toggle-rounding = { size = 6.0 } +pool-url-input = { width = 300.0, height = 28.0 } +pool-worker-input = { width = 200.0, height = 28.0 } +log-panel-height = { size = 120.0 } +log-panel-min = { size = 60.0 } + +[tabs.peers] +table-min-height = 150.0 +table-height-ratio = 0.45 +version-column-width = 150.0 +ping-column-width = 80.0 +connected-column-width = 100.0 +ban-score-column-width = 80.0 +banned-table-min-height = 100.0 +banned-table-reserve = 30.0 +banned-until-column-width = 200.0 +action-column-width = 100.0 +stats-card-min-height = { size = 44.0 } +stats-card-base-height = { size = 64.0 } +row-accent-width = { size = 3.0 } +peer-panel-height-ratio = { size = 0.75 } +peer-panel-height-ratio-bans = { size = 0.5 } +peer-panel-min-height = { size = 60.0 } +row-selection-rounding = { size = 4.0 } +row-accent-rounding = { size = 2.0 } +ping-dot-radius-base = { size = 2.5 } +ping-dot-radius-scale = { size = 1.0 } +ping-dot-x-offset = { size = 4.0 } +address-x-offset = { size = 14.0 } +dir-pill-padding = { size = 4.0 } +dir-pill-y-offset = { size = 1.0 } +dir-pill-y-bottom = { size = 3.0 } +dir-pill-rounding = { size = 3.0 } +tls-badge-min-width = { size = 20.0 } +tls-badge-width = { size = 28.0 } +tls-badge-rounding = { size = 3.0 } +banned-panel-min-height = { size = 60.0 } +banned-row-height-padding = { size = 12.0 } +banned-row-rounding = { size = 4.0 } +banned-accent-rounding = { size = 2.0 } +ban-dot-radius-base = { size = 2.0 } +ban-dot-radius-scale = { size = 1.0 } +ban-dot-x-offset = { size = 4.0 } +banned-address-x-offset = { size = 14.0 } +unban-btn-right-offset-multiplier = { size = 3.5 } +banned-row-btn-reserve = { size = 70.0 } + +[tabs.peers.peer-table] +min-height = 150 +height-ratio = 0.45 + +[tabs.peers.peer-table.columns] +version = { width = 150 } +ping = { width = 80 } +connected = { width = 100 } +ban-score = { width = 80 } + +[tabs.peers.banned-table] +min-height = 100 +bottom-reserve = 30 + +[tabs.peers.banned-table.columns] +banned-until = { width = 200 } +action = { width = 100 } + +[tabs.market] +summary-min-height = 100.0 +summary-max-height = 160.0 +summary-height-ratio = 0.25 +btc-price-position = 250.0 +change-24h-position = 120.0 +volume-label-position = 300.0 +volume-value-position = 420.0 +market-cap-label-position = 600.0 +market-cap-value-position = 720.0 +chart-height = 250.0 +portfolio-value-position = 150.0 +portfolio-btc-position = 350.0 +summary-panel = { min-height = 100, max-height = 160, height-ratio = 0.25 } +stats-card-min-height = { size = 44.0 } +chart-line-thickness = { size = 2.0 } +btc-price-label = { position = 250 } +change-24h-label = { position = 120 } +volume-label = { position = 300 } +volume-value-label = { position = 420 } +market-cap-label = { position = 600 } +market-cap-value-label = { position = 720 } +chart = { height = 220 } +portfolio-value-label = { position = 150 } +portfolio-btc-label = { position = 350 } +hero-card-min-height = { size = 50.0 } +hero-card-height = { size = 80.0 } +accent-stripe-inset-ratio = { size = 0.0 } +accent-stripe-left-offset = { size = 0.0 } +accent-stripe-width = { size = 4.0 } +accent-stripe-rounding = { size = 1.5 } +chart-y-axis-min-padding = { size = 40.0 } +chart-y-axis-padding = { size = 70.0 } +chart-dot-min-radius = { size = 1.5 } +chart-dot-radius = { size = 2.0 } +chart-hover-dot-min-radius = { size = 3.0 } +chart-hover-dot-radius = { size = 4.0 } +chart-hover-ring-min-radius = { size = 4.5 } +chart-hover-ring-radius = { size = 6.0 } +ratio-bar-min-height = { size = 4.0 } +ratio-bar-height = { size = 6.0 } +# Exchange pair bar +pair-bar-height = { height = 32.0 } +pair-chip-height = { height = 24.0 } +pair-chip-radius = { radius = 12.0 } +pair-chip-spacing = { size = 6.0 } +pair-bar-fade-width = { size = 48.0 } +pair-bar-arrow-size = { size = 28.0 } +exchange-combo-width = { size = 180.0 } +exchange-top-gap = { size = 0.0 } + +[tabs.console] +input-area-padding = 8.0 +output-line-spacing = 2.0 +output = { line-spacing = 2 } +scroll-multiplier = { size = 3.0 } +selection-extension = { size = 4.0 } +input-cursor-offset = { size = 3.0 } +output-min-height = { size = 40.0 } +output-min-height-ratio = { size = 0.15 } +status-dot-radius-base = { size = 3.0 } +status-dot-radius-scale = { size = 2.0 } +filter-max-width = { size = 160.0 } +filter-width-ratio = { size = 0.25 } +popup-max-width = { size = 680.0 } +popup-width-ratio = { size = 0.85 } +popup-max-height = { size = 520.0 } +popup-height-ratio = { size = 0.8 } +cmd-name-col-width = { size = 180.0 } +cmd-params-col-width = { size = 200.0 } +cmd-min-width = { size = 500.0 } +scanline-speed = { size = 40.0 } +scanline-height = { size = 36.0 } +scanline-alpha = { size = 8.0 } +scanline-gap = { size = 2.0 } +scanline-line-alpha = { size = 4.0 } +scanline-glow-spread = { size = 4.0 } +scanline-glow-intensity = { size = 0.6 } +scanline-glow-color = { size = 255.0 } +zoom-step = { size = 0.1 } +zoom-min = { size = 0.5 } +zoom-max = { size = 3.0 } + +[tabs.console.input-area] +padding = [8, 8] + +[dialogs] + +[dialogs.about] +width = 500.0 +height = 450.0 +title-font-scale = 1.5 +label-column-position = 120.0 +link-button-width = 100.0 +close-button-width = 120.0 +edition-label-right-offset = 120.0 +window = { width = 500, height = 450 } +title-label = { font = "h4", color = "var(--primary)" } +version-label = { font = "caption", position = 120 } +edition-label = { position = 120 } +link-button = { width = 100, font = "button-sm" } +close-button = { width = 120, font = "button", align = "center" } + +[dialogs.settings] +width = 600.0 +height = 550.0 +label-column-position = 150.0 +combo-width = 200.0 +connection-label-position = 100.0 +port-input-width = 100.0 +wallet-button-width = 200.0 +save-button-width = 100.0 +cancel-button-width = 100.0 +window = { width = 600, height = 550 } +label = { position = 150 } +combo = { width = 200 } +connection-label = { position = 100 } +port-input = { width = 100 } +wallet-button = { width = 200, font = "button" } +save-button = { width = 100, font = "button", background = "var(--primary)" } +cancel-button = { width = 100, font = "button", background = "var(--surface-variant)" } + +[dialogs.transaction-details] +width = 550.0 +height = 450.0 +confirmations-right-offset = 150.0 +label-column-position = 120.0 +txid-input-right-pad = 80.0 +copy-button-width = 70.0 +address-multiline-right-pad = 80.0 +address-multiline-height = 50.0 +memo-height = 60.0 +bottom-button-width = 130.0 +window = { width = 550, height = 450 } +label = { position = 120 } +confirmations-label = { position = 150 } +txid-input = { width = -80 } +copy-button = { width = 70, font = "button-sm" } +address-input = { width = -80, height = 50 } +memo-input = { height = 60 } +bottom-button = { width = 130, font = "button" } + +[dialogs.key-export] +width = 550.0 +height = 380.0 +warning-box-height = 80.0 +address-input-height = 60.0 +reveal-button-width = 120.0 +key-display-height = 80.0 +toggle-button-width = 80.0 +copy-button-width = 150.0 +close-button-width = 100.0 +window = { width = 550, height = 380 } +warning-box = { height = 80 } +address-input = { height = 60 } +reveal-button = { width = 120, font = "button" } +key-display = { height = 80 } +toggle-button = { width = 80, font = "button-sm" } +copy-button = { width = 150, font = "button" } +close-button = { width = 100, font = "button" } + +[dialogs.qr-popup] +width = 380.0 +height = 480.0 +qr-code-size = 280.0 +address-input-height = 60.0 +button-width = 120.0 +window = { width = 380, height = 480 } +qr-code = { size = 280 } +address-input = { height = 60 } +action-button = { width = 120, font = "button" } + +[dialogs.validate-address] +width = 500.0 +height = 300.0 +validate-button-width = 100.0 +paste-button-width = 80.0 +label-column-position = 100.0 +close-button-width = 100.0 +window = { width = 500, height = 300 } +validate-button = { width = 100, font = "button" } +paste-button = { width = 80, font = "button-sm" } +label = { position = 100 } +close-button = { width = 100, font = "button" } + +[dialogs.address-book] +width = 600.0 +height = 450.0 +table-bottom-reserve = 35.0 +label-column-width = 150.0 +notes-column-width = 150.0 +address-trunc-len = 40 +address-front-len = 20 +address-back-len = 17 +input-width = 400.0 +notes-height = 60.0 +action-button-width = 100.0 +window = { width = 600, height = 450 } +address-front-label = { truncate = 20 } +address-back-label = { truncate = 17 } +address-input = { width = 400 } +notes-input = { height = 60 } +action-button = { width = 100, font = "button" } + +[dialogs.address-book.address-table] +bottom-reserve = 35 + +[dialogs.address-book.address-table.columns] +label = { width = 150 } +notes = { width = 150 } +address = { truncate = 40 } + +[dialogs.shield] +width = 500.0 +height = 400.0 +address-trunc-threshold = 50 +address-trunc-front = 20 +address-trunc-back = 20 +fee-input-width = 150.0 +utxo-limit-input-width = 150.0 +shield-button-width = 120.0 +cancel-button-width = 100.0 +window = { width = 500, height = 400 } +address-label = { truncate = 50 } +address-front-label = { truncate = 20 } +address-back-label = { truncate = 20 } +fee-input = { width = 150 } +utxo-limit-input = { width = 150 } +shield-button = { width = 120, font = "button" } +cancel-button = { width = 100, font = "button" } + +[dialogs.request-payment] +width = 500.0 +height = 550.0 +z-addr-trunc-threshold = 50 +z-addr-trunc-front = 20 +z-addr-trunc-back = 20 +t-addr-trunc-threshold = 40 +t-addr-trunc-front = 17 +t-addr-trunc-back = 17 +amount-input-width = 150.0 +memo-height = 60.0 +qr-code-size = 200.0 +button-width = 100.0 +window = { width = 500, height = 550 } +z-addr-label = { truncate = 50 } +z-addr-front-label = { truncate = 20 } +z-addr-back-label = { truncate = 20 } +t-addr-label = { truncate = 40 } +t-addr-front-label = { truncate = 17 } +t-addr-back-label = { truncate = 17 } +amount-input = { width = 150 } +memo-input = { height = 60 } +qr-code = { size = 200 } +action-button = { width = 100, font = "button" } + +[dialogs.block-info] +width = 550.0 +height = 450.0 +height-input-width = 150.0 +label-column-position = 150.0 +hash-trunc-threshold = 50 +hash-trunc-front = 20 +hash-trunc-back = 20 +close-button-bottom-offset = 40.0 +close-button-width = 100.0 +window = { width = 550, height = 450 } +height-input = { width = 150 } +label = { position = 150 } +hash-label = { truncate = 50 } +hash-front-label = { truncate = 20 } +hash-back-label = { truncate = 20 } +close-button = { width = 100, font = "button" } + +[dialogs.export-all-keys] +width = 500.0 +height = 400.0 +export-button-width = 120.0 +close-button-width = 100.0 +window = { width = 500, height = 400 } +export-button = { width = 120, font = "button" } +close-button = { width = 100, font = "button" } + +[dialogs.export-transactions] +width = 450.0 +height = 280.0 +export-button-width = 120.0 +close-button-width = 100.0 +window = { width = 450, height = 280 } +export-button = { width = 120, font = "button" } +close-button = { width = 100, font = "button" } + +[dialogs.backup-wallet] +width = 550.0 +height = 280.0 +backup-button-width = 120.0 +close-button-width = 100.0 +window = { width = 550, height = 280 } +backup-button = { width = 120, font = "button" } +close-button = { width = 100, font = "button" } + +[dialogs.import-key] +width = 550.0 +height = 450.0 +key-input-height = 150.0 +rescan-height-input-width = 100.0 +import-button-width = 120.0 +close-button-width = 100.0 +window = { width = 550, height = 450 } +key-input = { height = 150 } +rescan-height-input = { width = 100 } +import-button = { width = 120, font = "button" } +close-button = { width = 100, font = "button" } + +[components] + +[components.status-bar] +padding = [8.0, 8.0] +height = 32.0 +right-content-offset = 220.0 +version-right-offset = 70.0 +text-style = { font = "body2", opacity = 0.6 } +icon-text-gap = { size = 4.0 } +section-gap = { size = 16.0 } +separator-gap = { size = 8.0 } +right-content = { position = 220 } +version-label = { position = 30 } +connection-dot = { opacity = 1.0 } + +[components.status-bar.window] +height = 30 +padding = [8, 0] + +[components.notifications] +width = 350.0 +height = 60.0 +border-width = 1.0 +border-radius = 8.0 +padding = [12.0, 10.0] +progress-bar-y-offset = 18.0 +pill-margin-y = { size = 3.0 } +pill-rounding = { size = 12.0 } +padding-x = { size = 12.0 } +glass-fill-alpha = { size = 18.0 } +glass-border-alpha = { size = 35.0 } +progress-bar-height = { size = 2.0 } +duration-info = { size = 1.0 } +duration-success = { size = 2.5 } +duration-warning = { size = 3.5 } +duration-error = { size = 4.0 } +window = { width = 350, height = 60, border-radius = 8, border-width = 1 } +viewport-padding = { size = 20.0 } +stack-gap = { size = 10.0 } +menu-bar-offset = { size = 25.0 } +notification-text = { font = "body2", color = "var(--on-surface)" } +notification-progress = { color = "var(--primary)", height = 4, position = 18 } + +[components.modal-scrim] +fill-alpha = { size = 12.0 } +noise-alpha = { size = 14.0 } + +[components.qr-code] +module-scale = { size = 4 } +border-modules = { size = 2 } + +[components.sidebar] +min-width = 280 +max-width = 400 +width-ratio = 0.32 +width = { size = 140.0 } +collapsed-width = { size = 64.0 } +collapse-anim-speed = { size = 10.0 } +auto-collapse-threshold = { size = 800.0 } +section-gap = { size = 4.0 } +section-label-pad-left = { size = 16.0 } +item-height = { size = 42.0 } +item-pad-x = { size = 8.0 } +min-height = { size = 360.0 } +margin-top = { size = -12 } +margin-bottom = { size = 40 } +glass-margin-y = { size = 6.0 } +glass-margin-left = { size = 6.0 } +glass-margin-right = { size = 2.0 } +strip-height = { size = 20.0 } +nav-gap = { size = 14.0 } +button-pad-collapsed = { size = 8.0 } +button-pad-expanded = { size = 14.0 } +icon-half-size = { size = 7.0 } +icon-label-gap = { size = 8.0 } +badge-radius-dot = { size = 4.0 } +badge-radius-number = { size = 8.0 } +button-spacing = { size = 4.0 } +bottom-padding = { size = 0.0 } +exit-icon-gap = { size = 4.0 } +cutout-shadow-alpha = { size = 55 } +cutout-highlight-alpha = { size = 8 } +cutout-line-width = { size = 0.75 } +cutout-glow-expand = { size = 0.0 } +cutout-glow-alpha = { size = 128 } +cutout-glow-line-width = { size = 0.5 } +inset-shadow-threshold = { size = 0.1 } +inset-shadow-inset = { size = 0.0 } +inset-shadow-max-alpha = { size = 48.0 } +inset-shadow-fade-ratio = { size = 5.0 } + +[components.content-area] +padding-x = 0.0 +padding-y = 0.0 +margin-top = { size = 4.0 } +margin-bottom = { size = -40.0 } +edge-fade-zone = { size = 0.0 } + +[components.content-area.window] +padding = [0, 12] + +[components.main-window] +padding-bottom = { size = 0.0 } +page-fade-speed = { size = 8.0 } +collapse-hysteresis = { size = 60.0 } +header-icon = { icon-dark = "logos/logo_ObsidianDragon_dark.png", icon-light = "logos/logo_ObsidianDragon_light.png" } +coin-icon = { icon = "logos/logo_dragonx_128.png" } +header-title = { font = "subtitle1", size = 14.0, pad-x = 16.0, pad-y = 12.0, logo-gap = 8.0, opacity = 0.7 } + +[components.main-window.window] +padding = [12, 38] + +[components.shutdown] +content-height = { height = 120.0 } +spinner-radius = { size = 20.0 } +spinner-thickness = { size = 3.0 } +spinner-speed = { size = 2.5 } +panel-width-fraction = { size = 0.7 } +panel-max-height = { size = 160.0 } +panel-rounding = { size = 6.0 } +panel-padding = { size = 12.0 } +separator-pad-fraction = { size = 0.25 } + +[components.settings-page] +top-margin = { size = 2.0 } +appearance-card-height = { size = 220.0 } +combo-row-gap = { size = 12.0 } +combo-inline-label-width = { size = 100.0 } +compact-breakpoint = { size = 700.0 } +wallet-btn-columns-wide = { size = 5.0 } +wallet-btn-columns-narrow = { size = 3.0 } +section-divider-alpha = { opacity = 0.08 } +edge-fade-zone = { size = 28.0 } +edge-fade-offset-top = { size = 0.0 } +edge-fade-offset-bottom = { size = 0.0 } +scroll-fade-color = { color = "var(--background)" } +label-min-width = { size = 100.0 } +label-width = { size = 120.0 } +input-min-width = { size = 180.0 } +refresh-btn-width = { size = 80.0 } +theme-combo-min-width = { size = 180.0 } +effects-input-min-width = { size = 100.0 } +effects-input-offset = { size = 80.0 } +save-btn-width = { size = 120.0 } +reset-btn-width = { size = 140.0 } +wallet-btn-min-height = { size = 24.0 } +wallet-btn-height = { size = 30.0 } +wallet-btn-min-width = { size = 130.0 } +wallet-btn-padding = { size = 24.0 } +rpc-label-min-width = { size = 70.0 } +rpc-label-width = { size = 85.0 } +security-combo-width = { size = 120.0 } +port-input-min-width = { size = 60.0 } +port-input-width-ratio = { size = 0.4 } + +[components.main-layout] +app-bar-height = { size = 64.0 } +status-bar-height = { size = 32.0 } +drawer-width = { size = 256.0 } +sync-bar-width = { size = 100.0 } +sync-bar-height = { size = 4.0 } +app-bar-button-size = { size = 40.0 } +app-bar-btn-rounding = { size = 20.0 } +title-font-height = { size = 24.0 } + +[style] +shadow-multiplier = { size = 0.6 } +shadow-multiplier-light = { size = 2.5 } +window-padding-x = 10.0 +window-padding-y = 10.0 +frame-padding-x = 8.0 +frame-padding-y = 4.0 +item-spacing-x = 8.0 +item-spacing-y = 6.0 +item-inner-spacing-x = 6.0 +item-inner-spacing-y = 4.0 +indent-spacing = 20.0 +scrollbar-size = 6.0 +grab-min-size = 8.0 +border-width = { window = 1.0, child = 1.0, popup = 1.0, frame = 0.0 } + +[style.border-radius] +window = 6.0 +child = 4.0 +frame = 4.0 +popup = 4.0 +scrollbar = 4.0 +grab = 4.0 +tab = 4.0 + +[style.padding] +window = [10.0, 10.0] +frame = [8.0, 4.0] + +[style.spacing] +item = [8.0, 6.0] +item-inner = [6.0, 4.0] +indent = 20.0 + +[panels] +summary = { min-width = 280.0, max-width = 400.0, width-ratio = 0.32, min-height = 200.0, max-height = 350.0, height-ratio = 0.8 } +side-panel = { min-width = 280.0, max-width = 450.0, width-ratio = 0.4, min-height = 200.0, max-height = 350.0, height-ratio = 0.8 } +table = { min-height = 150.0, height-ratio = 0.45, min-remaining = 100.0, default-reserve = 30.0 } + +[button] +min-width = 180.0 +width = 140.0 +width-lg = 160.0 +height = 0.0 +right-align-gap = 8.0 +right-align-margin = 16.0 +right-align-min-pos = 200.0 + +[business] +block-reward = { size = 1.5625 } +default-fee = { size = 0.0001 } +memo-max-length = { size = 512 } +utxo-limit = { size = 50 } +ram-base-mb = { size = 500.0 } +ram-dataset-mb = { size = 2080.0 } +ram-cache-mb = { size = 256.0 } +ram-per-thread-mb = { size = 2.0 } + +[animations] +pulse-speed-normal = { size = 3.0 } +pulse-speed-slow = { size = 2.0 } +pulse-speed-fast = { size = 4.0 } +pulse-base-normal = { size = 0.6 } +pulse-amp-normal = { size = 0.4 } +pulse-base-glow = { size = 0.5 } +pulse-amp-glow = { size = 0.5 } +skeleton-base = { size = 0.3 } +skeleton-amp = { size = 0.15 } +heat-glow-speed = { size = 2.5 } +heat-glow-phase-offset = { size = 0.4 } + +[console] +color-command = { color = "rgba(191,209,229,1.0)" } +color-result = { color = "rgba(200,200,200,1.0)" } +color-error = { color = "rgba(246,71,64,1.0)" } +color-daemon = { color = "rgba(160,160,160,0.706)" } +color-info = { color = "rgba(191,209,229,1.0)" } + +[inline-dialogs] +about = { width = 400.0, height = 250.0, close-button-width = 120.0, button-font = 1 } +import-key = { width = 500.0, height = 200.0, button-width = 120.0, button-font = 1 } +backup = { width = 500.0, height = 200.0, button-width = 120.0, button-font = 1 } + +[inline-dialogs.export-key] +width = 600.0 +height = 300.0 +key-display-height = 60.0 +close-button-width = 120.0 +button-font = 1 +close-button-font = -1 +addr-front-len = 20 +addr-back-len = 8 + +[backdrop] +gradient-top-r = 20 +gradient-top-g = 8 +gradient-top-b = 4 +gradient-top-a = 85 +gradient-bottom-r = 10 +gradient-bottom-g = 4 +gradient-bottom-b = 2 +gradient-bottom-a = 65 +background-alpha = 0.38 +surface-alpha = 0.48 +frame-alpha = 0.72 +surface-inline-alpha = 0.52 +background-inline-alpha = 0.28 +base-color-top = "rgba(30,14,10,210)" +base-color-bottom = "rgba(12,6,4,210)" +texture-tint-alpha = 135 +noise-opacity = { size = 48.0 } +noise-tile-scale = { size = 1.0 } +noise-texture-size = { size = 256.0 } +noise-max-alpha = { size = 6.0 } + + +[responsive] +glass-rounding = 8.0 +card-inner-padding = 12.0 +card-gap = 8.0 +ref-width = 1200.0 +ref-height = 650.0 +min-h-scale = 0.5 +max-h-scale = 1.5 +min-v-scale = 0.5 +max-v-scale = 1.4 +min-density = 0.6 +max-density = 1.2 +compact-width = 500.0 +compact-height = 400.0 +expanded-width = 900.0 +expanded-height = 700.0 + +# --------------------------------------------------------------------------- +# Loading Overlay (content area — while daemon is starting/syncing) +# --------------------------------------------------------------------------- +[screens.loading] +spinner-radius = { size = 18.0 } +spinner-thickness = { size = 2.5 } +spinner-speed = { size = 2.5 } +title-font = { font = "h6" } +status-font = { font = "body2" } +progress-bar = { height = 6.0, radius = 3.0 } +progress-width = { size = 260.0 } +backdrop-alpha = { opacity = 0.80 } +vertical-gap = { size = 8.0 } + +# --------------------------------------------------------------------------- +# First-Run Wizard Screens +# --------------------------------------------------------------------------- +[screens.first-run] +card = { width = 520.0, height = 440.0 } +logo = { size = 56.0 } +title = { font = "h5" } +subtitle = { font = "body1" } +progress-bar = { height = 8.0, radius = 4.0 } +primary-button = { width = 220.0, height = 44.0, font = "subtitle1" } +skip-button = { width = 120.0, height = 44.0, font = "subtitle1" } +trust-warning = { font = "caption", opacity = 0.7 } +strength-bar = { height = 4.0, radius = 2.0 } + +# --------------------------------------------------------------------------- +# Lock Screen +# --------------------------------------------------------------------------- +[screens.lock-screen] +card = { width = 400.0, height = 400.0 } +logo = { size = 64.0 } +title = { font = "h5" } +input = { width = 320.0, height = 40.0 } +unlock-button = { width = 320.0, height = 44.0, font = "subtitle1" } +error-text = { font = "caption" } +backdrop-alpha = { opacity = 0.0 } +mode-toggle = { font = "caption" } + +# --------------------------------------------------------------------------- +# Security defaults +# --------------------------------------------------------------------------- +[security] +auto-lock-timeout = { size = 300.0 } +unlock-duration = { size = 600.0 } +max-attempts-before-lockout = { size = 5.0 } +lockout-base-delay = { size = 2.0 } +pin-min-length = { size = 4.0 } +pin-max-length = { size = 8.0 } + +# --------------------------------------------------------------------------- +# Theme Visual Effects (DragonX base — fire-themed) +# Warm ember glow that smolders rather than flashes. Fire gradient tinting +# gives panels a volcanic warmth. No shimmer — fire doesn't sweep. +# --------------------------------------------------------------------------- +[effects] +hue-cycle-enabled = { size = 1.0 } +hue-cycle-speed = { size = 0.08 } +hue-cycle-saturation = { size = 0.85 } +hue-cycle-value = { size = 0.85 } +hue-cycle-range = { size = 0.15 } +hue-cycle-offset = { size = 0.0 } + +rainbow-border-enabled = { size = 1.0 } +rainbow-border-speed = { size = 0.03 } +rainbow-border-alpha = { size = 0.08 } +rainbow-border-stop-0 = { color = "#D32F2F" } +rainbow-border-stop-1 = { color = "#FF6D00" } +rainbow-border-stop-2 = { color = "#FFD54F" } + +shimmer-enabled = { size = 0.0 } + +positional-hue-enabled = { size = 1.0 } +positional-hue-top = { color = "#B71C1C" } +positional-hue-bottom = { color = "#FF9E40" } +positional-hue-strength = { size = 0.15 } + +# Thin bright crimson border glow on active sidebar button +glow-pulse-enabled = { size = 1.0 } +glow-pulse-speed = { size = 0.35 } +glow-pulse-min-alpha = { size = 0.15 } +glow-pulse-max-alpha = { size = 0.45 } +glow-pulse-radius = { size = 3.0 } +glow-pulse-color = { color = "#E53935" } + +edge-trace-enabled = { size = 0.0 } + +ember-rise-enabled = { size = 1.0 } +ember-rise-count = { size = 7.0 } +ember-rise-speed = { size = 0.35 } +ember-rise-particle-size = { size = 1.4 } +ember-rise-alpha = { size = 0.45 } +ember-rise-color = { color = "#FF6A00" } + +# Shader-like viewport overlay — warm fire color grading + vignette +viewport-wash-enabled = { size = 1.0 } +viewport-wash-alpha = { size = 0.04 } +viewport-wash-tl = { color = "#B71C1C" } +viewport-wash-tr = { color = "#FF6A00" } +viewport-wash-bl = { color = "#3E2723" } +viewport-wash-br = { color = "#FF8F00" } +viewport-wash-rotate = { size = 0.0 } +viewport-wash-pulse = { size = 0.15 } +viewport-wash-pulse-depth = { size = 0.3 } + +viewport-vignette-enabled = { size = 1.0 } +viewport-vignette-color = { color = "#1A0800" } +viewport-vignette-radius = { size = 0.20 } +viewport-vignette-alpha = { size = 0.15 } diff --git a/scripts/create-appimage.sh b/scripts/create-appimage.sh new file mode 100755 index 0000000..2444f5f --- /dev/null +++ b/scripts/create-appimage.sh @@ -0,0 +1,159 @@ +#!/bin/bash +# DragonX ImGui Wallet - AppImage Creation Script +# Copyright 2024-2026 The Hush Developers +# Released under the GPLv3 + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_DIR="${SCRIPT_DIR}/build/linux" +APPDIR="${BUILD_DIR}/AppDir" +VERSION="1.0.0" + +# Colors +GREEN='\033[0;32m' +RED='\033[0;31m' +NC='\033[0m' + +print_status() { echo -e "${GREEN}[*]${NC} $1"; } +print_error() { echo -e "${RED}[ERROR]${NC} $1"; } + +# Check prerequisites +if [ ! -f "${BUILD_DIR}/bin/ObsidianDragon" ]; then + print_error "Binary not found. Run build.sh --linux-release first." + exit 1 +fi + +# Check for appimagetool +APPIMAGETOOL="" +if command -v appimagetool &> /dev/null; then + APPIMAGETOOL="appimagetool" +elif [ -f "${BUILD_DIR}/appimagetool-x86_64.AppImage" ]; then + APPIMAGETOOL="${BUILD_DIR}/appimagetool-x86_64.AppImage" +else + print_status "Downloading appimagetool..." + wget -q -O "${BUILD_DIR}/appimagetool-x86_64.AppImage" \ + "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage" + chmod +x "${BUILD_DIR}/appimagetool-x86_64.AppImage" + APPIMAGETOOL="${BUILD_DIR}/appimagetool-x86_64.AppImage" +fi + +print_status "Creating AppDir structure..." +rm -rf "${APPDIR}" +mkdir -p "${APPDIR}/usr/bin" +mkdir -p "${APPDIR}/usr/lib" +mkdir -p "${APPDIR}/usr/share/applications" +mkdir -p "${APPDIR}/usr/share/icons/hicolor/256x256/apps" +mkdir -p "${APPDIR}/usr/share/ObsidianDragon/res" + +# Copy binary +print_status "Copying binary..." +cp "${BUILD_DIR}/bin/ObsidianDragon" "${APPDIR}/usr/bin/" + +# Copy resources +print_status "Copying resources..." +cp -r "${BUILD_DIR}/bin/res/"* "${APPDIR}/usr/share/ObsidianDragon/res/" 2>/dev/null || true + +# Create desktop file +print_status "Creating desktop file..." +cat > "${APPDIR}/usr/share/applications/ObsidianDragon.desktop" << EOF +[Desktop Entry] +Type=Application +Name=DragonX Wallet +Comment=DragonX Cryptocurrency Wallet +Exec=ObsidianDragon +Icon=ObsidianDragon +Categories=Finance;Network; +Terminal=false +StartupNotify=true +EOF + +# Copy desktop file to root +cp "${APPDIR}/usr/share/applications/ObsidianDragon.desktop" "${APPDIR}/" + +# Create icon (simple SVG placeholder if no icon exists) +print_status "Creating icon..." +if [ -f "${SCRIPT_DIR}/res/icons/dragonx-256.png" ]; then + cp "${SCRIPT_DIR}/res/icons/dragonx-256.png" "${APPDIR}/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" +else + # Create a simple SVG icon as placeholder + cat > "${APPDIR}/ObsidianDragon.svg" << 'EOF' + + + + + DX + +EOF + # Convert SVG to PNG if rsvg-convert is available + if command -v rsvg-convert &> /dev/null; then + rsvg-convert -w 256 -h 256 "${APPDIR}/ObsidianDragon.svg" > \ + "${APPDIR}/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" + fi +fi + +# Copy icon to root +cp "${APPDIR}/usr/share/icons/hicolor/256x256/apps/ObsidianDragon.png" "${APPDIR}/" 2>/dev/null || \ + cp "${APPDIR}/ObsidianDragon.svg" "${APPDIR}/ObsidianDragon.png" 2>/dev/null || true + +# Create AppRun script +print_status "Creating AppRun..." +cat > "${APPDIR}/AppRun" << 'EOF' +#!/bin/bash +SELF=$(readlink -f "$0") +HERE=${SELF%/*} + +# Set up resource paths +export DRAGONX_RES_PATH="${HERE}/usr/share/ObsidianDragon/res" + +# Find libraries +export LD_LIBRARY_PATH="${HERE}/usr/lib:${LD_LIBRARY_PATH}" + +# Change to resource directory for relative paths +cd "${HERE}/usr/share/ObsidianDragon" + +exec "${HERE}/usr/bin/ObsidianDragon" "$@" +EOF +chmod +x "${APPDIR}/AppRun" + +# Bundle required libraries (basic set) +print_status "Bundling libraries..." +LIBS_TO_BUNDLE=( + "libSDL3.so" +) + +for lib in "${LIBS_TO_BUNDLE[@]}"; do + LIB_PATH=$(ldconfig -p | grep "$lib" | head -1 | awk '{print $NF}') + if [ -n "$LIB_PATH" ] && [ -f "$LIB_PATH" ]; then + cp "$LIB_PATH" "${APPDIR}/usr/lib/" 2>/dev/null || true + fi +done + +# Also copy SDL3 from build if exists +if [ -f "${BUILD_DIR}/_deps/sdl3-build/libSDL3.so" ]; then + cp "${BUILD_DIR}/_deps/sdl3-build/libSDL3.so"* "${APPDIR}/usr/lib/" 2>/dev/null || true +fi + +# Create AppImage +print_status "Creating AppImage..." +cd "${BUILD_DIR}" + +ARCH=$(uname -m) +APPIMAGE_NAME="DragonX_Wallet-${VERSION}-${ARCH}.AppImage" + +# Run appimagetool +ARCH="${ARCH}" "${APPIMAGETOOL}" "${APPDIR}" "${APPIMAGE_NAME}" + +if [ -f "${APPIMAGE_NAME}" ]; then + # Copy to release/linux/ for clean output + OUT_DIR="${SCRIPT_DIR}/release/linux" + mkdir -p "${OUT_DIR}" + cp "${APPIMAGE_NAME}" "${OUT_DIR}/" + print_status "AppImage created successfully!" + print_status "Output: ${OUT_DIR}/${APPIMAGE_NAME}" + ls -lh "${OUT_DIR}/${APPIMAGE_NAME}" +else + print_error "AppImage creation failed" + exit 1 +fi diff --git a/scripts/fetch-libsodium.sh b/scripts/fetch-libsodium.sh new file mode 100755 index 0000000..33f4370 --- /dev/null +++ b/scripts/fetch-libsodium.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# ── scripts/fetch-libsodium.sh ────────────────────────────────────────────── +# Download and build libsodium from source for the target platform. +# Called automatically by CMake when the pre-built library is not found, +# or manually before building: +# +# ./scripts/fetch-libsodium.sh # native (Linux/macOS) +# ./scripts/fetch-libsodium.sh --mac # macOS cross-compile via osxcross +# ./scripts/fetch-libsodium.sh --win # Windows cross-compile via MinGW +# +# Output: libs/libsodium/ (include/ + lib/libsodium.a) +# ───────────────────────────────────────────────────────────────────────────── +set -euo pipefail + +SODIUM_VERSION="1.0.18" +SODIUM_SHA256="6f504490b342a4f8a4c4a02fc9b866cbef8622d5df4e5452b46be121e46636c1" +SODIUM_URL="https://github.com/jedisct1/libsodium/releases/download/1.0.18-RELEASE/libsodium-${SODIUM_VERSION}.tar.gz" + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" + +TARGET="native" +while [[ $# -gt 0 ]]; do + case $1 in + --mac) TARGET="mac"; shift ;; + --win) TARGET="win"; shift ;; + *) echo "Unknown option: $1"; exit 1 ;; + esac +done + +# ── Output directories ────────────────────────────────────────────────────── +case "$TARGET" in + mac) INSTALL_DIR="$PROJECT_DIR/libs/libsodium-mac" ;; + win) INSTALL_DIR="$PROJECT_DIR/libs/libsodium-win" ;; + *) INSTALL_DIR="$PROJECT_DIR/libs/libsodium" ;; +esac + +# Skip if already built +if [[ -f "$INSTALL_DIR/lib/libsodium.a" ]]; then + echo "[fetch-libsodium] Already present: $INSTALL_DIR/lib/libsodium.a" + exit 0 +fi + +# ── Download ──────────────────────────────────────────────────────────────── +TARBALL="$PROJECT_DIR/libs/libsodium-${SODIUM_VERSION}.tar.gz" +SRC_DIR="$PROJECT_DIR/libs/libsodium-${SODIUM_VERSION}" + +if [[ ! -f "$TARBALL" ]]; then + echo "[fetch-libsodium] Downloading libsodium ${SODIUM_VERSION}..." + curl -fSL -o "$TARBALL" "$SODIUM_URL" +fi + +# Verify checksum +echo "$SODIUM_SHA256 $TARBALL" | sha256sum -c - || { + echo "[fetch-libsodium] ERROR: SHA256 mismatch! Removing corrupted download." + rm -f "$TARBALL" + exit 1 +} + +# ── Extract ───────────────────────────────────────────────────────────────── +if [[ ! -d "$SRC_DIR" ]]; then + echo "[fetch-libsodium] Extracting..." + tar -xzf "$TARBALL" -C "$PROJECT_DIR/libs/" +fi + +# ── Configure & build ─────────────────────────────────────────────────────── +cd "$SRC_DIR" + +CONFIGURE_ARGS=( + --prefix="$INSTALL_DIR" + --disable-shared + --enable-static + --with-pic +) + +case "$TARGET" in + mac) + # Cross-compile for macOS via osxcross + if [[ -z "${OSXCROSS:-}" ]]; then + for try in "$HOME/osxcross" "/opt/osxcross" "$PROJECT_DIR/osxcross"; do + [[ -d "$try/target" ]] && OSXCROSS="$try" && break + done + fi + if [[ -z "${OSXCROSS:-}" ]]; then + echo "[fetch-libsodium] ERROR: osxcross not found. Set OSXCROSS=/path/to/osxcross" + exit 1 + fi + export PATH="$OSXCROSS/target/bin:$PATH" + + # Detect osxcross triple + TRIPLE=$(ls "$OSXCROSS/target/bin/" | grep -o 'x86_64-apple-darwin[0-9]*' | head -1) + [[ -z "$TRIPLE" ]] && TRIPLE="x86_64-apple-darwin22" + + CONFIGURE_ARGS+=(--host="$TRIPLE") + export CC="${TRIPLE}-cc" + export CXX="${TRIPLE}-c++" + export AR="${TRIPLE}-ar" + export RANLIB="${TRIPLE}-ranlib" + ;; + win) + # Cross-compile for Windows via MinGW + CONFIGURE_ARGS+=(--host=x86_64-w64-mingw32) + # Prefer the posix-thread variant if available + if command -v x86_64-w64-mingw32-gcc-posix &>/dev/null; then + export CC=x86_64-w64-mingw32-gcc-posix + export CXX=x86_64-w64-mingw32-g++-posix + else + export CC=x86_64-w64-mingw32-gcc + export CXX=x86_64-w64-mingw32-g++ + fi + export AR=x86_64-w64-mingw32-ar + export RANLIB=x86_64-w64-mingw32-ranlib + # Disable _FORTIFY_SOURCE — MinGW doesn't provide __memcpy_chk etc. + export CFLAGS="${CFLAGS:-} -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0" + ;; +esac + +echo "[fetch-libsodium] Configuring for target: $TARGET ..." +./configure "${CONFIGURE_ARGS[@]}" > /dev/null + +echo "[fetch-libsodium] Building..." +make -j"$(nproc)" > /dev/null 2>&1 + +echo "[fetch-libsodium] Installing to $INSTALL_DIR ..." +make install > /dev/null + +# ── Cleanup ───────────────────────────────────────────────────────────────── +cd "$PROJECT_DIR" +rm -rf "$SRC_DIR" +rm -f "$TARBALL" + +echo "[fetch-libsodium] Done: $INSTALL_DIR/lib/libsodium.a" diff --git a/scripts/json2toml.py b/scripts/json2toml.py new file mode 100644 index 0000000..a6f5e9c --- /dev/null +++ b/scripts/json2toml.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Convert DragonX ui.json / ui-dark.json / ui-light.json to TOML format. + +Usage: + python3 scripts/json2toml.py res/themes/ui.json res/themes/ui.toml + python3 scripts/json2toml.py res/themes/ui-dark.json res/themes/ui-dark.toml + python3 scripts/json2toml.py res/themes/ui-light.json res/themes/ui-light.toml + python3 scripts/json2toml.py --all # converts all three +""" + +import json +import sys +import os +import re +from collections import OrderedDict + +# Keys that need quoting in TOML because they contain special chars +def needs_quoting(key): + # TOML bare keys: [A-Za-z0-9_-]+ + return not re.match(r'^[A-Za-z0-9_-]+$', key) + +def quote_key(key): + if needs_quoting(key): + return f'"{key}"' + return key + +def format_value(val): + """Format a Python value as a TOML value string.""" + if isinstance(val, bool): + return "true" if val else "false" + elif isinstance(val, int): + return str(val) + elif isinstance(val, float): + # Ensure floats always have a decimal point + s = repr(val) + if '.' not in s and 'e' not in s and 'E' not in s: + s += '.0' + return s + elif isinstance(val, str): + # Escape backslashes and quotes + escaped = val.replace('\\', '\\\\').replace('"', '\\"') + return f'"{escaped}"' + elif isinstance(val, list): + parts = [format_value(v) for v in val] + return f'[{", ".join(parts)}]' + else: + return repr(val) + +def is_simple_leaf(obj): + """Check if an object is a simple leaf that can be an inline table. + Simple leafs: {"size": X}, {"color": "..."}, {"height": X}, or small + objects with only primitive values and no nested objects.""" + if not isinstance(obj, dict): + return False + for v in obj.values(): + if isinstance(v, (dict, list)): + return False + # Keep objects with many keys as sections (threshold: 6 keys) + return len(obj) <= 6 + +def is_array_of_objects(val): + """Check if val is an array of objects (needs [[array.of.tables]]).""" + return isinstance(val, list) and all(isinstance(v, dict) for v in val) and len(val) > 0 + +def write_inline_table(obj): + """Write a dict as a TOML inline table.""" + parts = [] + for k, v in obj.items(): + parts.append(f'{quote_key(k)} = {format_value(v)}') + return '{ ' + ', '.join(parts) + ' }' + +def emit_toml(data, lines, prefix='', depth=0): + """Recursively emit TOML from a parsed JSON dict.""" + + # Separate keys into: scalars/arrays, simple-leaf objects, complex objects, array-of-tables + scalars = [] + inline_leaves = [] + complex_tables = [] + array_tables = [] + + for key, val in data.items(): + # Skip _comment keys (we'll handle them differently) + if key.startswith('_comment'): + continue + + if isinstance(val, dict): + if is_simple_leaf(val): + inline_leaves.append((key, val)) + else: + complex_tables.append((key, val)) + elif is_array_of_objects(val): + array_tables.append((key, val)) + else: + scalars.append((key, val)) + + # Emit scalars first + for key, val in scalars: + lines.append(f'{quote_key(key)} = {format_value(val)}') + + # Emit inline leaf objects (like { size = 42.0 }) + for key, val in inline_leaves: + lines.append(f'{quote_key(key)} = {write_inline_table(val)}') + + # Emit complex sub-tables with [section] headers + for key, val in complex_tables: + subprefix = f'{prefix}.{key}' if prefix else key + lines.append('') + lines.append(f'[{subprefix}]') + emit_toml(val, lines, subprefix, depth + 1) + + # Emit array-of-tables with [[section]] headers + for key, val in array_tables: + subprefix = f'{prefix}.{key}' if prefix else key + for item in val: + lines.append('') + lines.append(f'[[{subprefix}]]') + if isinstance(item, dict): + for ik, iv in item.items(): + if isinstance(iv, dict): + # Nested object inside array item — inline table + lines.append(f'{quote_key(ik)} = {write_inline_table(iv)}') + else: + lines.append(f'{quote_key(ik)} = {format_value(iv)}') + +def convert_file(input_path, output_path): + """Convert a JSON theme file to TOML.""" + with open(input_path) as f: + data = json.load(f, object_pairs_hook=OrderedDict) + + lines = [] + + # Add header comments (converted from _comment_* keys) + for key, val in data.items(): + if key.startswith('_comment') and isinstance(val, str): + if val: + lines.append(f'# {val}') + else: + lines.append('') + + if lines: + lines.append('') + + # Emit all non-comment content + emit_toml(data, lines) + + # Clean up extra blank lines + output = '\n'.join(lines).strip() + '\n' + # Collapse 3+ consecutive newlines to 2 + while '\n\n\n' in output: + output = output.replace('\n\n\n', '\n\n') + + with open(output_path, 'w') as f: + f.write(output) + + print(f'Converted: {input_path} -> {output_path}') + print(f' JSON: {os.path.getsize(input_path):,} bytes') + print(f' TOML: {os.path.getsize(output_path):,} bytes') + print(f' Reduction: {100 - 100*os.path.getsize(output_path)/os.path.getsize(input_path):.0f}%') + +def main(): + if len(sys.argv) == 2 and sys.argv[1] == '--all': + base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + themes = os.path.join(base, 'res', 'themes') + for name in ['ui', 'ui-dark', 'ui-light']: + inp = os.path.join(themes, f'{name}.json') + out = os.path.join(themes, f'{name}.toml') + if os.path.exists(inp): + convert_file(inp, out) + else: + print(f'Skipping (not found): {inp}') + elif len(sys.argv) == 3: + convert_file(sys.argv[1], sys.argv[2]) + else: + print(__doc__) + sys.exit(1) + +if __name__ == '__main__': + main() diff --git a/scripts/legacy/build-release.sh b/scripts/legacy/build-release.sh new file mode 100755 index 0000000..1d48dd5 --- /dev/null +++ b/scripts/legacy/build-release.sh @@ -0,0 +1,224 @@ +#!/bin/bash +# DragonX ImGui Wallet - Release Build Script +# Copyright 2024-2026 The Hush Developers +# Released under the GPLv3 + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_DIR="${SCRIPT_DIR}/build/linux" +VERSION="1.0.0" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +print_status() { + echo -e "${GREEN}[*]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[!]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +usage() { + echo "DragonX ImGui Wallet Build Script" + echo "" + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " -d, --debug Build debug version" + echo " -r, --release Build release version (default)" + echo " -c, --clean Clean build directory first" + echo " -j N Use N parallel jobs (default: auto)" + echo " -a, --appimage Create AppImage after build" + echo " -h, --help Show this help" + echo "" + echo "Examples:" + echo " $0 -r # Release build" + echo " $0 -c -r # Clean + release build" + echo " $0 -r -a # Release build + AppImage" + echo " $0 -d -j4 # Debug build with 4 threads" +} + +# Default options +BUILD_TYPE="Release" +CLEAN=false +JOBS=$(nproc 2>/dev/null || echo 4) +CREATE_APPIMAGE=false + +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + -d|--debug) + BUILD_TYPE="Debug" + shift + ;; + -r|--release) + BUILD_TYPE="Release" + shift + ;; + -c|--clean) + CLEAN=true + shift + ;; + -j) + JOBS="$2" + shift 2 + ;; + -a|--appimage) + CREATE_APPIMAGE=true + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + print_error "Unknown option: $1" + usage + exit 1 + ;; + esac +done + +print_status "DragonX ImGui Wallet v${VERSION} - Build Script" +print_status "Build type: ${BUILD_TYPE}" +print_status "Parallel jobs: ${JOBS}" + +# Clean if requested +if [ "$CLEAN" = true ]; then + print_status "Cleaning build directory..." + rm -rf "${BUILD_DIR}" +fi + +# Create build directory +mkdir -p "${BUILD_DIR}" +cd "${BUILD_DIR}" + +# Configure +print_status "Running CMake configuration..." +cmake .. \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DDRAGONX_USE_SYSTEM_SDL3=ON + +# Build +print_status "Building with ${JOBS} parallel jobs..." +cmake --build . -j "${JOBS}" + +# Check if build succeeded +if [ -f "bin/ObsidianDragon" ]; then + print_status "Build successful!" + + # Show binary info + BINARY_SIZE=$(du -h bin/ObsidianDragon | cut -f1) + print_status "Binary size: ${BINARY_SIZE}" + + # Strip in release mode + if [ "$BUILD_TYPE" = "Release" ]; then + print_status "Stripping debug symbols..." + strip bin/ObsidianDragon + STRIPPED_SIZE=$(du -h bin/ObsidianDragon | cut -f1) + print_status "Stripped size: ${STRIPPED_SIZE}" + fi + + # Bundle daemon files if available + DAEMON_BUNDLED=0 + + # Look for hush-arrakis-chain in common locations (the daemon launcher script) + LAUNCHER_PATHS=( + "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/hush-arrakis-chain" + "${SCRIPT_DIR}/../hush-arrakis-chain" + "${SCRIPT_DIR}/hush-arrakis-chain" + "$HOME/hush3/src/hush-arrakis-chain" + ) + + for lpath in "${LAUNCHER_PATHS[@]}"; do + if [ -f "$lpath" ]; then + print_status "Bundling hush-arrakis-chain from $lpath" + cp "$lpath" bin/hush-arrakis-chain + chmod +x bin/hush-arrakis-chain + DAEMON_BUNDLED=1 + break + fi + done + + # Also look for hushd (the actual daemon binary) + HUSHD_PATHS=( + "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/hushd" + "${SCRIPT_DIR}/../hushd" + "${SCRIPT_DIR}/hushd" + "$HOME/hush3/src/hushd" + ) + + for hpath in "${HUSHD_PATHS[@]}"; do + if [ -f "$hpath" ]; then + print_status "Bundling hushd from $hpath" + cp "$hpath" bin/hushd + chmod +x bin/hushd + break + fi + done + + # Also copy dragonxd script if available (alternative launcher) + DRAGONXD_PATHS=( + "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/dragonxd" + "${SCRIPT_DIR}/../dragonxd" + "${SCRIPT_DIR}/dragonxd" + "$HOME/hush3/src/dragonxd" + ) + + for dpath in "${DRAGONXD_PATHS[@]}"; do + if [ -f "$dpath" ]; then + print_status "Bundling dragonxd script from $dpath" + cp "$dpath" bin/dragonxd + chmod +x bin/dragonxd + break + fi + done + + # Look for asmap.dat + ASMAP_PATHS=( + "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/asmap.dat" + "${SCRIPT_DIR}/../asmap.dat" + "${SCRIPT_DIR}/asmap.dat" + "$HOME/hush3/asmap.dat" + "$HOME/hush3/contrib/asmap/asmap.dat" + ) + + for apath in "${ASMAP_PATHS[@]}"; do + if [ -f "$apath" ]; then + print_status "Bundling asmap.dat from $apath" + cp "$apath" bin/ + break + fi + done + + if [ $DAEMON_BUNDLED -eq 1 ]; then + print_status "Daemon bundled - ready for distribution!" + else + print_warning "dragonxd not found - place prebuilt-binaries/dragonxd-linux/ in project directory for bundling" + fi +else + print_error "Build failed - binary not found" + exit 1 +fi + +# Create AppImage if requested +if [ "$CREATE_APPIMAGE" = true ]; then + print_status "Creating AppImage..." + "${SCRIPT_DIR}/create-appimage.sh" || print_warning "AppImage creation failed" +fi + +print_status "" +print_status "Build complete!" +print_status "Binary: ${BUILD_DIR}/bin/ObsidianDragon" +print_status "" +print_status "To run: cd ${BUILD_DIR}/bin && ./ObsidianDragon" diff --git a/scripts/legacy/build-windows.bat b/scripts/legacy/build-windows.bat new file mode 100644 index 0000000..842dc6d --- /dev/null +++ b/scripts/legacy/build-windows.bat @@ -0,0 +1,60 @@ +@echo off +REM DragonX Wallet - Windows Build Script (Native MSVC/MinGW) +REM Run from Visual Studio Developer Command Prompt or MSYS2 MinGW64 + +setlocal enabledelayedexpansion + +echo DragonX Wallet - Windows Build +echo ============================== + +REM Check for CMake +where cmake >nul 2>nul +if %errorlevel% neq 0 ( + echo Error: CMake not found! Please install CMake and add to PATH. + exit /b 1 +) + +REM Create build directory +if not exist build-win mkdir build-win +cd build-win + +REM Detect compiler +where cl >nul 2>nul +if %errorlevel% equ 0 ( + echo Using MSVC compiler + set GENERATOR=-G "Visual Studio 17 2022" -A x64 +) else ( + where gcc >nul 2>nul + if %errorlevel% equ 0 ( + echo Using MinGW/GCC compiler + set GENERATOR=-G "MinGW Makefiles" + ) else ( + echo Error: No compiler found! Run from VS Developer Command Prompt or MSYS2. + exit /b 1 + ) +) + +echo. +echo Configuring with CMake... +cmake .. %GENERATOR% -DCMAKE_BUILD_TYPE=Release -DDRAGONX_USE_SYSTEM_SDL3=OFF + +if %errorlevel% neq 0 ( + echo CMake configuration failed! + exit /b 1 +) + +echo. +echo Building... +cmake --build . --config Release --parallel + +if %errorlevel% neq 0 ( + echo Build failed! + exit /b 1 +) + +echo. +echo Build successful! +echo Output: build-win\bin\Release\ObsidianDragon.exe (MSVC) +echo or: build-win\bin\ObsidianDragon.exe (MinGW) + +endlocal diff --git a/scripts/legacy/build-windows.sh b/scripts/legacy/build-windows.sh new file mode 100755 index 0000000..766db48 --- /dev/null +++ b/scripts/legacy/build-windows.sh @@ -0,0 +1,477 @@ +#!/bin/bash +# DragonX Wallet - Windows Cross-Compile Build Script +# Requires: mingw-w64 toolchain with POSIX threads +# +# On Ubuntu/Debian: +# sudo apt install mingw-w64 cmake +# sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix +# sudo update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix +# +# On Arch Linux: +# sudo pacman -S mingw-w64-gcc cmake + +set -e + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BUILD_DIR="$SCRIPT_DIR/build/windows" + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +echo -e "${GREEN}DragonX Wallet - Windows Cross-Compile Build${NC}" +echo "==============================================" + +# Check for mingw toolchain (prefer POSIX variant) +MINGW_GCC="" +MINGW_GXX="" + +if command -v x86_64-w64-mingw32-gcc-posix &> /dev/null; then + MINGW_GCC="x86_64-w64-mingw32-gcc-posix" + MINGW_GXX="x86_64-w64-mingw32-g++-posix" + echo -e "${GREEN}Using POSIX thread model (recommended)${NC}" +elif command -v x86_64-w64-mingw32-gcc &> /dev/null; then + # Check if it's the posix variant + if x86_64-w64-mingw32-gcc -v 2>&1 | grep -q "posix"; then + MINGW_GCC="x86_64-w64-mingw32-gcc" + MINGW_GXX="x86_64-w64-mingw32-g++" + echo -e "${GREEN}Using POSIX thread model${NC}" + else + echo -e "${YELLOW}Warning: Using win32 thread model - may have threading issues${NC}" + echo "Run these commands to switch to POSIX threads:" + echo " sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix" + echo " sudo update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix" + MINGW_GCC="x86_64-w64-mingw32-gcc" + MINGW_GXX="x86_64-w64-mingw32-g++" + fi +else + echo -e "${RED}Error: mingw-w64 not found!${NC}" + echo "Install with:" + echo " Ubuntu/Debian: sudo apt install mingw-w64" + echo " Arch Linux: sudo pacman -S mingw-w64-gcc" + exit 1 +fi + +echo "C compiler: $MINGW_GCC" +echo "C++ compiler: $MINGW_GXX" + +# Clean and create build directory +if [ "$1" == "clean" ]; then + echo -e "${YELLOW}Cleaning build directory...${NC}" + rm -rf "$BUILD_DIR" +fi + +mkdir -p "$BUILD_DIR" +cd "$BUILD_DIR" + +# Create CMake toolchain file for MinGW +cat > mingw-toolchain.cmake << EOF +# MinGW-w64 Cross-Compilation Toolchain +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +# Compilers (using POSIX threads) +set(CMAKE_C_COMPILER $MINGW_GCC) +set(CMAKE_CXX_COMPILER $MINGW_GXX) +set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres) + +# Target environment +set(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32) + +# Search for programs in the build host directories +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + +# Search for libraries and headers in the target directories +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + +# Static linking - no DLLs needed +set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc -static-libstdc++ -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,--no-whole-archive") +set(CMAKE_CXX_FLAGS "\${CMAKE_CXX_FLAGS} -static") +set(CMAKE_C_FLAGS "\${CMAKE_C_FLAGS} -static") + +# Prefer static libraries +set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") +set(BUILD_SHARED_LIBS OFF) +EOF + +# ----------------------------------------------------------------------------- +# Generate embedded resources (Sapling params, asmap.dat) +# ----------------------------------------------------------------------------- +echo -e "${GREEN}Generating embedded resources...${NC}" + +GENERATED_DIR="$BUILD_DIR/generated" +mkdir -p "$GENERATED_DIR" + +# Find resource files +SAPLING_SPEND="" +SAPLING_OUTPUT="" +ASMAP_DAT="" + +# Look for Sapling params +PARAMS_PATHS=( + "$HOME/.zcash-params" + "$HOME/.hush-params" + "$SCRIPT_DIR/../SilentDragonX" + "$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + "$SCRIPT_DIR" +) + +for ppath in "${PARAMS_PATHS[@]}"; do + if [ -f "$ppath/sapling-spend.params" ] && [ -f "$ppath/sapling-output.params" ]; then + SAPLING_SPEND="$ppath/sapling-spend.params" + SAPLING_OUTPUT="$ppath/sapling-output.params" + echo " Found Sapling params in $ppath" + break + fi +done + +# Look for asmap.dat +ASMAP_PATHS=( + "$HOME/hush3/asmap.dat" + "$HOME/hush3/contrib/asmap/asmap.dat" + "$SCRIPT_DIR/../asmap.dat" + "$SCRIPT_DIR/asmap.dat" + "$SCRIPT_DIR/../SilentDragonX/asmap.dat" +) + +for apath in "${ASMAP_PATHS[@]}"; do + if [ -f "$apath" ]; then + ASMAP_DAT="$apath" + echo " Found asmap.dat at $apath" + break + fi +done + +# --------------------------------------------------------------------------- +# Generate embedded_data.h using INCBIN (assembler .incbin directive). +# +# Instead of converting binaries to giant hex arrays (530MB+ C source), +# we copy the raw files into generated/res/ and generate a small header +# that uses INCBIN() macros. The assembler streams the bytes directly +# into the object file, using near-zero compile-time RAM. +# --------------------------------------------------------------------------- +if [ -n "$SAPLING_SPEND" ] && [ -n "$SAPLING_OUTPUT" ]; then + echo -e "${GREEN}Embedding resources via INCBIN (assembler .incbin)...${NC}" + + # Stage raw binaries into generated/res/ so .incbin can find them + EMBED_RES_DIR="$GENERATED_DIR/res" + mkdir -p "$EMBED_RES_DIR" + + cp -f "$SAPLING_SPEND" "$EMBED_RES_DIR/sapling-spend.params" + echo " Staged sapling-spend.params ($(du -h "$SAPLING_SPEND" | cut -f1))" + cp -f "$SAPLING_OUTPUT" "$EMBED_RES_DIR/sapling-output.params" + echo " Staged sapling-output.params ($(du -h "$SAPLING_OUTPUT" | cut -f1))" + + if [ -n "$ASMAP_DAT" ]; then + cp -f "$ASMAP_DAT" "$EMBED_RES_DIR/asmap.dat" + echo " Staged asmap.dat ($(du -h "$ASMAP_DAT" | cut -f1))" + HAS_ASMAP=1 + else + HAS_ASMAP=0 + fi + + # Start writing the header — use absolute paths for .incbin + cat > "$GENERATED_DIR/embedded_data.h" << HEADER_START +// Auto-generated embedded resource data — INCBIN edition +// DO NOT EDIT — generated by build-windows.sh +// +// Uses assembler .incbin directive via incbin.h so the compiler never +// has to parse hundreds of millions of hex literals. Compile-time RAM +// drops from 12 GB+ to well under 1 GB. +#pragma once +#include +#include +#include "incbin.h" + +// ---- Sapling params (always present when this header exists) ---- +INCBIN(sapling_spend_params, "$EMBED_RES_DIR/sapling-spend.params"); +INCBIN(sapling_output_params, "$EMBED_RES_DIR/sapling-output.params"); + +HEADER_START + + # asmap.dat + if [ "$HAS_ASMAP" = "1" ]; then + echo "INCBIN(asmap_dat, \"$EMBED_RES_DIR/asmap.dat\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_asmap_dat_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_asmap_dat_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + echo "" >> "$GENERATED_DIR/embedded_data.h" + + # Daemon binaries + DAEMON_DIR="$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + if [ -d "$DAEMON_DIR" ] && [ -f "$DAEMON_DIR/hushd.exe" ]; then + echo -e "${GREEN}Embedding daemon binaries via INCBIN...${NC}" + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "#define HAS_EMBEDDED_DAEMON 1" >> "$GENERATED_DIR/embedded_data.h" + echo "" >> "$GENERATED_DIR/embedded_data.h" + + cp -f "$DAEMON_DIR/hushd.exe" "$EMBED_RES_DIR/hushd.exe" + echo " Staged hushd.exe ($(du -h "$DAEMON_DIR/hushd.exe" | cut -f1))" + echo "INCBIN(hushd_exe, \"$EMBED_RES_DIR/hushd.exe\");" >> "$GENERATED_DIR/embedded_data.h" + + if [ -f "$DAEMON_DIR/hush-cli.exe" ]; then + cp -f "$DAEMON_DIR/hush-cli.exe" "$EMBED_RES_DIR/hush-cli.exe" + echo " Staged hush-cli.exe ($(du -h "$DAEMON_DIR/hush-cli.exe" | cut -f1))" + echo "INCBIN(hush_cli_exe, \"$EMBED_RES_DIR/hush-cli.exe\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_hush_cli_exe_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_hush_cli_exe_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + echo "" >> "$GENERATED_DIR/embedded_data.h" + + if [ -f "$DAEMON_DIR/dragonxd.bat" ]; then + cp -f "$DAEMON_DIR/dragonxd.bat" "$EMBED_RES_DIR/dragonxd.bat" + echo " Staged dragonxd.bat" + echo "INCBIN(dragonxd_bat, \"$EMBED_RES_DIR/dragonxd.bat\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_dragonxd_bat_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_dragonxd_bat_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + echo "" >> "$GENERATED_DIR/embedded_data.h" + + if [ -f "$DAEMON_DIR/hush-tx.exe" ]; then + cp -f "$DAEMON_DIR/hush-tx.exe" "$EMBED_RES_DIR/hush-tx.exe" + echo " Staged hush-tx.exe ($(du -h "$DAEMON_DIR/hush-tx.exe" | cut -f1))" + echo "INCBIN(hush_tx_exe, \"$EMBED_RES_DIR/hush-tx.exe\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_hush_tx_exe_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_hush_tx_exe_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + echo "" >> "$GENERATED_DIR/embedded_data.h" + + if [ -f "$DAEMON_DIR/dragonx-cli.bat" ]; then + cp -f "$DAEMON_DIR/dragonx-cli.bat" "$EMBED_RES_DIR/dragonx-cli.bat" + echo " Staged dragonx-cli.bat" + echo "INCBIN(dragonx_cli_bat, \"$EMBED_RES_DIR/dragonx-cli.bat\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_dragonx_cli_bat_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_dragonx_cli_bat_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + + else + echo -e "${YELLOW}Note: Daemon binaries not found in prebuilt-binaries/dragonxd-win/ — wallet only${NC}" + fi + + # ── xmrig binary (from prebuilt-binaries/xmrig-hac/) ──────────────── + XMRIG_DIR="$SCRIPT_DIR/prebuilt-binaries/xmrig-hac" + if [ -f "$XMRIG_DIR/xmrig.exe" ]; then + cp -f "$XMRIG_DIR/xmrig.exe" "$EMBED_RES_DIR/xmrig.exe" + echo " Staged xmrig.exe ($(du -h "$XMRIG_DIR/xmrig.exe" | cut -f1))" + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "#define HAS_EMBEDDED_XMRIG 1" >> "$GENERATED_DIR/embedded_data.h" + echo "INCBIN(xmrig_exe, \"$EMBED_RES_DIR/xmrig.exe\");" >> "$GENERATED_DIR/embedded_data.h" + else + echo 'extern "C" { static const uint8_t* g_xmrig_exe_data = nullptr; }' >> "$GENERATED_DIR/embedded_data.h" + echo 'static const unsigned int g_xmrig_exe_size = 0;' >> "$GENERATED_DIR/embedded_data.h" + fi + + # ---- Theme images (backgrounds + logos) ---- + # Embed ALL images from res/img/backgrounds/ subdirectories and res/img/logos/ + # so the Windows single-file distribution can display theme backgrounds and logos + # without needing res/ on disk. + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "// ---- Embedded theme images ----" >> "$GENERATED_DIR/embedded_data.h" + IMAGE_TABLE_ENTRIES="" + IMAGE_COUNT=0 + for IMG_DIR in "$SCRIPT_DIR/res/img/backgrounds/texture" "$SCRIPT_DIR/res/img/backgrounds/gradient" "$SCRIPT_DIR/res/img/logos"; do + if [ -d "$IMG_DIR" ]; then + for IMG_FILE in "$IMG_DIR"/*.png; do + [ -f "$IMG_FILE" ] || continue + IMG_BASENAME=$(basename "$IMG_FILE") + IMG_SYMBOL=$(echo "$IMG_BASENAME" | sed 's/[^a-zA-Z0-9]/_/g') + echo " Staged image: $IMG_BASENAME ($(du -h "$IMG_FILE" | cut -f1))" + cp -f "$IMG_FILE" "$EMBED_RES_DIR/$IMG_BASENAME" + echo "INCBIN(img_${IMG_SYMBOL}, \"$EMBED_RES_DIR/$IMG_BASENAME\");" >> "$GENERATED_DIR/embedded_data.h" + IMAGE_TABLE_ENTRIES="${IMAGE_TABLE_ENTRIES} { g_img_${IMG_SYMBOL}_data, g_img_${IMG_SYMBOL}_size, \"${IMG_BASENAME}\" },\n" + IMAGE_COUNT=$((IMAGE_COUNT + 1)) + done + fi + done + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "#define HAS_EMBEDDED_IMAGES 1" >> "$GENERATED_DIR/embedded_data.h" + echo "#define EMBEDDED_IMAGE_COUNT $IMAGE_COUNT" >> "$GENERATED_DIR/embedded_data.h" + # Backward compat defines (referenced by s_resources[] guards) + echo "#define HAS_EMBEDDED_GRADIENT 1" >> "$GENERATED_DIR/embedded_data.h" + echo "#define HAS_EMBEDDED_LOGO 1" >> "$GENERATED_DIR/embedded_data.h" + # Backward compat aliases for the old symbol names + echo "static const uint8_t* g_dark_gradient_png_data = g_img_dark_gradient_png_data;" >> "$GENERATED_DIR/embedded_data.h" + echo "static const unsigned int g_dark_gradient_png_size = g_img_dark_gradient_png_size;" >> "$GENERATED_DIR/embedded_data.h" + echo "static const uint8_t* g_logo_ObsidianDragon_dark_png_data = g_img_logo_ObsidianDragon_dark_png_data;" >> "$GENERATED_DIR/embedded_data.h" + echo "static const unsigned int g_logo_ObsidianDragon_dark_png_size = g_img_logo_ObsidianDragon_dark_png_size;" >> "$GENERATED_DIR/embedded_data.h" + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "struct EmbeddedImageEntry { const uint8_t* data; unsigned int size; const char* filename; };" >> "$GENERATED_DIR/embedded_data.h" + echo "static const EmbeddedImageEntry s_embedded_images[] = {" >> "$GENERATED_DIR/embedded_data.h" + echo -e "$IMAGE_TABLE_ENTRIES" >> "$GENERATED_DIR/embedded_data.h" + echo " { nullptr, 0, nullptr }" >> "$GENERATED_DIR/embedded_data.h" + echo "};" >> "$GENERATED_DIR/embedded_data.h" + + # Embed bundled overlay themes (dark.toml, light.toml, obsidian.toml, etc.) + # These are extracted to the config dir on first run so the theme selector can find them. + THEMES_DIR="$SCRIPT_DIR/res/themes" + THEME_COUNT=0 + THEME_TABLE_ENTRIES="" + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "// ---- Bundled overlay themes ----" >> "$GENERATED_DIR/embedded_data.h" + for THEME_FILE in "$THEMES_DIR"/*.toml; do + THEME_BASENAME=$(basename "$THEME_FILE") + # Skip ui.toml — it's embedded separately via cmake + if [ "$THEME_BASENAME" = "ui.toml" ]; then + continue + fi + THEME_SYMBOL=$(echo "$THEME_BASENAME" | sed 's/[^a-zA-Z0-9]/_/g') + cp -f "$THEME_FILE" "$EMBED_RES_DIR/$THEME_BASENAME" + echo " Staged $THEME_BASENAME" + echo "INCBIN(theme_${THEME_SYMBOL}, \"$EMBED_RES_DIR/$THEME_BASENAME\");" >> "$GENERATED_DIR/embedded_data.h" + THEME_TABLE_ENTRIES="${THEME_TABLE_ENTRIES} { g_theme_${THEME_SYMBOL}_data, g_theme_${THEME_SYMBOL}_size, \"${THEME_BASENAME}\" },\n" + THEME_COUNT=$((THEME_COUNT + 1)) + done + echo "" >> "$GENERATED_DIR/embedded_data.h" + echo "#define EMBEDDED_THEME_COUNT $THEME_COUNT" >> "$GENERATED_DIR/embedded_data.h" + echo "" >> "$GENERATED_DIR/embedded_data.h" + # Generate the theme table struct + echo "// Auto-generated theme table" >> "$GENERATED_DIR/embedded_data.h" + echo "struct EmbeddedThemeEntry { const uint8_t* data; unsigned int size; const char* filename; };" >> "$GENERATED_DIR/embedded_data.h" + echo "static const EmbeddedThemeEntry s_embedded_themes[] = {" >> "$GENERATED_DIR/embedded_data.h" + echo -e "$THEME_TABLE_ENTRIES" >> "$GENERATED_DIR/embedded_data.h" + echo " { nullptr, 0, nullptr }" >> "$GENERATED_DIR/embedded_data.h" + echo "};" >> "$GENERATED_DIR/embedded_data.h" + echo "" >> "$GENERATED_DIR/embedded_data.h" + + echo -e "${GREEN}Embedded resources header generated (INCBIN — near-zero compile RAM)${NC}" +else + echo -e "${YELLOW}Warning: Sapling params not found — building without embedded resources${NC}" + echo "The wallet will require external param files." +fi + +# Ensure libsodium is available for Windows cross-compile +if [ ! -f "$SCRIPT_DIR/libs/libsodium-win/lib/libsodium.a" ]; then + echo -e "${YELLOW}libsodium for Windows not found, fetching...${NC}" + "$SCRIPT_DIR/scripts/fetch-libsodium.sh" --win +fi + +echo -e "${GREEN}Configuring with CMake...${NC}" +cmake .. \ + -DCMAKE_TOOLCHAIN_FILE=mingw-toolchain.cmake \ + -DCMAKE_BUILD_TYPE=Release \ + -DDRAGONX_USE_SYSTEM_SDL3=OFF + +echo -e "${GREEN}Building...${NC}" +cmake --build . -j$(nproc) + +# Check if build succeeded +if [ -f "bin/ObsidianDragon.exe" ]; then + echo "" + echo -e "${GREEN}Build successful!${NC}" + echo "Output: $BUILD_DIR/bin/ObsidianDragon.exe" + + # Show file size and check if statically linked + ls -lh bin/ObsidianDragon.exe + echo "" + echo -e "${GREEN}Statically linked - no DLLs required!${NC}" + + # Bundle daemon files if available from dragonxd-win directory + DAEMON_DIR="$SCRIPT_DIR/prebuilt-binaries/dragonxd-win" + DAEMON_BUNDLED=0 + + if [ -d "$DAEMON_DIR" ]; then + echo -e "${GREEN}Found daemon directory: $DAEMON_DIR${NC}" + + # Copy all daemon files + if [ -f "$DAEMON_DIR/dragonxd.bat" ]; then + cp "$DAEMON_DIR/dragonxd.bat" bin/ + echo " - dragonxd.bat" + DAEMON_BUNDLED=1 + fi + if [ -f "$DAEMON_DIR/dragonx-cli.bat" ]; then + cp "$DAEMON_DIR/dragonx-cli.bat" bin/ + echo " - dragonx-cli.bat" + fi + if [ -f "$DAEMON_DIR/hushd.exe" ]; then + cp "$DAEMON_DIR/hushd.exe" bin/ + echo " - hushd.exe ($(du -h "$DAEMON_DIR/hushd.exe" | cut -f1))" + fi + if [ -f "$DAEMON_DIR/hush-cli.exe" ]; then + cp "$DAEMON_DIR/hush-cli.exe" bin/ + echo " - hush-cli.exe" + fi + if [ -f "$DAEMON_DIR/hush-tx.exe" ]; then + cp "$DAEMON_DIR/hush-tx.exe" bin/ + echo " - hush-tx.exe" + fi + else + echo -e "${YELLOW}Daemon directory not found: $DAEMON_DIR${NC}" + echo " Place prebuilt-binaries/dragonxd-win/ in the project directory to bundle the daemon." + fi + + # Create distribution package + echo "" + echo -e "${GREEN}Creating distribution package...${NC}" + cd bin + DIST_NAME="DragonX-Wallet-Windows-x64" + rm -rf "$DIST_NAME" "$DIST_NAME.zip" + mkdir -p "$DIST_NAME" + cp ObsidianDragon.exe "$DIST_NAME/" + # Copy all daemon files + [ -f dragonxd.bat ] && cp dragonxd.bat "$DIST_NAME/" + [ -f dragonx-cli.bat ] && cp dragonx-cli.bat "$DIST_NAME/" + [ -f hushd.exe ] && cp hushd.exe "$DIST_NAME/" + [ -f hush-cli.exe ] && cp hush-cli.exe "$DIST_NAME/" + [ -f hush-tx.exe ] && cp hush-tx.exe "$DIST_NAME/" + + # Create README + cat > "$DIST_NAME/README.txt" << 'READMEEOF' +DragonX Wallet - Windows Edition +================================ + +SINGLE-FILE DISTRIBUTION +======================== +This wallet is a true single-file executable with all resources embedded. +Just run ObsidianDragon.exe - no additional files needed! + +On first run, the wallet will automatically extract: +- Sapling parameters to %APPDATA%\ZcashParams\ +- asmap.dat to %APPDATA%\Hush\DRAGONX\ + +The wallet will look for the daemon config at: + %APPDATA%\Hush\DRAGONX\DRAGONX.conf + +This will be auto-created on first run if the daemon is present. + +For support: https://git.hush.is/hush/ObsidianDragon +READMEEOF + + if command -v zip &> /dev/null; then + zip -r "$DIST_NAME.zip" "$DIST_NAME" + # Copy zip + single-file exe to release/windows/ + local OUT_DIR="$SCRIPT_DIR/release/windows" + mkdir -p "$OUT_DIR" + cp "$DIST_NAME.zip" "$OUT_DIR/" + cp ObsidianDragon.exe "$OUT_DIR/" + echo -e "${GREEN}Distribution package: $OUT_DIR/$DIST_NAME.zip${NC}" + echo -e "${GREEN}Single-file exe: $OUT_DIR/ObsidianDragon.exe${NC}" + ls -lh "$OUT_DIR/" + else + echo "Install 'zip' to create distribution archive" + fi + + cd .. + echo "" + echo -e "${GREEN}============================================${NC}" + echo -e "${GREEN}SINGLE-FILE DISTRIBUTION READY!${NC}" + echo -e "${GREEN}============================================${NC}" + echo "" + echo "The executable contains embedded:" + echo " - Sapling spend params (~48MB)" + echo " - Sapling output params (~3MB)" + echo " - asmap.dat (~1MB)" + echo "" + echo "Just copy ObsidianDragon.exe to Windows and run it!" + echo "Resources will be extracted automatically on first launch." +else + echo -e "${RED}Build failed!${NC}" + exit 1 +fi diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 0000000..1e3013d --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,414 @@ +#!/usr/bin/env bash +# ── scripts/setup.sh ──────────────────────────────────────────────────────── +# DragonX Wallet — Development Environment Setup +# Copyright 2024-2026 The Hush Developers +# Released under the GPLv3 +# +# Detects your OS/distro, installs build prerequisites, fetches libraries, +# and validates the environment so you can build immediately with: +# +# ./build.sh # dev build +# ./build.sh --win-release # Windows cross-compile +# ./build.sh --linux-release # Linux release + AppImage +# +# Usage: +# ./scripts/setup.sh # Interactive — install everything needed +# ./scripts/setup.sh --check # Just report what's missing, don't install +# ./scripts/setup.sh --all # Install dev + all cross-compile targets +# ./scripts/setup.sh --win # Also install Windows cross-compile deps +# ./scripts/setup.sh --mac # Also install macOS cross-compile deps +# ./scripts/setup.sh --sapling # Also download Sapling params (~51 MB) +# ───────────────────────────────────────────────────────────────────────────── +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" + +# ── Colours ────────────────────────────────────────────────────────────────── +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +CYAN='\033[0;36m' +BOLD='\033[1m' +NC='\033[0m' + +ok() { echo -e " ${GREEN}✓${NC} $1"; } +miss() { echo -e " ${RED}✗${NC} $1"; } +skip() { echo -e " ${YELLOW}—${NC} $1"; } +info() { echo -e "${GREEN}[*]${NC} $1"; } +warn() { echo -e "${YELLOW}[!]${NC} $1"; } +err() { echo -e "${RED}[ERROR]${NC} $1"; } +header(){ echo -e "\n${CYAN}── $1 ──${NC}"; } + +# ── Parse args ─────────────────────────────────────────────────────────────── +CHECK_ONLY=false +SETUP_WIN=false +SETUP_MAC=false +SETUP_SAPLING=false + +while [[ $# -gt 0 ]]; do + case $1 in + --check) CHECK_ONLY=true; shift ;; + --win) SETUP_WIN=true; shift ;; + --mac) SETUP_MAC=true; shift ;; + --sapling) SETUP_SAPLING=true; shift ;; + --all) SETUP_WIN=true; SETUP_MAC=true; SETUP_SAPLING=true; shift ;; + -h|--help) + sed -n '2,/^# ─\{10\}/{ /^# ─\{10\}/d; s/^# \?//p; }' "$0" + exit 0 + ;; + *) err "Unknown option: $1"; exit 1 ;; + esac +done + +# ── Detect OS / distro ────────────────────────────────────────────────────── +detect_os() { + OS="$(uname -s)" + DISTRO="unknown" + PKG="" + + case "$OS" in + Linux) + if [[ -f /etc/os-release ]]; then + . /etc/os-release + case "${ID:-}" in + ubuntu|debian|linuxmint|pop|elementary|zorin|neon) + DISTRO="debian"; PKG="apt" ;; + fedora|rhel|centos|rocky|alma) + DISTRO="fedora"; PKG="dnf" ;; + arch|manjaro|endeavouros|garuda) + DISTRO="arch"; PKG="pacman" ;; + opensuse*|suse*) + DISTRO="suse"; PKG="zypper" ;; + void) + DISTRO="void"; PKG="xbps" ;; + gentoo) + DISTRO="gentoo"; PKG="emerge" ;; + *) + # Fallback: check for package managers + command -v apt &>/dev/null && { DISTRO="debian"; PKG="apt"; } || + command -v dnf &>/dev/null && { DISTRO="fedora"; PKG="dnf"; } || + command -v pacman &>/dev/null && { DISTRO="arch"; PKG="pacman"; } + ;; + esac + fi + ;; + Darwin) + DISTRO="macos" + command -v brew &>/dev/null && PKG="brew" + ;; + *) + err "Unsupported OS: $OS" + exit 1 + ;; + esac +} + +# ── Package lists per distro ──────────────────────────────────────────────── +# Core: minimum to do a dev build (Linux native) +pkgs_core_debian="build-essential cmake git pkg-config + libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev + libxinerama-dev libxi-dev libxkbcommon-dev libwayland-dev + libsodium-dev libcurl4-openssl-dev" + +pkgs_core_fedora="gcc gcc-c++ cmake git pkg-config + mesa-libGL-devel libX11-devel libXcursor-devel libXrandr-devel + libXinerama-devel libXi-devel libxkbcommon-devel wayland-devel + libsodium-devel libcurl-devel" + +pkgs_core_arch="base-devel cmake git pkg-config + mesa libx11 libxcursor libxrandr libxinerama libxi + libxkbcommon wayland libsodium curl" + +pkgs_core_macos="cmake" + +# Windows cross-compile (from Linux) +pkgs_win_debian="mingw-w64 zip" +pkgs_win_fedora="mingw64-gcc mingw64-gcc-c++ zip" +pkgs_win_arch="mingw-w64-gcc zip" + +# macOS cross-compile helpers (osxcross is separate) +pkgs_mac_debian="genisoimage icnsutils" +pkgs_mac_fedora="genisoimage" +pkgs_mac_arch="cdrtools" + +# ── Helpers ────────────────────────────────────────────────────────────────── +has_cmd() { command -v "$1" &>/dev/null; } + +# Install packages for the detected distro +install_pkgs() { + local pkgs="$1" + local desc="$2" + + if $CHECK_ONLY; then + warn "Would install ($desc): $pkgs" + return + fi + + info "Installing $desc packages..." + case "$PKG" in + apt) sudo apt-get update -qq && sudo apt-get install -y $pkgs ;; + dnf) sudo dnf install -y $pkgs ;; + pacman) sudo pacman -S --needed --noconfirm $pkgs ;; + zypper) sudo zypper install -y $pkgs ;; + brew) brew install $pkgs ;; + *) err "No supported package manager found for $DISTRO" + echo "Please install manually: $pkgs" + return 1 ;; + esac +} + +# Select the right package list variable +get_pkgs() { + local category="$1" # core, win, mac + local var="pkgs_${category}_${DISTRO}" + echo "${!var:-}" +} + +# ── Check individual tools ────────────────────────────────────────────────── +MISSING=0 + +check_tool() { + local cmd="$1" + local label="${2:-$1}" + if has_cmd "$cmd"; then + ok "$label" + else + miss "$label (not found: $cmd)" + MISSING=$((MISSING + 1)) + fi +} + +check_file() { + local path="$1" + local label="$2" + if [[ -f "$path" ]]; then + ok "$label" + else + miss "$label ($path)" + MISSING=$((MISSING + 1)) + fi +} + +check_dir() { + local path="$1" + local label="$2" + if [[ -d "$path" ]]; then + ok "$label" + else + miss "$label ($path)" + MISSING=$((MISSING + 1)) + fi +} + +# ═════════════════════════════════════════════════════════════════════════════ +# MAIN +# ═════════════════════════════════════════════════════════════════════════════ +echo -e "${BOLD}DragonX Wallet — Development Setup${NC}" +echo "═══════════════════════════════════" + +detect_os +info "Detected: $OS / $DISTRO (package manager: ${PKG:-none})" + +# ── 1. Core build dependencies ────────────────────────────────────────────── +header "Core Build Dependencies" + +core_pkgs="$(get_pkgs core)" +if [[ -z "$core_pkgs" ]]; then + warn "No package list for $DISTRO — check README for manual instructions" +else + # Check if key tools are already present + NEED_CORE=false + has_cmd cmake && has_cmd g++ && has_cmd pkg-config || NEED_CORE=true + + if $NEED_CORE; then + install_pkgs "$core_pkgs" "core build" + else + ok "Core tools already installed (cmake, g++, pkg-config)" + fi +fi + +check_tool cmake "cmake" +check_tool g++ "g++ (C++ compiler)" +check_tool git "git" +check_tool make "make" + +# ── 2. libsodium ──────────────────────────────────────────────────────────── +header "libsodium" + +SODIUM_OK=false +# Check system libsodium +if pkg-config --exists libsodium 2>/dev/null; then + ok "libsodium (system, $(pkg-config --modversion libsodium))" + SODIUM_OK=true +elif [[ -f "$PROJECT_DIR/libs/libsodium/lib/libsodium.a" ]]; then + ok "libsodium (local build)" + SODIUM_OK=true +else + miss "libsodium not found" + if ! $CHECK_ONLY; then + info "Building libsodium from source..." + "$SCRIPT_DIR/fetch-libsodium.sh" && SODIUM_OK=true + fi +fi + +# ── 3. Windows cross-compile (optional) ───────────────────────────────────── +header "Windows Cross-Compile" + +if $SETUP_WIN; then + win_pkgs="$(get_pkgs win)" + if [[ -n "$win_pkgs" ]]; then + install_pkgs "$win_pkgs" "Windows cross-compile" + fi + + # Set posix thread model if available + if has_cmd update-alternatives && [[ "$PKG" == "apt" ]]; then + if ! $CHECK_ONLY; then + sudo update-alternatives --set x86_64-w64-mingw32-gcc \ + /usr/bin/x86_64-w64-mingw32-gcc-posix 2>/dev/null || true + sudo update-alternatives --set x86_64-w64-mingw32-g++ \ + /usr/bin/x86_64-w64-mingw32-g++-posix 2>/dev/null || true + fi + fi + + # Fetch libsodium for Windows + if [[ ! -f "$PROJECT_DIR/libs/libsodium-win/lib/libsodium.a" ]]; then + if ! $CHECK_ONLY; then + info "Building libsodium for Windows target..." + "$SCRIPT_DIR/fetch-libsodium.sh" --win + else + miss "libsodium-win (not built yet)" + fi + else + ok "libsodium-win" + fi +fi + +if has_cmd x86_64-w64-mingw32-g++-posix || has_cmd x86_64-w64-mingw32-g++; then + ok "mingw-w64 ($(x86_64-w64-mingw32-g++-posix --version 2>/dev/null | head -1 || x86_64-w64-mingw32-g++ --version 2>/dev/null | head -1))" +else + if $SETUP_WIN; then + miss "mingw-w64" + else + skip "mingw-w64 (use --win to install)" + fi +fi + +# ── 4. macOS cross-compile (optional) ─────────────────────────────────────── +header "macOS Cross-Compile" + +if $SETUP_MAC; then + mac_pkgs="$(get_pkgs mac)" + if [[ -n "$mac_pkgs" ]]; then + install_pkgs "$mac_pkgs" "macOS cross-compile helpers" + fi + + # Fetch libsodium for macOS + if [[ ! -f "$PROJECT_DIR/libs/libsodium-mac/lib/libsodium.a" ]]; then + if ! $CHECK_ONLY; then + info "Building libsodium for macOS target..." + "$SCRIPT_DIR/fetch-libsodium.sh" --mac + else + miss "libsodium-mac (not built yet)" + fi + else + ok "libsodium-mac" + fi +fi + +if [[ -d "$PROJECT_DIR/external/osxcross/target" ]] || [[ -d "${OSXCROSS:-}/target" ]]; then + ok "osxcross" +else + if $SETUP_MAC; then + miss "osxcross (must be set up manually — see README)" + else + skip "osxcross (use --mac to set up macOS deps)" + fi +fi + +# ── 5. Sapling parameters ─────────────────────────────────────────────────── +header "Sapling Parameters" + +SAPLING_DIR="" +for d in "$HOME/.zcash-params" "$HOME/.hush-params"; do + if [[ -f "$d/sapling-spend.params" && -f "$d/sapling-output.params" ]]; then + SAPLING_DIR="$d" + break + fi +done + +# Also check project-local locations +if [[ -z "$SAPLING_DIR" ]]; then + for d in "$PROJECT_DIR/prebuilt-binaries/dragonxd-linux" "$PROJECT_DIR/prebuilt-binaries/dragonxd-win"; do + if [[ -f "$d/sapling-spend.params" && -f "$d/sapling-output.params" ]]; then + SAPLING_DIR="$d" + break + fi + done +fi + +if [[ -n "$SAPLING_DIR" ]]; then + ok "sapling-spend.params ($(du -h "$SAPLING_DIR/sapling-spend.params" | cut -f1))" + ok "sapling-output.params ($(du -h "$SAPLING_DIR/sapling-output.params" | cut -f1))" +elif $SETUP_SAPLING; then + if ! $CHECK_ONLY; then + info "Downloading Sapling parameters (~51 MB)..." + PARAMS_DIR="$HOME/.zcash-params" + mkdir -p "$PARAMS_DIR" + + SPEND_URL="https://z.cash/downloads/sapling-spend.params" + OUTPUT_URL="https://z.cash/downloads/sapling-output.params" + + curl -fSL -o "$PARAMS_DIR/sapling-spend.params" "$SPEND_URL" && \ + ok "Downloaded sapling-spend.params" + curl -fSL -o "$PARAMS_DIR/sapling-output.params" "$OUTPUT_URL" && \ + ok "Downloaded sapling-output.params" + fi +else + skip "Sapling params not found (use --sapling to download, or they'll be extracted at runtime from embedded builds)" +fi + +# ── 6. Binary directories ─────────────────────────────────────────────────── +header "Binary Directories" + +for platform in dragonxd-linux dragonxd-win dragonxd-mac xmrig; do + dir="$PROJECT_DIR/prebuilt-binaries/$platform" + if [[ -d "$dir" ]]; then + # Count actual files (not .gitkeep) + count=$(find "$dir" -maxdepth 1 -type f ! -name '.gitkeep' | wc -l) + if [[ $count -gt 0 ]]; then + ok "prebuilt-binaries/$platform/ ($count files)" + else + skip "prebuilt-binaries/$platform/ (empty — place binaries here)" + fi + else + if ! $CHECK_ONLY; then + mkdir -p "$dir" + touch "$dir/.gitkeep" + ok "Created prebuilt-binaries/$platform/" + else + miss "prebuilt-binaries/$platform/" + fi + fi +done + +# ── Summary ────────────────────────────────────────────────────────────────── +echo "" +echo "═══════════════════════════════════════════" +if [[ $MISSING -eq 0 ]]; then + echo -e "${GREEN}${BOLD} Setup complete — ready to build!${NC}" + echo "" + echo " Quick start:" + echo " ./build.sh # Dev build" + echo " ./build.sh --linux-release # Linux release + AppImage" + echo " ./build.sh --win-release # Windows cross-compile" +else + echo -e "${YELLOW}${BOLD} $MISSING item(s) still need attention${NC}" + if $CHECK_ONLY; then + echo "" + echo " Run without --check to install automatically:" + echo " ./scripts/setup.sh" + echo " ./scripts/setup.sh --all # Include cross-compile + Sapling" + fi +fi +echo "═══════════════════════════════════════════" diff --git a/src/app.cpp b/src/app.cpp new file mode 100644 index 0000000..df574c6 --- /dev/null +++ b/src/app.cpp @@ -0,0 +1,2357 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "app.h" +#include "config/version.h" +#include "rpc/rpc_client.h" +#include "rpc/rpc_worker.h" +#include "rpc/connection.h" +#include "config/settings.h" +#include "daemon/embedded_daemon.h" +#include "daemon/xmrig_manager.h" +#include "ui/windows/main_window.h" +#include "ui/windows/balance_tab.h" +#include "ui/windows/send_tab.h" +#include "ui/windows/receive_tab.h" +#include "ui/windows/transactions_tab.h" +#include "ui/windows/mining_tab.h" +#include "ui/windows/peers_tab.h" +#include "ui/windows/market_tab.h" +#include "ui/windows/settings_window.h" +#include "ui/windows/about_dialog.h" +#include "embedded/IconsMaterialDesign.h" +#include "ui/windows/key_export_dialog.h" +#include "ui/windows/transaction_details_dialog.h" +#include "ui/windows/qr_popup_dialog.h" +#include "ui/windows/validate_address_dialog.h" +#include "ui/windows/address_book_dialog.h" +#include "ui/windows/shield_dialog.h" +#include "ui/windows/request_payment_dialog.h" +#include "ui/windows/block_info_dialog.h" +#include "ui/windows/export_all_keys_dialog.h" +#include "ui/windows/export_transactions_dialog.h" +#include "ui/windows/console_tab.h" +#include "ui/pages/settings_page.h" +#include "ui/theme.h" +#include "ui/sidebar.h" +#include "ui/effects/imgui_acrylic.h" +#include "ui/effects/theme_effects.h" +#include "ui/effects/low_spec.h" +#include "ui/material/color_theme.h" +#include "ui/material/type.h" +#include "ui/material/typography.h" +#include "ui/material/draw_helpers.h" +#include "ui/notifications.h" +#include "util/i18n.h" +#include "util/platform.h" +#include "util/payment_uri.h" +#include "util/texture_loader.h" +#include "util/bootstrap.h" +#include "util/secure_vault.h" +#include "resources/embedded_resources.h" +#include "ui/schema/ui_schema.h" +#include "ui/schema/skin_manager.h" +#include "util/perf_log.h" + +// Embedded ui.toml (generated at build time) — fallback when file not on disk +#if __has_include("ui_toml_embedded.h") +#include "ui_toml_embedded.h" +#define HAS_EMBEDDED_UI_TOML 1 +#else +#define HAS_EMBEDDED_UI_TOML 0 +#endif + +#include "imgui.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include "util/logger.h" +#endif + +namespace dragonx { + +using json = nlohmann::json; + +App::App() = default; +App::~App() = default; + +bool App::init() +{ + DEBUG_LOGF("Initializing ObsidianDragon...\n"); + + // Extract embedded resources (Sapling params, asmap.dat) on first run + if (resources::hasEmbeddedResources() && resources::needsParamsExtraction()) { + DEBUG_LOGF("First run - extracting bundled resources...\n"); + resources::extractEmbeddedResources(); + } + + // Initialize settings + settings_ = std::make_unique(); + if (!settings_->load()) { + DEBUG_LOGF("Warning: Could not load settings, using defaults\n"); + } + + // Ensure ObsidianDragon config directory and template files exist + util::Platform::ensureObsidianDragonSetup(); + + // Initialize PIN vault + vault_ = std::make_unique(); + + // Theme is now applied via SkinManager below after UISchema loads. + // The old SetThemeById() C++ fallback is no longer needed at startup + // because SkinManager.setActiveSkin() loads colors from ui.toml directly. + + // Initialize unified UI schema (loads TOML, drives all layout values) + { + std::string schemaPath = util::Platform::getExecutableDirectory() + "/res/themes/ui.toml"; + bool loaded = false; + if (std::filesystem::exists(schemaPath)) { + loaded = ui::schema::UISchema::instance().loadFromFile(schemaPath); + } + // Fallback: load from build-time embedded data when file not on disk + // (e.g., single-file Windows distribution without res/ directory) + if (!loaded) { +#if HAS_EMBEDDED_UI_TOML + std::string embedded(reinterpret_cast(embedded::ui_toml_data), + embedded::ui_toml_size); + ui::schema::UISchema::instance().loadFromString(embedded, "embedded"); +#else + DEBUG_LOGF("Warning: ui.toml not found at %s and no embedded fallback\n", schemaPath.c_str()); +#endif + } + + // Initialize SkinManager and activate saved skin + auto& skinMgr = ui::schema::SkinManager::instance(); + skinMgr.refresh(); + + // Register image reload callback for skin changes + skinMgr.setImageReloadCallback([this](const std::string& bgPath, const std::string& logoPath) { + reloadThemeImages(bgPath, logoPath); + }); + + std::string skinId = settings_->getSkinId(); + if (skinId.empty()) skinId = "dragonx"; + + // Apply gradient background preference before activating the skin + // so the initial image resolution uses the correct mode. + if (settings_->getGradientBackground()) { + skinMgr.setGradientMode(true); + } + + skinMgr.setActiveSkin(skinId); + } + + // Apply saved language + std::string lang = settings_->getLanguage(); + if (!lang.empty()) { + util::I18n::instance().loadLanguage(lang); + } + + // Initialize RPC client + rpc_ = std::make_unique(); + + // Initialize background RPC worker thread + worker_ = std::make_unique(); + worker_->start(); + + // Forward error/warning notifications to the console tab + // Use ConsoleTab colors so the Errors filter works correctly + ui::Notifications::instance().setConsoleCallback( + [this](const std::string& msg, bool is_error) { + ImU32 color = is_error ? ui::ConsoleTab::COLOR_ERROR : ui::material::Warning(); + console_tab_.addLine(msg, color); + }); + + // Check for first-run wizard — also re-run if blockchain data is missing + // even when wizard was previously completed (e.g. data dir was deleted) + if (isFirstRun()) { + wizard_phase_ = WizardPhase::Appearance; + DEBUG_LOGF("First run detected — starting wizard\n"); + // Don't start daemon yet — wait for wizard completion + } else { + // Normal startup — connect to daemon + tryConnect(); + } + + DEBUG_LOGF("Initialization complete\n"); + return true; +} + +void App::update() +{ + PERF_SCOPE("Update.Total"); + ImGuiIO& io = ImGui::GetIO(); + + // Track user interaction for auto-lock + if (io.MouseDelta.x != 0 || io.MouseDelta.y != 0 || + io.MouseClicked[0] || io.MouseClicked[1] || + io.InputQueueCharacters.Size > 0) { + last_interaction_ = std::chrono::steady_clock::now(); + } + + // Drain completed RPC results back onto the main thread + if (worker_) { + worker_->drainResults(); + } + + // Auto-lock check (only when connected + encrypted + unlocked) + if (state_.connected && state_.isUnlocked()) { + checkAutoLock(); + } + + // P8: Dedup rebuildAddressList — only rebuild once per frame + if (address_list_dirty_) { + address_list_dirty_ = false; + state_.rebuildAddressList(); + } + + // Hot-reload unified UI schema + { + PERF_SCOPE("Update.SchemaHotReload"); + ui::schema::UISchema::instance().pollForChanges(); + ui::schema::UISchema::instance().applyIfDirty(); + } + + // Refresh balance layout config after schema reload + ui::RefreshBalanceLayoutConfig(); + + // If font sizes changed in the JSON, rebuild the font atlas + if (ui::schema::UISchema::instance().consumeFontsChanged()) { + auto& typo = ui::material::Typography::instance(); + typo.reload(io, typo.getDpiScale()); + DEBUG_LOGF("App: Font atlas rebuilt after hot-reload\n"); + } + + // Update timers + refresh_timer_ += io.DeltaTime; + price_timer_ += io.DeltaTime; + fast_refresh_timer_ += io.DeltaTime; + + // Fast refresh (mining stats + daemon memory) every second + // Skip when wallet is locked — no need to poll, and queued tasks + // would delay the PIN unlock worker task. + if (fast_refresh_timer_ >= FAST_REFRESH_INTERVAL) { + fast_refresh_timer_ = 0.0f; + if (state_.connected && !state_.isLocked()) { + refreshMiningInfo(); + } + + // Poll xmrig stats every ~2 seconds (use a simple toggle) + static bool xmrig_poll_tick = false; + xmrig_poll_tick = !xmrig_poll_tick; + if (xmrig_poll_tick && xmrig_manager_ && xmrig_manager_->isRunning()) { + xmrig_manager_->pollStats(); + auto& ps = state_.pool_mining; + auto& xs = xmrig_manager_->getStats(); + ps.xmrig_running = true; + ps.hashrate_10s = xs.hashrate_10s; + ps.hashrate_60s = xs.hashrate_60s; + ps.hashrate_15m = xs.hashrate_15m; + ps.accepted = xs.accepted; + ps.rejected = xs.rejected; + ps.uptime_sec = xs.uptime_sec; + ps.pool_diff = xs.pool_diff; + ps.pool_url = xs.pool_url; + ps.algo = xs.algo; + ps.connected = xs.connected; + // Get memory directly from OS (more reliable than API) + double memMB = xmrig_manager_->getMemoryUsageMB(); + ps.memory_used = static_cast(memMB * 1024.0 * 1024.0); + ps.threads_active = xs.threads_active; + ps.log_lines = xmrig_manager_->getRecentLines(30); + + // Record hashrate sample for the chart + ps.hashrate_history.push_back(ps.hashrate_10s); + if (ps.hashrate_history.size() > PoolMiningState::MAX_HISTORY) { + ps.hashrate_history.erase(ps.hashrate_history.begin()); + } + } else if (xmrig_manager_ && !xmrig_manager_->isRunning()) { + state_.pool_mining.xmrig_running = false; + } + } + + // Regular refresh every 5 seconds + // Skip when wallet is locked — same reason as above. + if (refresh_timer_ >= REFRESH_INTERVAL) { + refresh_timer_ = 0.0f; + if (state_.connected && !state_.isLocked()) { + refreshData(); + } else if (!connection_in_progress_ && + wizard_phase_ == WizardPhase::None) { + tryConnect(); + } + } + + // Price refresh every 60 seconds + if (price_timer_ >= PRICE_INTERVAL) { + price_timer_ = 0.0f; + if (settings_->getFetchPrices()) { + refreshPrice(); + } + } + + // Keyboard shortcut: Ctrl+, to open Settings page + if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_Comma)) { + current_page_ = ui::NavPage::Settings; + } + + // Keyboard shortcut: Ctrl+Left/Right to cycle themes + if (io.KeyCtrl && !io.WantTextInput) { + bool prevTheme = ImGui::IsKeyPressed(ImGuiKey_LeftArrow); + bool nextTheme = ImGui::IsKeyPressed(ImGuiKey_RightArrow); + if (prevTheme || nextTheme) { + auto& skinMgr = ui::schema::SkinManager::instance(); + const auto& skins = skinMgr.available(); + if (!skins.empty()) { + int cur = 0; + for (int i = 0; i < (int)skins.size(); i++) { + if (skins[i].id == skinMgr.activeSkinId()) { cur = i; break; } + } + if (prevTheme) + cur = (cur - 1 + (int)skins.size()) % (int)skins.size(); + else + cur = (cur + 1) % (int)skins.size(); + skinMgr.setActiveSkin(skins[cur].id); + if (settings_) { + settings_->setSkinId(skins[cur].id); + settings_->save(); + } + ui::Notifications::instance().info("Theme: " + skins[cur].name); + } + } + } + + // Keyboard shortcut: F5 to refresh + if (ImGui::IsKeyPressed(ImGuiKey_F5)) { + refreshNow(); + } + + // Keyboard shortcut: Ctrl+Shift+Down to toggle low-spec mode + // (checked BEFORE Ctrl+Down so it doesn't also trigger theme effects) + if (io.KeyCtrl && io.KeyShift && !io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { + bool newLow = !ui::effects::isLowSpecMode(); + ui::effects::setLowSpecMode(newLow); + if (newLow) { + // Disable all heavy effects at runtime (don't overwrite saved prefs) + ui::effects::ImGuiAcrylic::ApplyBlurAmount(0.0f); + ui::effects::ImGuiAcrylic::SetUIOpacity(1.0f); + ui::effects::ThemeEffects::instance().setEnabled(false); + ui::effects::ThemeEffects::instance().setReducedTransparency(true); + if (settings_) { + settings_->setLowSpecMode(true); + settings_->setWindowOpacity(1.0f); + settings_->save(); + } + } else { + // Restore effect settings from saved preferences + if (settings_) { + settings_->setLowSpecMode(false); + settings_->save(); + ui::effects::ImGuiAcrylic::ApplyBlurAmount(settings_->getBlurMultiplier()); + ui::effects::ImGuiAcrylic::SetUIOpacity(settings_->getUIOpacity()); + ui::effects::ThemeEffects::instance().setEnabled(settings_->getThemeEffectsEnabled()); + ui::effects::ThemeEffects::instance().setReducedTransparency(!settings_->getThemeEffectsEnabled()); + } + } + ui::Notifications::instance().info(newLow ? "Low-spec mode enabled" : "Low-spec mode disabled"); + } + + // Keyboard shortcut: Ctrl+Down to toggle theme effects (Shift excluded) + else if (io.KeyCtrl && !io.KeyShift && !io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { + bool newState = !ui::effects::ThemeEffects::instance().isEnabled(); + ui::effects::ThemeEffects::instance().setEnabled(newState); + ui::effects::ThemeEffects::instance().setReducedTransparency(!newState); + if (settings_) { + settings_->setThemeEffectsEnabled(newState); + settings_->save(); + } + ui::Notifications::instance().info(newState ? "Theme effects enabled" : "Theme effects disabled"); + } + + // Keyboard shortcut: Ctrl+Up to toggle simple gradient background + if (io.KeyCtrl && !io.KeyShift && !io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { + bool newGrad = !settings_->getGradientBackground(); + settings_->setGradientBackground(newGrad); + ui::schema::SkinManager::instance().setGradientMode(newGrad); + settings_->save(); + ui::Notifications::instance().info(newGrad ? "Simple background enabled" : "Simple background disabled"); + } + + // Debug: Ctrl+Shift+W to re-show first-run wizard (set to false to disable) + constexpr bool ENABLE_WIZARD_HOTKEY = false; + if constexpr (ENABLE_WIZARD_HOTKEY) { + if (io.KeyCtrl && io.KeyShift && ImGui::IsKeyPressed(ImGuiKey_W)) { + wizard_phase_ = WizardPhase::Appearance; + DEBUG_LOGF("[Debug] Wizard re-opened via Ctrl+Shift+W\n"); + } + } +} + +void App::render() +{ + // First-run wizard gate — blocks all normal UI + if (wizard_phase_ != WizardPhase::None && wizard_phase_ != WizardPhase::Done) { + renderFirstRunWizard(); + return; + } + + // Process deferred encryption from wizard (runs in background) + processDeferredEncryption(); + + // Main content area - use full window (no menu bar) + ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->WorkPos); + ImGui::SetNextWindowSize(viewport->WorkSize); + + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoScrollWithMouse; + + // When OS backdrop is active, use NoBackground so DWM Mica/Acrylic shows through + if (ui::material::IsBackdropActive()) { + window_flags |= ImGuiWindowFlags_NoBackground; + } + + // Main window padding from ui.toml schema (DPI-scaled) + const float hdp = ui::Layout::dpiScale(); + const auto& mwWin = ui::schema::UI().window("components.main-window"); + const float mainPadX = (mwWin.padding[0] > 0.0f ? mwWin.padding[0] : 16.0f) * hdp; + const float mainPadTop = (mwWin.padding[1] > 0.0f ? mwWin.padding[1] : 42.0f) * hdp; + const float mainPadBot = ui::schema::UI().drawElement("components.main-window", "padding-bottom").size * hdp; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(mainPadX, mainPadTop)); + ImGui::Begin("MainContent", nullptr, window_flags); + ImGui::PopStyleVar(); // WindowPadding — applied to the window, safe to pop now + + // ---- Top-left branding: logo + "ObsidianDragon" title ---- + // Drawn via DrawList in the top padding area — zero layout impact. + { + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 winPos = ImGui::GetWindowPos(); + const auto& S = ui::schema::UI(); + auto hdrElem = S.drawElement("components.main-window", "header-title"); + auto hdrLabel = S.label("components.main-window", "header-title"); + + // Helper to read extraFloats with fallback (DPI-scaled) + auto hdrF = [&](const char* key, float fb) -> float { + auto it = hdrElem.extraFloats.find(key); + return ((it != hdrElem.extraFloats.end()) ? it->second : fb) * hdp; + }; + + const float brandPadX = hdrF("pad-x", mainPadX / hdp); + const float brandPadY = hdrF("pad-y", 8.0f); + const float logoGap = hdrF("logo-gap", 8.0f); + const float hdrOpacity = (hdrElem.opacity >= 0.0f) ? hdrElem.opacity : 0.7f; + + // Logo + float logoSize = mainPadTop - brandPadY * 2.0f; // fit within header + if (logoSize < 16.0f * hdp) logoSize = 16.0f * hdp; + float logoX = winPos.x + brandPadX; + float logoY = winPos.y + brandPadY; + if (logo_tex_ != 0) { + float aspect = (logo_h_ > 0) ? (float)logo_w_ / (float)logo_h_ : 1.0f; + float logoW = logoSize * aspect; + dl->AddImage(logo_tex_, + ImVec2(logoX, logoY), + ImVec2(logoX + logoW, logoY + logoSize)); + logoX += logoW + logoGap; + } + + // Title text — font and size from schema (DPI-scaled) + ImFont* titleFont = S.resolveFont(hdrLabel.font); + if (!titleFont) titleFont = ui::material::Type().subtitle1(); + // TOML size is in logical pixels; scale by DPI. Font's LegacySize + // is already DPI-scaled from the atlas reload. + float titleFontSize = hdrElem.size >= 0.0f + ? hdrElem.size * hdp + : titleFont->LegacySize; + if (titleFont) { + float textY = winPos.y + (mainPadTop - titleFontSize) * 0.5f; + ImU32 textCol = ui::material::OnSurface(); + // Apply header text opacity + int a = (int)((float)((textCol >> 24) & 0xFF) * hdrOpacity); + textCol = (textCol & 0x00FFFFFF) | ((ImU32)a << 24); + dl->AddText(titleFont, titleFontSize, + ImVec2(logoX, textY), + textCol, "ObsidianDragon"); + } + } + + // Sidebar + Content layout + const float dp = ui::Layout::dpiScale(); + auto sbde = [dp](const char* key, float fb) { + float v = ui::schema::UI().drawElement("components.sidebar", key).size; + return (v >= 0 ? v : fb) * dp; + }; + float statusBarH = ui::schema::UI().window("components.status-bar").height; + if (statusBarH <= 0.0f) statusBarH = 24.0f; // safety fallback + // Content area padding from ui.toml schema + const auto& caWin = ui::schema::UI().window("components.content-area"); + const float caMarginTop = ui::schema::UI().drawElement("components.content-area", "margin-top").size; + const float caMarginBot = ui::schema::UI().drawElement("components.content-area", "margin-bottom").size; + const float contentH = ImGui::GetContentRegionAvail().y - statusBarH - ImGui::GetStyle().ItemSpacing.y + - caMarginTop - caMarginBot; + + // Auto-collapse when viewport is narrow (skip if user manually toggled) + float vpW = viewport->WorkSize.x; + float collapseHysteresis = ui::schema::UI().drawElement("components.main-window", "collapse-hysteresis").sizeOr(60.0f) * dp; + const float autoCollapseThreshold = sbde("auto-collapse-threshold", 800.0f); + if (!sidebar_user_toggled_) { + if (vpW < autoCollapseThreshold && !sidebar_collapsed_) { + sidebar_collapsed_ = true; + } else if (vpW >= autoCollapseThreshold + collapseHysteresis && sidebar_collapsed_) { + sidebar_collapsed_ = false; + } + } else { + // Reset manual override when viewport crosses the threshold significantly, + // so auto-collapse resumes after the user resizes the window + if ((!sidebar_collapsed_ && vpW >= autoCollapseThreshold + collapseHysteresis) || + (sidebar_collapsed_ && vpW < autoCollapseThreshold)) { + sidebar_user_toggled_ = false; + } + } + + // Animate sidebar width + float targetW = sidebar_collapsed_ ? sbde("collapsed-width", 64.0f) : sbde("width", 160.0f); + // On DPI change, snap instantly instead of animating from stale value + bool dpiChanged = (prev_dpi_scale_ > 0.0f && std::abs(dp - prev_dpi_scale_) > 0.01f); + prev_dpi_scale_ = dp; + if (sidebar_width_anim_ <= 0.0f || dpiChanged) sidebar_width_anim_ = targetW; + { + float diff = targetW - sidebar_width_anim_; + float dt = ImGui::GetIO().DeltaTime; + float t = dt * sbde("collapse-anim-speed", 10.0f); + if (t > 1.0f) t = 1.0f; + sidebar_width_anim_ += diff * t; + } + const float sidebarW = sidebar_width_anim_; + + // Build sidebar status for badges + footer + ui::SidebarStatus sbStatus; + sbStatus.peerCount = static_cast(state_.peers.size()); + sbStatus.miningActive = state_.mining.generate; + + // Load logo texture lazily on first frame (or after theme change) + // Also reload when dark↔light mode changes so the correct variant shows + { + bool wantDark = ui::material::IsDarkTheme(); + if (!logo_loaded_ || (wantDark != logo_is_dark_variant_)) { + logo_loaded_ = true; + logo_is_dark_variant_ = wantDark; + logo_tex_ = 0; logo_w_ = 0; logo_h_ = 0; + + // 1) Check for theme-override logo from active skin + const auto* activeSkin = ui::schema::SkinManager::instance().findById( + ui::schema::SkinManager::instance().activeSkinId()); + std::string logoPath; + if (activeSkin && !activeSkin->logoPath.empty()) { + logoPath = activeSkin->logoPath; + } else { + // 2) Read icon filename from ui.toml (dark/light variant) + auto iconElem = ui::schema::UI().drawElement("components.main-window", "header-icon"); + const char* iconKey = wantDark ? "icon-dark" : "icon-light"; + auto it = iconElem.extraColors.find(iconKey); + std::string iconFile; + if (it != iconElem.extraColors.end() && !it->second.empty()) { + iconFile = it->second; + } else { + // Fallback filenames + iconFile = wantDark ? "logos/logo_ObsidianDragon_dark.png" : "logos/logo_ObsidianDragon_light.png"; + } + logoPath = util::getExecutableDirectory() + "/res/img/" + iconFile; + } + if (util::LoadTextureFromFile(logoPath.c_str(), &logo_tex_, &logo_w_, &logo_h_)) { + DEBUG_LOGF("Loaded header logo from %s (%dx%d)\n", logoPath.c_str(), logo_w_, logo_h_); + } else { + // Try embedded data fallback — use actual filename from path + // so light/dark variants resolve correctly on Windows single-file + std::string embeddedName = std::filesystem::path(logoPath).filename().string(); + const auto* logoRes = resources::getEmbeddedResource(embeddedName); + if (!logoRes || !logoRes->data || logoRes->size == 0) { + // Final fallback: try the default dark logo constant + logoRes = resources::getEmbeddedResource(resources::RESOURCE_LOGO); + } + if (logoRes && logoRes->data && logoRes->size > 0) { + if (util::LoadTextureFromMemory(logoRes->data, logoRes->size, &logo_tex_, &logo_w_, &logo_h_)) { + DEBUG_LOGF("Loaded header logo from embedded: %s (%dx%d)\n", embeddedName.c_str(), logo_w_, logo_h_); + } else { + DEBUG_LOGF("Note: Failed to decode embedded logo (text-only header)\n"); + } + } else { + DEBUG_LOGF("Note: Header logo not found at %s (text-only header)\n", logoPath.c_str()); + } + } + } + } + + // Load coin logo texture lazily (DragonX currency icon for balance tab) + if (!coin_logo_loaded_) { + coin_logo_loaded_ = true; + coin_logo_tex_ = 0; coin_logo_w_ = 0; coin_logo_h_ = 0; + + // Read coin icon filename from ui.toml + auto coinElem = ui::schema::UI().drawElement("components.main-window", "coin-icon"); + auto cit = coinElem.extraColors.find("icon"); + std::string coinFile = (cit != coinElem.extraColors.end() && !cit->second.empty()) + ? cit->second : "logos/logo_dragonx_128.png"; + std::string coinPath = util::getExecutableDirectory() + "/res/img/" + coinFile; + if (util::LoadTextureFromFile(coinPath.c_str(), &coin_logo_tex_, &coin_logo_w_, &coin_logo_h_)) { + DEBUG_LOGF("Loaded coin logo from %s (%dx%d)\n", coinPath.c_str(), coin_logo_w_, coin_logo_h_); + } else { + // Try embedded resource fallback (Windows single-file distribution) + std::string coinBasename = std::filesystem::path(coinFile).filename().string(); + const auto* coinRes = resources::getEmbeddedResource(coinBasename); + if (coinRes && coinRes->data && coinRes->size > 0) { + if (util::LoadTextureFromMemory(coinRes->data, coinRes->size, &coin_logo_tex_, &coin_logo_w_, &coin_logo_h_)) { + DEBUG_LOGF("Loaded coin logo from embedded: %s (%dx%d)\n", coinBasename.c_str(), coin_logo_w_, coin_logo_h_); + } else { + DEBUG_LOGF("Note: Failed to decode embedded coin logo\n"); + } + } else { + DEBUG_LOGF("Note: Coin logo not found at %s\n", coinPath.c_str()); + } + } + } + + if (logo_tex_ != 0) { + sbStatus.logoTexID = logo_tex_; + sbStatus.logoW = logo_w_; + sbStatus.logoH = logo_h_; + } + if (gradient_tex_ != 0) { + sbStatus.gradientTexID = gradient_tex_; + } + // Count unconfirmed transactions + { + int unconf = 0; + for (const auto& tx : state_.transactions) { + if (!tx.isConfirmed()) ++unconf; + } + sbStatus.unconfirmedTxCount = unconf; + } + + // Sidebar margins from ui.toml schema (DPI-scaled like all sidebar values) + const float sbMarginTop = sbde("margin-top", 0.0f); + const float sbMarginBottom = sbde("margin-bottom", 0.0f); + const float sbMinHeight = sbde("min-height", 360.0f); + + // Ensure sidebar is tall enough to fit all buttons — shrink margins if needed + float sidebarH = contentH - sbMarginTop - sbMarginBottom; + float effectiveMarginTop = sbMarginTop; + if (sidebarH < sbMinHeight) { + float available = contentH - sbMinHeight; + if (available > 0.0f) { + float ratio = available / (sbMarginTop + sbMarginBottom); + effectiveMarginTop = sbMarginTop * ratio; + } else { + effectiveMarginTop = 0.0f; + } + sidebarH = std::max(contentH - effectiveMarginTop, sbMinHeight); + } + + // Sidebar navigation + // Save cursor Y before applying sidebar margin so the content area + // (placed via SameLine) starts at the original row position, not the + // margin-shifted one. + float preSidebarCursorY = ImGui::GetCursorPosY(); + if (effectiveMarginTop > 0.0f) + ImGui::SetCursorPosY(preSidebarCursorY + effectiveMarginTop); + bool prevCollapsed = sidebar_collapsed_; + { + PERF_SCOPE("Render.Sidebar"); + ui::RenderSidebar(current_page_, sidebarW, sidebarH, sbStatus, sidebar_collapsed_); + } + if (sbStatus.exitClicked) { + requestQuit(); + } + if (sidebar_collapsed_ != prevCollapsed) { + sidebar_user_toggled_ = true; // user clicked chevron or pressed [ + } + + ImGui::SameLine(); + // Restore cursor Y so content area is not shifted by sidebar margin + ImGui::SetCursorPosY(preSidebarCursorY); + + // Page transition: detect change, ramp alpha + if (current_page_ != prev_page_) { + page_alpha_ = ui::effects::isLowSpecMode() ? 1.0f : 0.0f; + prev_page_ = current_page_; + } + if (page_alpha_ < 1.0f) { + float dt = ImGui::GetIO().DeltaTime; + float pageFadeSpeed = ui::schema::UI().drawElement("components.main-window", "page-fade-speed").sizeOr(8.0f); + page_alpha_ += dt * pageFadeSpeed; + if (page_alpha_ > 1.0f) page_alpha_ = 1.0f; + } + + // Content area — fills remaining width, tabs handle their own scrolling + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + caMarginTop); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, + ImGui::GetStyle().Alpha * page_alpha_); + ImGuiWindowFlags contentFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + if (ui::material::IsBackdropActive()) + contentFlags |= ImGuiWindowFlags_NoBackground; + float caPadX = caWin.padding[0] > 0.0f ? caWin.padding[0] : ImGui::GetStyle().WindowPadding.x; + float caPadY = caWin.padding[1] > 0.0f ? caWin.padding[1] : ImGui::GetStyle().WindowPadding.y; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(caPadX, caPadY)); + + // Capture content area screen position for edge fade mask + ImVec2 caScreenPos = ImGui::GetCursorScreenPos(); + + ImGui::BeginChild("##ContentArea", ImVec2(0, contentH), false, contentFlags); + + // Capture vertex start for edge fade mask + ImDrawList* caDL = ImGui::GetWindowDrawList(); + int caVtxStart = caDL->VtxBuffer.Size; + + // Also capture ForegroundDrawList vertex start — DrawGlassPanel draws + // theme effects (rainbow border, edge trace, shimmer, specular glare) + // on the ForegroundDrawList, and those must also be edge-faded. + ImDrawList* fgDL = ImGui::GetForegroundDrawList(); + int fgVtxStart = fgDL->VtxBuffer.Size; + + // --------------------------------------------------------------- + // Loading overlay — show only while daemon is not yet connected. + // Once connected, all tabs render normally; individual tabs show + // inline sync-progress indicators when the chain is still syncing. + // Pages that remain accessible even without a connection: + // Console, Peers, Settings + // --------------------------------------------------------------- + bool pageNeedsDaemon = (current_page_ != ui::NavPage::Console && + current_page_ != ui::NavPage::Peers && + current_page_ != ui::NavPage::Settings); + bool daemonReady = state_.connected; // don't gate on sync state + + if (state_.isLocked()) { + // Lock screen — covers tab content just like the loading overlay + renderLockScreen(); + } else if (pageNeedsDaemon && (!daemonReady || (state_.connected && !state_.encryption_state_known))) { + // Reset lock screen focus flag so it auto-focuses next time + lock_screen_was_visible_ = false; + // Show loading overlay instead of tab content + renderLoadingOverlay(contentH); + } else { + lock_screen_was_visible_ = false; + + { + PERF_SCOPE("Render.ActiveTab"); + switch (current_page_) { + case ui::NavPage::Overview: + ui::RenderBalanceTab(this); + break; + case ui::NavPage::Send: + ui::RenderSendTab(this); + break; + case ui::NavPage::Receive: + ui::RenderReceiveTab(this); + break; + case ui::NavPage::History: + ui::RenderTransactionsTab(this); + break; + case ui::NavPage::Mining: + ui::RenderMiningTab(this); + break; + case ui::NavPage::Peers: + ui::RenderPeersTab(this); + break; + case ui::NavPage::Market: + ui::RenderMarketTab(this); + break; + case ui::NavPage::Console: + console_tab_.render(embedded_daemon_.get(), rpc_.get(), worker_.get(), xmrig_manager_.get()); + break; + case ui::NavPage::Settings: + ui::RenderSettingsPage(this); + break; + default: + break; + } + } // PERF_SCOPE + + } // end loading gate + + // Snapshot ForegroundDrawList vertex count BEFORE viewport-wide effects + // so the edge fade only applies to per-panel theme effects, not embers/overlay. + int fgVtxEnd = fgDL->VtxBuffer.Size; + + // Viewport-wide ambient theme effects (e.g. ember particles for fire themes) + { + PERF_SCOPE("Render.ThemeEffects"); + auto& fx = ui::effects::ThemeEffects::instance(); + ImDrawList* fgDl = ImGui::GetForegroundDrawList(); + + if (fx.hasEmberRise()) { + fx.drawViewportEmbers(fgDl); + } + + // Sandstorm particles (wind-driven sand for desert themes) + if (fx.hasSandstorm()) { + fx.drawSandstorm(fgDl); + } + + // Shader-like post-processing overlay (color wash + vignette) + if (fx.hasViewportOverlay()) { + fx.drawViewportOverlay(fgDl); + } + } + + // Apply edge fade mask to content area — soft transparency at top/bottom edges + // so content doesn't appear sharply clipped at the content area boundary. + { + PERF_SCOPE("Render.EdgeFade"); + float caTopEdge = caScreenPos.y; + float caBottomEdge = caScreenPos.y + contentH; + // Cache the schema lookup — value only changes on theme reload + static uint32_t s_fadeGen = 0; + static float s_fadeZone = 0.0f; + uint32_t curGen = ui::schema::UI().generation(); + if (curGen != s_fadeGen) { + s_fadeGen = curGen; + s_fadeZone = ui::schema::UI().drawElement("components.content-area", "edge-fade-zone").size; + } + float fadeZone = s_fadeZone * ui::Layout::dpiScale(); + // fadeZone <= 0 disables the effect entirely + if (fadeZone > 0.0f) { + // Pre-compute safe zone — vertices with y fully inside don't need any work + float safeTop = caTopEdge + fadeZone; + float safeBot = caBottomEdge - fadeZone; + + // Lambda to fade a range of vertices in a given draw list + auto fadeVerts = [&](ImDrawList* dl, int vtxStart, int vtxEnd) { + for (int vi = vtxStart; vi < vtxEnd; vi++) { + ImDrawVert& v = dl->VtxBuffer[vi]; + // Skip vertices in the safe zone (the common case) + if (v.pos.y >= safeTop && v.pos.y <= safeBot) + continue; + + float alpha = 1.0f; + + // Top fade + float dTop = v.pos.y - caTopEdge; + if (dTop < fadeZone) + alpha = std::min(alpha, std::max(0.0f, dTop / fadeZone)); + + // Bottom fade + float dBot = caBottomEdge - v.pos.y; + if (dBot < fadeZone) + alpha = std::min(alpha, std::max(0.0f, dBot / fadeZone)); + + if (alpha < 1.0f) { + int a = (v.col >> IM_COL32_A_SHIFT) & 0xFF; + a = static_cast(a * alpha); + v.col = (v.col & ~IM_COL32_A_MASK) | (static_cast(a) << IM_COL32_A_SHIFT); + } + } + }; + + // Fade content area window draw list (fills, text, borders) + fadeVerts(caDL, caVtxStart, caDL->VtxBuffer.Size); + + // Fade ForegroundDrawList panel effects (rainbow border, edge trace, + // shimmer, specular glare) — but NOT viewport-wide effects (embers, + // overlay) which were added after fgVtxEnd. + fadeVerts(fgDL, fgVtxStart, fgVtxEnd); + } + } + + // Page-transition alpha: during page switches page_alpha_ ramps 0→1. + // ImGuiStyleVar_Alpha only affects widget rendering inside the content + // child window. ForegroundDrawList effects (per-panel AND viewport-wide) + // bypass it, so we manually scale their vertex alpha here. + if (page_alpha_ < 1.0f) { + int fgEnd = fgDL->VtxBuffer.Size; + for (int vi = fgVtxStart; vi < fgEnd; vi++) { + ImDrawVert& v = fgDL->VtxBuffer[vi]; + int a = (v.col >> IM_COL32_A_SHIFT) & 0xFF; + a = static_cast(a * page_alpha_); + v.col = (v.col & ~IM_COL32_A_MASK) | (static_cast(a) << IM_COL32_A_SHIFT); + } + } + + ImGui::EndChild(); + ImGui::PopStyleVar(); // WindowPadding (content area) + ImGui::PopStyleVar(); // Alpha + + // Status bar — anchored to the bottom of the main window + // Use mainPadX/mainPadBot (the actual MainContent window padding) because the + // style var was already popped and GetStyle().WindowPadding is now wrong. + { + PERF_SCOPE("Render.StatusBar"); + float windowBottom = ImGui::GetWindowPos().y + ImGui::GetWindowSize().y; + float statusY = windowBottom - statusBarH - mainPadBot; + ImGui::SetCursorScreenPos(ImVec2(ImGui::GetWindowPos().x + mainPadX, statusY)); + renderStatusBar(); + } + + // ==================================================================== + // Modal dialogs — rendered INSIDE "MainContent" window scope so that + // ImGui's modal dim-layer and input blocking covers the sidebar, + // content area, status bar, and every other widget in this window. + // ==================================================================== + PERF_BEGIN(_perfDialogs); + if (show_settings_) { + ui::RenderSettingsWindow(this, &show_settings_); + } + + if (show_about_) { + ui::RenderAboutDialog(this, &show_about_); + } + + if (show_import_key_) { + renderImportKeyDialog(); + } + + if (show_export_key_) { + renderExportKeyDialog(); + } + + if (show_backup_) { + renderBackupDialog(); + } + + // Encrypt wallet / change passphrase dialogs (from Settings) + renderEncryptWalletDialog(); + renderDecryptWalletDialog(); + + // PIN setup / change / remove dialogs (from Settings) + renderPinDialogs(); + + // Send confirm popup + ui::RenderSendConfirmPopup(this); + + // Console RPC Command Reference popup + console_tab_.renderCommandsPopupModal(); + + // Key export dialog (triggered from balance tab context menu) + ui::KeyExportDialog::render(this); + + // Transaction details dialog (triggered from transactions tab) + ui::TransactionDetailsDialog::render(this); + + // QR code popup dialog (triggered from balance tab) + ui::QRPopupDialog::render(this); + + // Validate address dialog (triggered from Edit menu) + ui::ValidateAddressDialog::render(this); + + // Address book dialog (triggered from Edit menu) + ui::AddressBookDialog::render(this); + + // Shield/merge dialog (triggered from Wallet menu) + ui::ShieldDialog::render(this); + + // Request payment dialog (triggered from Wallet menu) + ui::RequestPaymentDialog::render(this); + + // Block info dialog (triggered from View menu) + ui::BlockInfoDialog::render(this); + + // Export all keys dialog (triggered from File menu) + ui::ExportAllKeysDialog::render(this); + + // Export transactions to CSV dialog (triggered from File menu) + ui::ExportTransactionsDialog::render(this); + + // Windows Defender antivirus help dialog + renderAntivirusHelpDialog(); + + PERF_END("Render.Dialogs", _perfDialogs); + + ImGui::End(); + + // Debug: ImGui demo window + if (show_demo_window_) { + ImGui::ShowDemoWindow(&show_demo_window_); + } + + // Render notifications (toast messages) + ui::Notifications::instance().render(); +} + +void App::renderStatusBar() +{ + // Status bar layout from unified UI schema + const auto& S = ui::schema::UI(); + const auto& sbWin = S.window("components.status-bar"); + const float sbHeight = sbWin.height; + const float sbPadX = sbWin.padding[0]; + const float sbPadY = sbWin.padding[1]; + const float sbIconTextGap = S.drawElement("components.status-bar", "icon-text-gap").size; + const float sbSectionGap = S.drawElement("components.status-bar", "section-gap").size; + const float sbSeparatorGap = S.drawElement("components.status-bar", "separator-gap").size; + const float sbRightContentOff = S.label("components.status-bar", "right-content").position; + const float sbVersionRightOff = S.label("components.status-bar", "version-label").position; + + ImGuiWindowFlags childFlags = ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoScrollWithMouse; + if (ui::material::IsBackdropActive()) { + childFlags |= ImGuiWindowFlags_NoBackground; + } + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(sbPadX, sbPadY)); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0)); + ImGui::BeginChild("##StatusBar", ImVec2(0, sbHeight), false, childFlags); + + // Use schema-configured font for status bar text (default: body2 = caption+1px) + auto sbTextStyle = S.label("components.status-bar", "text-style"); + ImFont* sbFont = S.resolveFont(sbTextStyle.font); + if (!sbFont) sbFont = ui::material::Type().body2(); + ImGui::PushFont(sbFont); + + // Apply text opacity from schema (default 60%) + auto sbTextElem = S.drawElement("components.status-bar", "text-style"); + float sbTextOpacity = (sbTextElem.opacity >= 0.0f) ? sbTextElem.opacity : 0.6f; + ImVec4 baseTextCol = ImGui::GetStyleColorVec4(ImGuiCol_Text); + baseTextCol.w *= sbTextOpacity; + ImGui::PushStyleColor(ImGuiCol_Text, baseTextCol); + + // Vertically center text within the status bar below the divider line. + // sbPadY is already applied by WindowPadding, so the content region starts + // at wPos.y + sbPadY. We set CursorPosY relative to wPos.y (not content + // start), so we must account for sbPadY ourselves to avoid placing text + // above the padded region. + { + float fontH = ImGui::GetFont()->LegacySize; + float topMargin = sbPadY; // match the window padding = space below divider + float availH = sbHeight - topMargin; + float centerY = topMargin + (availH - fontH) * 0.5f; + if (centerY > 0.0f) + ImGui::SetCursorPosY(centerY); + } + { + ImVec2 wPos = ImGui::GetWindowPos(); + float wWidth = ImGui::GetWindowWidth(); + ImGui::GetWindowDrawList()->AddLine( + ImVec2(wPos.x, wPos.y), + ImVec2(wPos.x + wWidth, wPos.y), + ui::schema::UI().resolveColor("var(--status-divider)", IM_COL32(255, 255, 255, 20)), 1.0f); + } + + // Connection status + float dotOpacity = S.drawElement("components.status-bar", "connection-dot").opacity; + if (dotOpacity < 0.0f) dotOpacity = 1.0f; + if (state_.connected) { + ImGui::PushFont(ui::material::Type().iconSmall()); + ImGui::TextColored(ImVec4(0.2f, 0.8f, 0.2f, dotOpacity), ICON_MD_CIRCLE); + ImGui::PopFont(); + ImGui::SameLine(0, sbIconTextGap); + ImGui::Text("Connected"); + } else { + ImGui::PushFont(ui::material::Type().iconSmall()); + ImGui::TextColored(ImVec4(0.8f, 0.2f, 0.2f, dotOpacity), ICON_MD_CIRCLE); + ImGui::PopFont(); + ImGui::SameLine(0, sbIconTextGap); + ImGui::Text("Disconnected"); + } + + // Block height + ImGui::SameLine(0, sbSectionGap); + ImGui::TextDisabled("|"); + ImGui::SameLine(0, sbSeparatorGap); + ImGui::Text("Block: %d", state_.sync.blocks); + + // Sync status or peer count + ImGui::SameLine(0, sbSectionGap); + ImGui::TextDisabled("|"); + ImGui::SameLine(0, sbSeparatorGap); + if (state_.sync.syncing) { + int blocksLeft = state_.sync.headers - state_.sync.blocks; + if (blocksLeft < 0) blocksLeft = 0; + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.0f, 1.0f), "Syncing %.1f%% (%d left)", + state_.sync.verification_progress * 100.0, blocksLeft); + } else if (state_.connected) { + ImGui::Text("Peers: %zu", state_.peers.size()); + } + + // Network hashrate (if connected and have data) + if (state_.connected && state_.mining.networkHashrate > 0) { + ImGui::SameLine(0, sbSectionGap); + ImGui::TextDisabled("|"); + ImGui::SameLine(0, sbSeparatorGap); + if (state_.mining.networkHashrate >= 1e9) { + ImGui::Text("Net: %.2f GH/s", state_.mining.networkHashrate / 1e9); + } else if (state_.mining.networkHashrate >= 1e6) { + ImGui::Text("Net: %.2f MH/s", state_.mining.networkHashrate / 1e6); + } else if (state_.mining.networkHashrate >= 1e3) { + ImGui::Text("Net: %.2f KH/s", state_.mining.networkHashrate / 1e3); + } else { + ImGui::Text("Net: %.1f H/s", state_.mining.networkHashrate); + } + } + + // Mining indicator (if mining) + if (state_.mining.generate) { + ImGui::SameLine(0, sbSectionGap); + ImGui::TextDisabled("|"); + ImGui::SameLine(0, sbSeparatorGap); + ImGui::PushFont(ui::material::Type().iconSmall()); + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), ICON_MD_CONSTRUCTION); + ImGui::PopFont(); + ImGui::SameLine(0, sbIconTextGap); + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "%.1f H/s", + state_.mining.localHashrate); + } + + // Right side: connection status message (if any) + version always at far right + float rightStart = ImGui::GetWindowWidth() - sbRightContentOff; + if (!connection_status_.empty() && connection_status_ != "Connected") { + ImGui::SameLine(rightStart); + ImGui::TextDisabled("%s", connection_status_.c_str()); + } else if (!daemon_status_.empty() && daemon_status_.find("Error") != std::string::npos) { + ImGui::SameLine(rightStart); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.5f, 1.0f), "Daemon not found"); + } + + // Version always at far right + ImGui::SameLine(ImGui::GetWindowWidth() - sbVersionRightOff); + ImGui::Text("v%s", DRAGONX_VERSION); + + ImGui::PopStyleColor(1); // Text opacity + ImGui::PopFont(); // status bar font + ImGui::EndChild(); + ImGui::PopStyleColor(2); // ChildBg + Border + ImGui::PopStyleVar(1); // WindowPadding +} + +void App::reloadThemeImages(const std::string& bgPath, const std::string& logoPath) +{ + // Reload background image from the path resolved by the skin system. + // Each theme specifies its image via [theme] images.background_image in its .toml. + if (!bgPath.empty()) { + ImTextureID newTex = 0; + int w = 0, h = 0; + bool loaded = false; +#ifdef _WIN32 + // On Windows, try embedded resource by filename if file load fails + { + std::filesystem::path p(bgPath); + std::string filename = p.filename().string(); + const auto* res = resources::getEmbeddedResource(filename); + if (res && res->data && res->size > 0) { + loaded = util::LoadTextureFromMemory(res->data, res->size, &newTex, &w, &h); + if (loaded) + DEBUG_LOGF("[App] Loaded theme background from embedded: %s (%dx%d)\n", filename.c_str(), w, h); + } + } +#endif + if (!loaded) { + loaded = util::LoadTextureFromFile(bgPath.c_str(), &newTex, &w, &h); + if (loaded) + DEBUG_LOGF("[App] Loaded theme background image: %s (%dx%d)\n", bgPath.c_str(), w, h); + else + DEBUG_LOGF("[App] Warning: Failed to load theme background: %s\n", bgPath.c_str()); + } + if (loaded) + gradient_tex_ = newTex; + else + gradient_tex_ = 0; // Clear stale texture when load fails + } else { + // No background image specified by theme — clear texture, + // main loop will fall back to programmatic gradient + gradient_tex_ = 0; + } + + // Reset logo loaded flags — will reload on next render frame + logo_loaded_ = false; + logo_tex_ = 0; + logo_w_ = 0; + logo_h_ = 0; + coin_logo_loaded_ = false; + coin_logo_tex_ = 0; + coin_logo_w_ = 0; + coin_logo_h_ = 0; +} + +void App::renderAboutDialog() +{ + auto dlg = ui::schema::UI().drawElement("inline-dialogs", "about"); + auto dlgF = [&](const char* key, float fb) -> float { + auto it = dlg.extraFloats.find(key); + return it != dlg.extraFloats.end() ? it->second : fb; + }; + ImGui::OpenPopup("About ObsidianDragon"); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(dlgF("width", 400.0f), dlg.height > 0 ? dlg.height : 250.0f)); + + const auto& acrylicTheme = ui::GetCurrentAcrylicTheme(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(ui::Layout::spacingXl(), ui::Layout::spacingLg())); + if (ui::effects::ImGuiAcrylic::BeginAcrylicPopupModal("About ObsidianDragon", &show_about_, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ui::material::Type().text(ui::material::TypeStyle::H6, DRAGONX_APP_NAME); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + + ImGui::Text("Version: %s", DRAGONX_VERSION); + ImGui::Text("ImGui: %s", IMGUI_VERSION); + ImGui::Spacing(); + + ImGui::TextWrapped("A shielded cryptocurrency wallet for DragonX (DRGX), " + "built with Dear ImGui for a lightweight, portable experience."); + ImGui::Spacing(); + + ImGui::Text("Copyright 2024-2026 The Hush Developers"); + ImGui::Text("Released under the GPLv3 License"); + + ImGui::Spacing(); + ImGui::Separator(); + + if (ui::material::StyledButton("Close", ImVec2(dlgF("close-button-width", 120.0f), 0), ui::material::resolveButtonFont((int)dlgF("button-font", 1)))) { + show_about_ = false; + ImGui::CloseCurrentPopup(); + } + + ui::effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopStyleVar(); +} + +void App::renderImportKeyDialog() +{ + auto dlg = ui::schema::UI().drawElement("inline-dialogs", "import-key"); + auto dlgF = [&](const char* key, float fb) -> float { + auto it = dlg.extraFloats.find(key); + return it != dlg.extraFloats.end() ? it->second : fb; + }; + ImGui::OpenPopup("Import Private Key"); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(dlgF("width", 500.0f), dlg.height > 0 ? dlg.height : 200.0f)); + + const auto& acrylicTheme = ui::GetCurrentAcrylicTheme(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(ui::Layout::spacingXl(), ui::Layout::spacingLg())); + if (ui::effects::ImGuiAcrylic::BeginAcrylicPopupModal("Import Private Key", &show_import_key_, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ui::material::Type().text(ui::material::TypeStyle::H6, "Import Private Key"); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ImGui::TextWrapped("Enter a private key to import. The wallet will rescan the blockchain for transactions."); + ImGui::Spacing(); + + ImGui::Text("Private Key:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##importkey", import_key_input_, sizeof(import_key_input_)); + + ImGui::Spacing(); + + if (!import_status_.empty()) { + if (import_success_) { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "%s", import_status_.c_str()); + } else { + ImGui::TextColored(ImVec4(0.8f, 0.3f, 0.3f, 1.0f), "%s", import_status_.c_str()); + } + } + + ImGui::Spacing(); + ImGui::Separator(); + + int btnFont = (int)dlgF("button-font", 1); + float btnW = dlgF("button-width", 120.0f); + if (ui::material::StyledButton("Import", ImVec2(btnW, 0), ui::material::resolveButtonFont(btnFont))) { + std::string key(import_key_input_); + if (!key.empty()) { + importPrivateKey(key, [this](bool success, const std::string& msg) { + import_success_ = success; + import_status_ = msg; + if (success) { + memset(import_key_input_, 0, sizeof(import_key_input_)); + } + }); + } + } + ImGui::SameLine(); + if (ui::material::StyledButton("Close", ImVec2(btnW, 0), ui::material::resolveButtonFont(btnFont))) { + show_import_key_ = false; + import_status_.clear(); + memset(import_key_input_, 0, sizeof(import_key_input_)); + ImGui::CloseCurrentPopup(); + } + + ui::effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopStyleVar(); +} + +void App::renderExportKeyDialog() +{ + auto dlg = ui::schema::UI().drawElement("inline-dialogs", "export-key"); + auto dlgF = [&](const char* key, float fb) -> float { + auto it = dlg.extraFloats.find(key); + return it != dlg.extraFloats.end() ? it->second : fb; + }; + ImGui::OpenPopup("Export Private Key"); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(dlgF("width", 600.0f), dlg.height > 0 ? dlg.height : 300.0f)); + + const auto& acrylicTheme = ui::GetCurrentAcrylicTheme(); + int btnFont = (int)dlgF("button-font", 1); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(ui::Layout::spacingXl(), ui::Layout::spacingLg())); + if (ui::effects::ImGuiAcrylic::BeginAcrylicPopupModal("Export Private Key", &show_export_key_, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ui::material::Type().text(ui::material::TypeStyle::H6, "Export Private Key"); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.4f, 1.0f), + "WARNING: Anyone with this key can spend your coins!"); + ImGui::Spacing(); + + // Address selector + ImGui::Text("Select Address:"); + std::vector all_addrs; + for (const auto& a : state_.t_addresses) all_addrs.push_back(a.address); + for (const auto& a : state_.z_addresses) all_addrs.push_back(a.address); + + int addrFrontLen = (int)dlgF("addr-front-len", 20); + int addrBackLen = (int)dlgF("addr-back-len", 8); + if (ImGui::BeginCombo("##exportaddr", export_address_.empty() ? "Select address..." : export_address_.c_str())) { + for (const auto& addr : all_addrs) { + bool selected = (export_address_ == addr); + std::string display = addr.substr(0, addrFrontLen) + "..." + addr.substr(addr.length() - addrBackLen); + if (ImGui::Selectable(display.c_str(), selected)) { + export_address_ = addr; + export_result_.clear(); + } + } + ImGui::EndCombo(); + } + + ImGui::SameLine(); + if (ui::material::StyledButton("Export", ImVec2(0, 0), ui::material::resolveButtonFont(btnFont))) { + if (!export_address_.empty()) { + exportPrivateKey(export_address_, [this](const std::string& key) { + export_result_ = key; + }); + } + } + + ImGui::Spacing(); + + if (!export_result_.empty()) { + ImGui::Text("Private Key:"); + ImGui::InputTextMultiline("##exportresult", (char*)export_result_.c_str(), + export_result_.size() + 1, ImVec2(-1, dlgF("key-display-height", 60.0f)), ImGuiInputTextFlags_ReadOnly); + + if (ui::material::StyledButton("Copy to Clipboard", ImVec2(0, 0), ui::material::resolveButtonFont(btnFont))) { + ImGui::SetClipboardText(export_result_.c_str()); + } + } + + ImGui::Spacing(); + ImGui::Separator(); + + int closeBtnFont = (int)dlgF("close-button-font", -1); + if (closeBtnFont < 0) closeBtnFont = btnFont; + if (ui::material::StyledButton("Close", ImVec2(dlgF("close-button-width", 120.0f), 0), ui::material::resolveButtonFont(closeBtnFont))) { + show_export_key_ = false; + export_result_.clear(); + export_address_.clear(); + ImGui::CloseCurrentPopup(); + } + + ui::effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopStyleVar(); +} + +void App::renderBackupDialog() +{ + auto dlg = ui::schema::UI().drawElement("inline-dialogs", "backup"); + auto dlgF = [&](const char* key, float fb) -> float { + auto it = dlg.extraFloats.find(key); + return it != dlg.extraFloats.end() ? it->second : fb; + }; + ImGui::OpenPopup("Backup Wallet"); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(dlgF("width", 500.0f), dlg.height > 0 ? dlg.height : 200.0f)); + + const auto& acrylicTheme = ui::GetCurrentAcrylicTheme(); + int btnFont = (int)dlgF("button-font", 1); + float btnW = dlgF("button-width", 120.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(ui::Layout::spacingXl(), ui::Layout::spacingLg())); + if (ui::effects::ImGuiAcrylic::BeginAcrylicPopupModal("Backup Wallet", &show_backup_, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ui::material::Type().text(ui::material::TypeStyle::H6, "Backup Wallet"); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ImGui::TextWrapped("Export all private keys to a file. Keep this file secure!"); + ImGui::Spacing(); + + ImGui::Text("Backup File Path:"); + static char backup_path[512] = "dragonx-backup.txt"; + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##backuppath", backup_path, sizeof(backup_path)); + + ImGui::Spacing(); + + if (!backup_status_.empty()) { + if (backup_success_) { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "%s", backup_status_.c_str()); + } else { + ImGui::TextColored(ImVec4(0.8f, 0.3f, 0.3f, 1.0f), "%s", backup_status_.c_str()); + } + } + + ImGui::Spacing(); + ImGui::Separator(); + + if (ui::material::StyledButton("Save Backup", ImVec2(btnW, 0), ui::material::resolveButtonFont(btnFont))) { + std::string path(backup_path); + if (!path.empty()) { + backupWallet(path, [this](bool success, const std::string& msg) { + backup_success_ = success; + backup_status_ = msg; + }); + } + } + ImGui::SameLine(); + if (ui::material::StyledButton("Close", ImVec2(btnW, 0), ui::material::resolveButtonFont(btnFont))) { + show_backup_ = false; + backup_status_.clear(); + ImGui::CloseCurrentPopup(); + } + + ui::effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopStyleVar(); +} + +void App::renderAntivirusHelpDialog() +{ +#ifdef _WIN32 + if (!pending_antivirus_dialog_) return; + + ImGui::OpenPopup("Windows Defender Blocked Miner"); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(560.0f, 360.0f)); + + const auto& acrylicTheme = ui::GetCurrentAcrylicTheme(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(ui::Layout::spacingXl(), ui::Layout::spacingLg())); + + if (ui::effects::ImGuiAcrylic::BeginAcrylicPopupModal("Windows Defender Blocked Miner", &pending_antivirus_dialog_, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + + ui::material::Type().text(ui::material::TypeStyle::H6, "Windows Defender Blocked xmrig"); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + + ImGui::TextWrapped( + "Mining software is often flagged as potentially unwanted. " + "Follow these steps to enable pool mining:"); + + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ui::material::Type().text(ui::material::TypeStyle::Subtitle2, "Step 1: Add Exclusion"); + ImGui::BulletText("Open Windows Security > Virus & threat protection"); + ImGui::BulletText("Click Manage settings > Exclusions > Add or remove"); + ImGui::BulletText("Add folder: %%APPDATA%%\\ObsidianDragon\\"); + + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ui::material::Type().text(ui::material::TypeStyle::Subtitle2, "Step 2: Restore from Quarantine (if needed)"); + ImGui::BulletText("Windows Security > Protection history"); + ImGui::BulletText("Find xmrig.exe and click Restore"); + + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + ui::material::Type().text(ui::material::TypeStyle::Subtitle2, "Step 3: Restart wallet and try again"); + + ImGui::Dummy(ImVec2(0, ui::Layout::spacingMd())); + ImGui::Separator(); + ImGui::Dummy(ImVec2(0, ui::Layout::spacingSm())); + + float btnW = 160.0f; + if (ui::material::StyledButton("Open Windows Security", ImVec2(btnW, 0))) { + // Open Windows Security app to the exclusions page + ShellExecuteA(NULL, "open", "windowsdefender://threat", NULL, NULL, SW_SHOWNORMAL); + } + ImGui::SameLine(); + if (ui::material::StyledButton("Close", ImVec2(100.0f, 0))) { + pending_antivirus_dialog_ = false; + ImGui::CloseCurrentPopup(); + } + + ui::effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopStyleVar(); +#endif +} + +void App::refreshNow() +{ + refresh_timer_ = REFRESH_INTERVAL; // Trigger immediate refresh +} + +void App::handlePaymentURI(const std::string& uri) +{ + auto payment = util::parsePaymentURI(uri); + + if (!payment.valid) { + ui::Notifications::instance().error("Invalid payment URI: " + payment.error); + return; + } + + // Store pending payment + pending_payment_valid_ = true; + pending_to_address_ = payment.address; + pending_amount_ = payment.amount; + pending_memo_ = payment.memo; + pending_label_ = payment.label; + + // Switch to Send page + current_page_ = ui::NavPage::Send; + + // Notify user + std::string msg = "Payment request loaded"; + if (payment.amount > 0) { + char buf[64]; + snprintf(buf, sizeof(buf), " for %.8f DRGX", payment.amount); + msg += buf; + } + ui::Notifications::instance().info(msg); +} + +void App::setCurrentTab(int tab) { + // Legacy int-to-NavPage mapping (used by balance_tab context menus) + static const ui::NavPage kTabMap[] = { + ui::NavPage::Overview, // 0 = Balance + ui::NavPage::Send, // 1 = Send + ui::NavPage::Receive, // 2 = Receive + ui::NavPage::History, // 3 = Transactions + ui::NavPage::Mining, // 4 = Mining + ui::NavPage::Peers, // 5 = Peers + ui::NavPage::Market, // 6 = Market + ui::NavPage::Console, // 7 = Console + ui::NavPage::Settings, // 8 = Settings + }; + if (tab >= 0 && tab < static_cast(sizeof(kTabMap)/sizeof(kTabMap[0]))) + current_page_ = kTabMap[tab]; +} + +bool App::startEmbeddedDaemon() +{ + if (!use_embedded_daemon_) { + DEBUG_LOGF("Embedded daemon disabled, not starting\n"); + return false; + } + + // Check if Sapling params exist - try extracting if embedded + if (!rpc::Connection::verifySaplingParams()) { + DEBUG_LOGF("Sapling params not found, checking for embedded resources...\n"); + + // Try to extract embedded resources if available + if (resources::hasEmbeddedResources()) { + DEBUG_LOGF("Extracting embedded Sapling params...\n"); + daemon_status_ = "Extracting Sapling parameters..."; + resources::extractEmbeddedResources(); + + // Check again after extraction + if (!rpc::Connection::verifySaplingParams()) { + daemon_status_ = "Failed to extract Sapling parameters."; + DEBUG_LOGF("Sapling params still not found after extraction!\n"); + DEBUG_LOGF("Expected location: %s\n", rpc::Connection::getSaplingParamsDir().c_str()); + return false; + } + DEBUG_LOGF("Sapling params extracted successfully\n"); + } else { + daemon_status_ = "Sapling parameters not found. They should be in: " + rpc::Connection::getSaplingParamsDir(); + DEBUG_LOGF("Sapling params not found and no embedded resources available!\n"); + DEBUG_LOGF("Expected location: %s\n", rpc::Connection::getSaplingParamsDir().c_str()); + return false; + } + } + + // Create daemon manager if needed + if (!embedded_daemon_) { + embedded_daemon_ = std::make_unique(); + + // Set up state callback + embedded_daemon_->setStateCallback([this](daemon::EmbeddedDaemon::State state, const std::string& msg) { + switch (state) { + case daemon::EmbeddedDaemon::State::Starting: + daemon_status_ = "Starting dragonxd..."; + break; + case daemon::EmbeddedDaemon::State::Running: + daemon_status_ = "dragonxd running"; + break; + case daemon::EmbeddedDaemon::State::Stopping: + daemon_status_ = "Stopping dragonxd..."; + break; + case daemon::EmbeddedDaemon::State::Stopped: + daemon_status_ = "dragonxd stopped"; + break; + case daemon::EmbeddedDaemon::State::Error: + daemon_status_ = "Error: " + msg; + break; + } + }); + } + + // Sync debug logging categories from user settings + if (settings_) { + embedded_daemon_->setDebugCategories(settings_->getDebugCategories()); + } + + return embedded_daemon_->start(); +} + +void App::stopEmbeddedDaemon() +{ + if (!embedded_daemon_) return; + + // Never stop an external daemon unless the user explicitly opted in + // via the "Stop external daemon" checkbox in Settings. This is a + // defence-in-depth guard — callers should also check, but this + // ensures no code path accidentally shuts down a daemon we don't own. + if (embedded_daemon_->externalDaemonDetected() && + !(settings_ && settings_->getStopExternalDaemon())) { + DEBUG_LOGF("stopEmbeddedDaemon: external daemon detected — " + "skipping (stop_external_daemon setting is off)\n"); + return; + } + + // Send RPC "stop" command — this is the graceful path that lets the + // daemon flush state, save block indexes, close sockets, etc. + bool stop_sent = false; + + // Try the existing RPC connection first + if (rpc_ && rpc_->isConnected()) { + DEBUG_LOGF("Sending stop command via existing RPC connection...\n"); + try { + rpc_->stop([](const json&) { + DEBUG_LOGF("Stop command acknowledged by daemon\n"); + }); + stop_sent = true; + } catch (...) { + DEBUG_LOGF("Failed to send stop via existing connection\n"); + } + } + + // If the main connection wasn't established (e.g. daemon was still + // starting up when user closed the window), create a temporary + // RPC connection just to send the stop command. + if (!stop_sent) { + DEBUG_LOGF("Main RPC not connected — creating temporary connection for stop...\n"); + auto config = rpc::Connection::autoDetectConfig(); + if (!config.rpcuser.empty() && !config.rpcpassword.empty()) { + auto tmp_rpc = std::make_unique(); + // Use a short timeout — if daemon isn't listening yet, don't block + if (tmp_rpc->connect(config.host, config.port, + config.rpcuser, config.rpcpassword)) { + DEBUG_LOGF("Temporary RPC connected, sending stop...\n"); + try { + tmp_rpc->call("stop"); + stop_sent = true; + DEBUG_LOGF("Stop command sent via temporary connection\n"); + } catch (...) { + DEBUG_LOGF("Stop RPC failed via temporary connection\n"); + } + tmp_rpc->disconnect(); + } else { + DEBUG_LOGF("Could not establish temporary RPC connection\n"); + } + } else { + DEBUG_LOGF("No RPC credentials available (DRAGONX.conf missing?)\n"); + } + } + + if (stop_sent) { + DEBUG_LOGF("Waiting for daemon to begin shutdown...\n"); + shutdown_status_ = "Waiting for daemon to begin shutdown..."; + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + } + + // Wait for process to exit; SIGTERM/TerminateProcess as last resort + shutdown_status_ = "Waiting for dragonxd process to exit..."; + embedded_daemon_->stop(30000); +} + +bool App::isEmbeddedDaemonRunning() const +{ + return embedded_daemon_ && embedded_daemon_->isRunning(); +} + +double App::getDaemonMemoryUsageMB() const +{ + // If we have an embedded daemon with a tracked process handle, use it + // directly — more reliable than a process scan since we own the handle. + if (embedded_daemon_ && embedded_daemon_->isRunning()) { + double mb = embedded_daemon_->getMemoryUsageMB(); + daemon_mem_diag_ = "embedded"; + if (mb > 0.0) return mb; + } else { + daemon_mem_diag_ = "process scan"; + } + // Fall back to platform-level process scan (external daemon) + return util::Platform::getDaemonMemoryUsageMB(); +} + +// ============================================================================ +// Shutdown +// ============================================================================ + +void App::requestQuit() +{ + beginShutdown(); +} + +void App::beginShutdown() +{ + // Only start shutdown once + if (shutting_down_) return; + shutting_down_ = true; + quit_requested_ = true; + shutdown_timer_ = 0.0f; + shutdown_start_time_ = std::chrono::steady_clock::now(); + + // Signal the RPC worker to stop accepting new tasks (non-blocking). + // The actual thread join + rpc disconnect happen in shutdown() after + // the render loop exits, so the UI stays responsive. + if (worker_) { + worker_->requestStop(); + } + + // Stop xmrig pool miner before stopping the daemon + if (xmrig_manager_ && xmrig_manager_->isRunning()) { + shutdown_status_ = "Stopping pool miner..."; + xmrig_manager_->stop(3000); + } + + DEBUG_LOGF("beginShutdown: starting (embedded_daemon_=%s)\n", + embedded_daemon_ ? "yes" : "no"); + + // If no embedded daemon, just mark done — don't stop + // an externally-managed daemon that the user started themselves. + // Worker join + RPC disconnect happen in shutdown(). + if (!embedded_daemon_) { + DEBUG_LOGF("beginShutdown: no embedded daemon, disconnecting only\n"); + shutdown_status_ = "Disconnecting..."; + if (settings_) { + settings_->save(); + } + shutdown_complete_ = true; + return; + } + + // Save settings now (safe to do on main thread) + if (settings_) { + settings_->save(); + } + + // If user opted to keep daemon running, just mark done. + // Also never stop an external daemon the user started themselves, + // unless they've explicitly enabled the "stop external daemon" setting. + bool externalDaemon = embedded_daemon_ && embedded_daemon_->externalDaemonDetected(); + if ((settings_ && settings_->getKeepDaemonRunning()) || + (externalDaemon && !(settings_ && settings_->getStopExternalDaemon()))) { + DEBUG_LOGF("beginShutdown: %s, skipping daemon stop\n", + externalDaemon ? "external daemon (not ours to stop)" + : "keep_daemon_running enabled"); + shutdown_status_ = "Disconnecting (daemon stays running)..."; + shutdown_complete_ = true; + return; + } + + shutdown_status_ = "Sending stop command to daemon..."; + DEBUG_LOGF("beginShutdown: spawning shutdown thread for daemon stop\n"); + + // Run the daemon shutdown on a background thread so the UI + // keeps rendering the shutdown screen (like SilentDragonX's + // modal "Please wait" dialog). + shutdown_thread_ = std::thread([this]() { + DEBUG_LOGF("shutdown thread: calling stopEmbeddedDaemon()\n"); + shutdown_status_ = "Sending stop command to daemon..."; + // Send RPC stop command + stopEmbeddedDaemon(); + + DEBUG_LOGF("shutdown thread: daemon stopped, disconnecting RPC\n"); + shutdown_status_ = "Cleaning up..."; + + DEBUG_LOGF("shutdown thread: complete\n"); + shutdown_status_ = "Shutdown complete"; + shutdown_complete_ = true; + }); +} + +void App::renderShutdownScreen() +{ + using namespace ui::material; + auto shutElem = [](const char* key, float fb) { + float v = ui::schema::UI().drawElement("components.shutdown", key).size; + return v >= 0 ? v : fb; + }; + shutdown_timer_ += ImGui::GetIO().DeltaTime; + + // Use the main viewport so the overlay covers the primary window + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImVec2 vp_pos = vp->Pos; + ImVec2 vp_size = vp->Size; + float cx = vp_size.x * 0.5f; // horizontal centre (local coords) + + // Semi-transparent dark overlay covering the entire main window + ImGui::SetNextWindowPos(vp_pos); + ImGui::SetNextWindowSize(vp_size); + ImGui::SetNextWindowFocus(); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.06f, 0.06f, 0.08f, 0.92f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + ImGui::Begin("##ShutdownOverlay", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoNav | + ImGuiWindowFlags_NoSavedSettings); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + // Convert local centre to screen coords for draw-list primitives + ImVec2 wp = ImGui::GetWindowPos(); + constexpr float kPi = 3.14159265f; + + // ------------------------------------------------------------------- + // Vertical centering: estimate total content height + // ------------------------------------------------------------------- + float lineH = ImGui::GetTextLineHeightWithSpacing(); + float titleH = Type().h5() ? Type().h5()->LegacySize : lineH * 1.5f; + float spinnerD = shutElem("spinner-radius", 20.0f) * 2.0f + 12.0f; + float statusH = lineH * 2.0f; + float sepH = lineH; + float panelH = shutElem("panel-max-height", 160.0f); + float totalH = titleH + spinnerD + statusH + sepH + panelH + lineH * 4.0f; + float y_start = (vp_size.y - totalH) * 0.5f; + if (y_start < lineH * 2.0f) y_start = lineH * 2.0f; + ImGui::SetCursorPosY(y_start); + + // ------------------------------------------------------------------- + // 1. Title — large, gold/amber + // ------------------------------------------------------------------- + { + const char* title = "Shutting Down"; + ImGui::PushFont(Type().h5()); + ImVec2 ts = ImGui::CalcTextSize(title); + ImGui::SetCursorPosX(cx - ts.x * 0.5f); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.85f, 0.0f, 1.0f)); + ImGui::TextUnformatted(title); + ImGui::PopStyleColor(); + ImGui::PopFont(); + } + + ImGui::Spacing(); + ImGui::Spacing(); + ImGui::Spacing(); + + // ------------------------------------------------------------------- + // 2. Animated arc spinner + // ------------------------------------------------------------------- + { + float r = shutElem("spinner-radius", 20.0f); + float thick = shutElem("spinner-thickness", 3.0f); + // Screen-space centre for draw list + ImVec2 sc(wp.x + cx, wp.y + ImGui::GetCursorPosY() + r + 2.0f); + + // Background ring (dim) + dl->PathArcTo(sc, r, 0.0f, kPi * 2.0f, 48); + dl->PathStroke(ui::schema::UI().resolveColor("var(--spinner-track)", IM_COL32(255, 255, 255, 25)), 0, thick); + + // Spinning foreground arc (~270°) + float angle = shutdown_timer_ * shutElem("spinner-speed", 2.5f); + float a_min = angle; + float a_max = angle + kPi * 1.5f; + dl->PathArcTo(sc, r, a_min, a_max, 36); + dl->PathStroke(ui::schema::UI().resolveColor("var(--spinner-active)", IM_COL32(255, 218, 0, 200)), 0, thick); + + // Advance cursor past the spinner + ImGui::Dummy(ImVec2(0, r * 2.0f + 8.0f)); + } + + ImGui::Spacing(); + + // ------------------------------------------------------------------- + // 3. Phase status (what the shutdown thread is doing) + // ------------------------------------------------------------------- + if (!shutdown_status_.empty()) { + ImVec2 ts = ImGui::CalcTextSize(shutdown_status_.c_str()); + ImGui::SetCursorPosX(cx - ts.x * 0.5f); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.75f, 0.75f, 0.75f, 1.0f)); + ImGui::TextUnformatted(shutdown_status_.c_str()); + ImGui::PopStyleColor(); + } + + ImGui::Spacing(); + + // ------------------------------------------------------------------- + // 4. Elapsed time — small, dim + // ------------------------------------------------------------------- + { + char elapsed[64]; + int secs = (int)shutdown_timer_; + if (secs < 60) + snprintf(elapsed, sizeof(elapsed), "%d seconds", secs); + else + snprintf(elapsed, sizeof(elapsed), "%d min %d sec", secs / 60, secs % 60); + + ImGui::PushFont(Type().caption()); + ImVec2 ts = ImGui::CalcTextSize(elapsed); + ImGui::SetCursorPosX(cx - ts.x * 0.5f); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.45f, 0.45f, 0.45f, 1.0f)); + ImGui::TextUnformatted(elapsed); + ImGui::PopStyleColor(); + ImGui::PopFont(); + } + + ImGui::Spacing(); + ImGui::Spacing(); + + // ------------------------------------------------------------------- + // 5. Separator line + // ------------------------------------------------------------------- + { + float pad = vp_size.x * shutElem("separator-pad-fraction", 0.25f); + ImVec2 p0(wp.x + pad, wp.y + ImGui::GetCursorPosY()); + ImVec2 p1(wp.x + vp_size.x - pad, p0.y); + dl->AddLine(p0, p1, ui::schema::UI().resolveColor("var(--status-divider)", IM_COL32(255, 255, 255, 30)), 1.0f); + ImGui::Dummy(ImVec2(0, 4.0f)); + } + + ImGui::Spacing(); + + // ------------------------------------------------------------------- + // 6. Daemon output panel — terminal-style box + // ------------------------------------------------------------------- + if (embedded_daemon_) { + auto lines = embedded_daemon_->getRecentLines(8); + if (!lines.empty()) { + float panelW = vp_size.x * shutElem("panel-width-fraction", 0.70f); + float panelX = cx - panelW * 0.5f; + float panelH = shutElem("panel-max-height", 160.0f); + + // Panel background (dark, rounded) + ImVec2 panelMin(wp.x + panelX, wp.y + ImGui::GetCursorPosY()); + ImVec2 panelMax(panelMin.x + panelW, panelMin.y + panelH); + dl->AddRectFilled(panelMin, panelMax, + ui::schema::UI().resolveColor("var(--shutdown-panel-bg)", IM_COL32(12, 14, 20, 220)), shutElem("panel-rounding", 6.0f)); + dl->AddRect(panelMin, panelMax, + ui::schema::UI().resolveColor("var(--shutdown-panel-border)", IM_COL32(255, 255, 255, 18)), shutElem("panel-rounding", 6.0f), 0, 1.0f); + + // Label above lines + float panelPad = shutElem("panel-padding", 12.0f); + ImGui::SetCursorPos(ImVec2(panelX + panelPad, + ImGui::GetCursorPosY() + panelPad)); + ImGui::PushFont(Type().caption()); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.45f, 0.45f, 0.50f, 1.0f)); + ImGui::TextUnformatted("dragonxd output"); + ImGui::PopStyleColor(); + ImGui::PopFont(); + + ImGui::Spacing(); + + // Output lines in green — clip to panel bounds + float leftPad = panelX + panelPad; + float maxTextW = panelW - panelPad * 2.0f; + ImGui::PushClipRect(panelMin, panelMax, true); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.4f, 0.78f, 0.4f, 0.9f)); + ImGui::PushFont(Type().caption()); + for (const auto& line : lines) { + // Stop rendering if we've reached near the panel bottom + float curY = wp.y + ImGui::GetCursorPosY(); + if (curY + ImGui::GetTextLineHeight() > panelMax.y - panelPad) + break; + + ImGui::SetCursorPosX(leftPad); + // Truncate if wider than panel + ImVec2 ts = ImGui::CalcTextSize(line.c_str()); + if (ts.x > maxTextW && line.size() > 10) { + // Binary search for fit is overkill; just trim chars + size_t maxChars = (size_t)(line.size() * (maxTextW / ts.x)); + if (maxChars > 3) { + std::string trunc = line.substr(0, maxChars - 3) + "..."; + ImGui::TextUnformatted(trunc.c_str()); + } else { + ImGui::TextUnformatted("..."); + } + } else { + ImGui::TextUnformatted(line.c_str()); + } + } + ImGui::PopFont(); + ImGui::PopStyleColor(); + ImGui::PopClipRect(); + + // Advance cursor past the panel + float panelBottom = panelMax.y - wp.y; + ImGui::SetCursorPosY(panelBottom + 4.0f); + ImGui::Dummy(ImVec2(0, 0)); + } + } + + ImGui::End(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Loading Overlay — shown inside content area while daemon is starting/syncing +// ============================================================================ + +void App::renderLoadingOverlay(float contentH) +{ + using namespace ui::material; + constexpr float kPi = 3.14159265f; + + auto loadElem = [](const char* key, float fb) { + float v = ui::schema::UI().drawElement("screens.loading", key).size; + return v >= 0 ? v : fb; + }; + + loading_timer_ += ImGui::GetIO().DeltaTime; + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 wp = ImGui::GetWindowPos(); + ImVec2 ws = ImGui::GetWindowSize(); + + // Layout constants + float lineH = ImGui::GetTextLineHeightWithSpacing(); + float spinnerR = loadElem("spinner-radius", 18.0f); + float gap = loadElem("vertical-gap", 8.0f); + float barH = loadElem("progress-bar", 6.0f); + float barW = loadElem("progress-width", 260.0f); + float cx = ws.x * 0.5f; // centre X (local coords) + + // Estimate total block height for vertical centering + float totalH = spinnerR * 2.0f + gap + lineH * 2.0f + gap + barH + gap + lineH; + float yOff = (ws.y - totalH) * 0.5f; + if (yOff < lineH * 2.0f) yOff = lineH * 2.0f; + + // Screen-space Y cursor (absolute) + float curY = wp.y + yOff; + + // ------------------------------------------------------------------- + // 1. Animated arc spinner + // ------------------------------------------------------------------- + { + float r = spinnerR; + float thick = loadElem("spinner-thickness", 2.5f); + ImVec2 sc(wp.x + cx, curY + r + 2.0f); + + // Background ring (dim) + dl->PathArcTo(sc, r, 0.0f, kPi * 2.0f, 48); + dl->PathStroke(ui::schema::UI().resolveColor("var(--spinner-track)", + IM_COL32(255, 255, 255, 25)), 0, thick); + + // Spinning foreground arc (~270°) + float angle = loading_timer_ * loadElem("spinner-speed", 2.5f); + dl->PathArcTo(sc, r, angle, angle + kPi * 1.5f, 36); + dl->PathStroke(ui::schema::UI().resolveColor("var(--spinner-active)", + IM_COL32(255, 218, 0, 200)), 0, thick); + + curY += r * 2.0f + gap + 4.0f; + } + + // ------------------------------------------------------------------- + // 2. Connection / daemon status text + // ------------------------------------------------------------------- + { + const char* statusText = connection_status_.c_str(); + ImFont* font = Type().subtitle1(); + if (!font) font = ImGui::GetFont(); + ImVec2 ts = font->CalcTextSizeA(font->LegacySize, FLT_MAX, 0.0f, statusText); + dl->AddText(font, font->LegacySize, + ImVec2(wp.x + cx - ts.x * 0.5f, curY), + IM_COL32(220, 220, 220, 255), statusText); + curY += ts.y + gap; + } + + // ------------------------------------------------------------------- + // 3. Sync progress bar (if connected and syncing) + // ------------------------------------------------------------------- + if (state_.connected && state_.sync.syncing) { + float progress = static_cast(state_.sync.verification_progress); + float barRadius = loadElem("progress-bar", 3.0f); + + float barX = wp.x + cx - barW * 0.5f; + ImVec2 barMin(barX, curY); + ImVec2 barMax(barX + barW, curY + barH); + + // Track background + dl->AddRectFilled(barMin, barMax, + ui::schema::UI().resolveColor("var(--progress-track)", + IM_COL32(255, 255, 255, 30)), barRadius); + + // Filled portion + ImVec2 fillMax(barMin.x + barW * progress, barMax.y); + if (fillMax.x > barMin.x + 1.0f) { + dl->AddRectFilled(barMin, fillMax, + ui::schema::UI().resolveColor("var(--primary)", + IM_COL32(255, 218, 0, 200)), barRadius); + } + + curY += barH + gap; + + // Progress text — "Syncing 45.2% — Block 123456 / 234567" + char syncBuf[128]; + snprintf(syncBuf, sizeof(syncBuf), "Syncing %.1f%% — Block %d / %d", + progress * 100.0f, state_.sync.blocks, state_.sync.headers); + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + ImVec2 ts = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, syncBuf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(wp.x + cx - ts.x * 0.5f, curY), + IM_COL32(150, 150, 150, 255), syncBuf); + curY += ts.y + gap; + } else if (!state_.connected && state_.sync.blocks > 0) { + // Show last known block height while reconnecting + char blockBuf[64]; + snprintf(blockBuf, sizeof(blockBuf), "Last block: %d", state_.sync.blocks); + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + ImVec2 ts = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, blockBuf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(wp.x + cx - ts.x * 0.5f, curY), + IM_COL32(130, 130, 130, 255), blockBuf); + curY += ts.y + gap; + } + + // ------------------------------------------------------------------- + // 3b. Deferred encryption status + // ------------------------------------------------------------------- + if (deferred_encrypt_pending_) { + curY += gap; + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + + const char* encLabel = encrypt_in_progress_ + ? "Encrypting wallet..." + : "Waiting for daemon to encrypt wallet..."; + ImVec2 ts = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, encLabel); + ImU32 encCol = IM_COL32(255, 218, 0, 200); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(wp.x + cx - ts.x * 0.5f, curY), encCol, encLabel); + curY += ts.y + gap * 0.5f; + + // Indeterminate progress bar + float encBarW = barW * 0.6f; + float encBarH = 4.0f; + float encBarX = wp.x + cx - encBarW * 0.5f; + dl->AddRectFilled(ImVec2(encBarX, curY), ImVec2(encBarX + encBarW, curY + encBarH), + IM_COL32(255, 255, 255, 20), 2.0f); + float t = loading_timer_; + float pulse = 0.5f + 0.5f * sinf(t * 2.0f); + float segW = encBarW * 0.3f; + float segX = encBarX + (encBarW - segW) * pulse; + dl->AddRectFilled(ImVec2(segX, curY), ImVec2(segX + segW, curY + encBarH), + encCol, 2.0f); + curY += encBarH + gap; + } + + // ------------------------------------------------------------------- + // 3c. Daemon crash error message + // ------------------------------------------------------------------- + if (embedded_daemon_ && + embedded_daemon_->getState() == daemon::EmbeddedDaemon::State::Error) { + curY += gap; + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + ImFont* bodyFont2 = Type().body2(); + if (!bodyFont2) bodyFont2 = ImGui::GetFont(); + + // Error title + const char* errTitle = "Daemon Error"; + ImVec2 ts = bodyFont2->CalcTextSizeA(bodyFont2->LegacySize, FLT_MAX, 0.0f, errTitle); + dl->AddText(bodyFont2, bodyFont2->LegacySize, + ImVec2(wp.x + cx - ts.x * 0.5f, curY), + IM_COL32(255, 90, 90, 255), errTitle); + curY += ts.y + gap * 0.5f; + + // Error details (wrapped) — show full diagnostic info + const std::string& errDetail = embedded_daemon_->getLastError(); + if (!errDetail.empty()) { + float wrapW = ws.x * 0.8f; + if (wrapW > 700.0f) wrapW = 700.0f; + ImVec2 es = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, wrapW, errDetail.c_str()); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(wp.x + cx - wrapW * 0.5f, curY), + IM_COL32(255, 180, 180, 220), errDetail.c_str(), nullptr, wrapW); + curY += es.y + gap; + } + + // Crash count hint + if (embedded_daemon_->getCrashCount() >= 3) { + const char* hint = "Use Settings > Restart Daemon to try again"; + ImVec2 hs2 = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, hint); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(wp.x + cx - hs2.x * 0.5f, curY), + IM_COL32(200, 200, 200, 180), hint); + curY += hs2.y + gap; + } + } + + // ------------------------------------------------------------------- + // 4. Daemon output snippet (last few lines, if embedded) + // ------------------------------------------------------------------- + if (embedded_daemon_) { + auto lines = embedded_daemon_->getRecentLines(8); + if (!lines.empty()) { + curY += gap; + + float panelW = ws.x * 0.85f; + if (panelW > 900.0f) panelW = 900.0f; + float panelX = wp.x + cx - panelW * 0.5f; + float panelPad = 8.0f; + + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + float panelLineH = capFont->LegacySize + 4.0f; + float panelContentH = panelPad * 2.0f + panelLineH * (float)lines.size(); + + ImVec2 panelMin(panelX, curY); + ImVec2 panelMax(panelX + panelW, curY + panelContentH); + + dl->AddRectFilled(panelMin, panelMax, + ui::schema::UI().resolveColor("var(--shutdown-panel-bg)", + IM_COL32(12, 14, 20, 180)), 6.0f); + dl->AddRect(panelMin, panelMax, + ui::schema::UI().resolveColor("var(--shutdown-panel-border)", + IM_COL32(255, 255, 255, 15)), 6.0f, 0, 1.0f); + + float textY = curY + panelPad; + float maxTextW = panelW - panelPad * 2.0f; + ImU32 textCol = IM_COL32(102, 199, 102, 217); // green tint + + for (const auto& line : lines) { + std::string display = line; + ImVec2 ts = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, display.c_str()); + if (ts.x > maxTextW && display.size() > 10) { + size_t maxChars = (size_t)(display.size() * (maxTextW / ts.x)); + if (maxChars > 3) display = display.substr(0, maxChars - 3) + "..."; + else display = "..."; + } + dl->AddText(capFont, capFont->LegacySize, + ImVec2(panelX + panelPad, textY), + textCol, display.c_str()); + textY += panelLineH; + } + } + } +} + +void App::shutdown() +{ + // Clean up bootstrap if running + if (bootstrap_) { + bootstrap_->cancel(); + bootstrap_.reset(); + } + + // If beginShutdown() was never called (e.g. direct exit), + // do synchronous shutdown as fallback. + if (!shutting_down_) { + DEBUG_LOGF("Synchronous shutdown fallback...\n"); + if (worker_) { + worker_->stop(); + } + if (settings_) { + settings_->save(); + } + if (embedded_daemon_) { + stopEmbeddedDaemon(); + } + if (rpc_) { + rpc_->disconnect(); + } + return; + } + + // Wait for the async shutdown thread to finish + if (shutdown_thread_.joinable()) { + shutdown_thread_.join(); + } + // Wait for wizard's external daemon stop thread + if (wizard_stop_thread_.joinable()) { + wizard_stop_thread_.join(); + } + // Wait for daemon restart thread + if (daemon_restart_thread_.joinable()) { + daemon_restart_thread_.join(); + } + // Join the RPC worker thread (was signaled in beginShutdown via requestStop) + if (worker_) { + worker_->stop(); + } + // Disconnect RPC after worker is fully stopped (safe — no curl in flight) + if (rpc_) { + rpc_->disconnect(); + } +} + +// =========================================================================== +// First-run detection +// =========================================================================== + +bool App::isFirstRun() const { + std::string dataDir = util::Platform::getDragonXDataDir(); + std::error_code ec; + return !std::filesystem::exists(dataDir, ec) || + !std::filesystem::exists(std::filesystem::path(dataDir) / "blocks", ec); +} + +bool App::hasPinVault() const { + return vault_ && vault_->hasVault() && settings_ && settings_->getPinEnabled(); +} + +bool App::hasPendingRPCResults() const { + return worker_ && worker_->hasPendingResults(); +} +void App::restartDaemon() +{ + if (!use_embedded_daemon_ || daemon_restarting_.load()) return; + daemon_restarting_ = true; + + // Reset crash counter on manual restart + if (embedded_daemon_) { + embedded_daemon_->resetCrashCount(); + } + + DEBUG_LOGF("[App] Restarting embedded daemon...\n"); + connection_status_ = "Restarting daemon..."; + + // Disconnect RPC so the loading overlay appears + if (rpc_ && rpc_->isConnected()) { + rpc_->disconnect(); + } + onDisconnected("Daemon restart"); + + // Sync debug categories from settings to daemon + if (embedded_daemon_ && settings_) { + embedded_daemon_->setDebugCategories(settings_->getDebugCategories()); + } + + // Run stop + start on a background thread to avoid blocking the UI. + // The 5-second auto-retry in render() will reconnect once the daemon + // is back up. + if (daemon_restart_thread_.joinable()) { + daemon_restart_thread_.join(); + } + daemon_restart_thread_ = std::thread([this]() { + if (embedded_daemon_ && isEmbeddedDaemonRunning()) { + stopEmbeddedDaemon(); + } + // Brief pause to let the port free up + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + startEmbeddedDaemon(); + daemon_restarting_ = false; + DEBUG_LOGF("[App] Daemon restart complete — waiting for RPC...\n"); + }); +} + +} // namespace dragonx diff --git a/src/app.h b/src/app.h new file mode 100644 index 0000000..b033a87 --- /dev/null +++ b/src/app.h @@ -0,0 +1,526 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "data/wallet_state.h" +#include "ui/sidebar.h" +#include "ui/windows/console_tab.h" +#include "imgui.h" + +// Forward declarations +namespace dragonx { + namespace rpc { + class RPCClient; + class RPCWorker; + struct ConnectionConfig; + } + namespace config { class Settings; } + namespace daemon { class EmbeddedDaemon; class XmrigManager; } + namespace util { class Bootstrap; class SecureVault; } +} + +namespace dragonx { + +/** + * @brief First-run wizard states + */ +enum class WizardPhase { + None, // No wizard — normal operation + BootstrapOffer, // Step 1: offer bootstrap download + BootstrapInProgress,// downloading / extracting + BootstrapFailed, // error with retry/skip option + Appearance, // Step 2: visual effects / performance options + EncryptOffer, // Step 3: offer wallet encryption + EncryptInProgress, // encrypting + daemon restarting + PinSetup, // Step 4: optional PIN setup (after encryption) + Done // wizard complete, launch normally +}; + +/** + * @brief Encrypt-wallet dialog phases (settings page flow) + */ +enum class EncryptDialogPhase { + PassphraseEntry, // Enter & confirm passphrase + Encrypting, // In-progress animation + PinSetup, // Offer PIN after successful encryption + Done // Finished — close dialog +}; + +/** + * @brief Main application class + * + * Manages application state, RPC connection, and coordinates UI rendering. + */ +class App { +public: + App(); + ~App(); + + // Non-copyable + App(const App&) = delete; + App& operator=(const App&) = delete; + + /** + * @brief Initialize the application + * @return true if initialization succeeded + */ + bool init(); + + /** + * @brief Update application state (called every frame) + */ + void update(); + + /** + * @brief Render the application UI (called every frame) + */ + void render(); + + /** + * @brief Clean shutdown + */ + void shutdown(); + + /** + * @brief Check if app should exit (render loop can stop) + * Enforces minimum 1-second display of shutdown screen so user sees feedback. + */ + bool shouldQuit() const { + if (!quit_requested_ || !shutdown_complete_) return false; + auto elapsed = std::chrono::steady_clock::now() - shutdown_start_time_; + return elapsed >= std::chrono::seconds(1); + } + + /** + * @brief Request application exit — begins async shutdown + */ + void requestQuit(); + + /** + * @brief Begin graceful shutdown (called on window close) + * Starts daemon stop on a background thread while UI keeps rendering. + */ + void beginShutdown(); + + /** + * @brief Whether we are in the shutdown phase + */ + bool isShuttingDown() const { return shutting_down_; } + + /** + * @brief Render the shutdown overlay (called instead of normal UI during shutdown) + */ + void renderShutdownScreen(); + + /** + * @brief Render loading overlay in content area while daemon is starting/syncing + * @param contentH Height of the content area child window + */ + void renderLoadingOverlay(float contentH); + + // Accessors for subsystems + rpc::RPCClient* rpc() { return rpc_.get(); } + rpc::RPCWorker* worker() { return worker_.get(); } + config::Settings* settings() { return settings_.get(); } + WalletState& state() { return state_; } + const WalletState& state() const { return state_; } + const WalletState& getWalletState() const { return state_; } + + // Connection state (convenience wrappers) + bool isConnected() const { return state_.connected; } + int getBlockHeight() const { return state_.sync.blocks; } + const std::string& getConnectionStatus() const { return connection_status_; } + const std::string& getDaemonStatus() const { return daemon_status_; } + + // Balance info (convenience wrappers) + double getShieldedBalance() const { return state_.shielded_balance; } + double getTransparentBalance() const { return state_.transparent_balance; } + double getTotalBalance() const { return state_.total_balance; } + double getUnconfirmedBalance() const { return state_.unconfirmed_balance; } + + // Addresses + const std::vector& getZAddresses() const { return state_.z_addresses; } + const std::vector& getTAddresses() const { return state_.t_addresses; } + + // Transactions + const std::vector& getTransactions() const { return state_.transactions; } + + // Mining + const MiningInfo& getMiningInfo() const { return state_.mining; } + void startMining(int threads); + void stopMining(); + bool isMiningToggleInProgress() const { return mining_toggle_in_progress_.load(std::memory_order_relaxed); } + + // Pool mining (xmrig) + void startPoolMining(int threads); + void stopPoolMining(); + + // Peers + const std::vector& getPeers() const { return state_.peers; } + const std::vector& getBannedPeers() const { return state_.bannedPeers; } + void banPeer(const std::string& ip, int duration_seconds = 86400); + void unbanPeer(const std::string& ip); + void clearBans(); + + // Address operations + void createNewZAddress(std::function callback = nullptr); + void createNewTAddress(std::function callback = nullptr); + + // Hide/unhide addresses from the address list (persisted in settings) + void hideAddress(const std::string& addr); + void unhideAddress(const std::string& addr); + bool isAddressHidden(const std::string& addr) const; + int getHiddenAddressCount() const; + + void favoriteAddress(const std::string& addr); + void unfavoriteAddress(const std::string& addr); + bool isAddressFavorite(const std::string& addr) const; + + // Key export/import + void exportPrivateKey(const std::string& address, std::function callback); + void exportAllKeys(std::function callback); + void importPrivateKey(const std::string& key, std::function callback); + + // Wallet backup + void backupWallet(const std::string& destination, std::function callback); + + // Transaction operations + void sendTransaction(const std::string& from, const std::string& to, + double amount, double fee, const std::string& memo, + std::function callback); + + // Force refresh + void refreshNow(); + void refreshMiningInfo(); + void refreshPeerInfo(); + void refreshMarketData(); + + // UI navigation + void setCurrentPage(ui::NavPage page) { current_page_ = page; } + ui::NavPage getCurrentPage() const { return current_page_; } + + // Dialog triggers (used by settings page to open modal dialogs) + void showImportKeyDialog() { show_import_key_ = true; } + void showExportKeyDialog() { show_export_key_ = true; } + void showBackupDialog() { show_backup_ = true; } + void showAboutDialog() { show_about_ = true; } + + // Legacy tab compat — maps int to NavPage + void setCurrentTab(int tab); + int getCurrentTab() const { return static_cast(current_page_); } + + // Payment URI handling + void handlePaymentURI(const std::string& uri); + bool hasPendingPayment() const { return pending_payment_valid_; } + void clearPendingPayment() { pending_payment_valid_ = false; } + std::string getPendingToAddress() const { return pending_to_address_; } + double getPendingAmount() const { return pending_amount_; } + std::string getPendingMemo() const { return pending_memo_; } + std::string getPendingLabel() const { return pending_label_; } + + // Embedded daemon control + bool startEmbeddedDaemon(); + void stopEmbeddedDaemon(); + bool isEmbeddedDaemonRunning() const; + bool isUsingEmbeddedDaemon() const { return use_embedded_daemon_; } + void setUseEmbeddedDaemon(bool use) { use_embedded_daemon_ = use; } + + // Get daemon memory usage in MB (uses embedded daemon handle if available, + // falls back to platform-level process scan for external daemons) + double getDaemonMemoryUsageMB() const; + + // Diagnostic string describing daemon memory detection path (for debugging) + const std::string& getDaemonMemDiag() const { return daemon_mem_diag_; } + + // Background gradient overlay texture + void setGradientTexture(ImTextureID tex) { gradient_tex_ = tex; } + ImTextureID getGradientTexture() const { return gradient_tex_; } + + // Logo texture accessor (wallet branding icon) + ImTextureID getLogoTexture() const { return logo_tex_; } + + // Coin logo texture accessor (DragonX currency icon for balance tab) + ImTextureID getCoinLogoTexture() const { return coin_logo_tex_; } + + /** + * @brief Reload theme images (background gradient + logo) from new paths + * @param bgPath Path to background image override (empty = use default) + * @param logoPath Path to logo image override (empty = use default) + */ + void reloadThemeImages(const std::string& bgPath, const std::string& logoPath); + + // Wizard / first-run + WizardPhase getWizardPhase() const { return wizard_phase_; } + bool isFirstRun() const; + + /** + * @brief Stop daemon and re-run the setup wizard + * Called from Settings. Daemon restarts automatically when wizard completes. + */ + void restartWizard(); + + /** + * @brief Restart the embedded daemon (e.g. after changing debug categories) + * Shows "Restarting daemon..." in the loading overlay while the daemon cycles. + */ + void restartDaemon(); + + // Wallet encryption helpers + void encryptWalletWithPassphrase(const std::string& passphrase); + void unlockWallet(const std::string& passphrase, int timeout); + void lockWallet(); + void changePassphrase(const std::string& oldPass, const std::string& newPass); + + // Dialog triggers for encryption (from settings page) + void showEncryptDialog() { + show_encrypt_dialog_ = true; + encrypt_dialog_phase_ = EncryptDialogPhase::PassphraseEntry; + encrypt_status_.clear(); + memset(encrypt_pass_buf_, 0, sizeof(encrypt_pass_buf_)); + memset(encrypt_confirm_buf_, 0, sizeof(encrypt_confirm_buf_)); + memset(enc_dlg_pin_buf_, 0, sizeof(enc_dlg_pin_buf_)); + memset(enc_dlg_pin_confirm_buf_, 0, sizeof(enc_dlg_pin_confirm_buf_)); + enc_dlg_saved_passphrase_.clear(); + enc_dlg_pin_status_.clear(); + } + void showChangePassphraseDialog() { show_change_passphrase_ = true; } + void showDecryptDialog() { + show_decrypt_dialog_ = true; + decrypt_phase_ = 0; // passphrase entry + decrypt_status_.clear(); + decrypt_in_progress_ = false; + memset(decrypt_pass_buf_, 0, sizeof(decrypt_pass_buf_)); + } + + // Dialog triggers for PIN (from settings page) + void showPinSetupDialog() { show_pin_setup_ = true; pin_status_.clear(); } + void showPinChangeDialog() { show_pin_change_ = true; pin_status_.clear(); } + void showPinRemoveDialog() { show_pin_remove_ = true; pin_status_.clear(); } + bool hasPinVault() const; + + /// @brief Check if RPC worker has queued results waiting to be processed + bool hasPendingRPCResults() const; + +private: + // Subsystems + std::unique_ptr rpc_; + std::unique_ptr worker_; + std::unique_ptr settings_; + std::unique_ptr embedded_daemon_; + std::unique_ptr xmrig_manager_; + bool pending_antivirus_dialog_ = false; // Show Windows Defender help dialog + + // Wallet state + WalletState state_; + + // Shutdown state + std::atomic shutting_down_{false}; + std::atomic shutdown_complete_{false}; + std::atomic refresh_in_progress_{false}; + bool address_list_dirty_ = false; // P8: dedup rebuildAddressList + std::string shutdown_status_; + std::thread shutdown_thread_; + float shutdown_timer_ = 0.0f; + std::chrono::steady_clock::time_point shutdown_start_time_; + + // Daemon restart (e.g. after changing debug log categories) + std::atomic daemon_restarting_{false}; + std::thread daemon_restart_thread_; + + // UI State + bool quit_requested_ = false; + bool show_demo_window_ = false; + bool show_settings_ = false; + bool show_about_ = false; + bool show_import_key_ = false; + bool show_export_key_ = false; + bool show_backup_ = false; + bool show_address_book_ = false; + + // Embedded daemon state + bool use_embedded_daemon_ = true; + std::string daemon_status_; + mutable std::string daemon_mem_diag_; // diagnostic info for daemon memory detection + + // Export/Import state + std::string export_result_; + char import_key_input_[512] = {0}; + std::string export_address_; + std::string import_status_; + bool import_success_ = false; + std::string backup_status_; + bool backup_success_ = false; + + // Connection + std::string connection_status_ = "Disconnected"; + bool connection_in_progress_ = false; + float loading_timer_ = 0.0f; // spinner animation for loading overlay + + // Current page (sidebar navigation) + ui::NavPage current_page_ = ui::NavPage::Overview; + ui::NavPage prev_page_ = ui::NavPage::Overview; + float page_alpha_ = 1.0f; // 0→1 fade on page switch + bool sidebar_collapsed_ = false; // true = icon-only mode + bool sidebar_user_toggled_ = false; // user manually toggled — suppress auto-collapse + float sidebar_width_anim_ = 0.0f; // animated width (0 = uninitialized) + float prev_dpi_scale_ = 0.0f; // detect DPI changes to snap sidebar width + + // Background gradient overlay + ImTextureID gradient_tex_ = 0; + + // Logo texture (reload on skin change / dark↔light switch) + ImTextureID logo_tex_ = 0; + int logo_w_ = 0; + int logo_h_ = 0; + bool logo_loaded_ = false; + bool logo_is_dark_variant_ = true; // tracks which variant is currently loaded + + // Coin logo texture (DragonX currency icon, separate from wallet branding) + ImTextureID coin_logo_tex_ = 0; + int coin_logo_w_ = 0; + int coin_logo_h_ = 0; + bool coin_logo_loaded_ = false; + + // Console tab + ui::ConsoleTab console_tab_; + + // Pending payment from URI + bool pending_payment_valid_ = false; + std::string pending_to_address_; + double pending_amount_ = 0.0; + std::string pending_memo_; + std::string pending_label_; + + // Timers (in seconds since last update) + float refresh_timer_ = 0.0f; + float price_timer_ = 0.0f; + float fast_refresh_timer_ = 0.0f; // For mining stats + + // Refresh intervals (seconds) + static constexpr float REFRESH_INTERVAL = 5.0f; + static constexpr float PRICE_INTERVAL = 60.0f; + static constexpr float FAST_REFRESH_INTERVAL = 1.0f; + + // Mining refresh guard (prevents worker queue pileup) + std::atomic mining_refresh_in_progress_{false}; + int mining_slow_counter_ = 0; // counts fast ticks; fires slow refresh every N + + // Mining toggle guard (prevents concurrent setgenerate calls) + std::atomic mining_toggle_in_progress_{false}; + + // Auto-shield guard (prevents concurrent auto-shield operations) + std::atomic auto_shield_pending_{false}; + + // P4: Incremental transaction cache + int last_tx_block_height_ = -1; // block height at last full tx fetch + + // First-run wizard state + WizardPhase wizard_phase_ = WizardPhase::None; + std::unique_ptr bootstrap_; + std::string wizard_pending_passphrase_; // held until daemon connects + std::string wizard_saved_passphrase_; // held until PinSetup completes/skipped + + // Deferred encryption (wizard background task) + std::string deferred_encrypt_passphrase_; + std::string deferred_encrypt_pin_; + bool deferred_encrypt_pending_ = false; + + // Wizard: stopping an external daemon before bootstrap + bool wizard_stopping_external_ = false; + std::string wizard_stop_status_; + std::thread wizard_stop_thread_; + + // PIN vault + std::unique_ptr vault_; + + // Lock screen state + bool lock_screen_was_visible_ = false; // tracks lock→unlock transitions for auto-focus + bool lock_use_pin_ = true; // true = PIN input, false = passphrase input + char lock_pin_buf_[16] = {}; + char lock_passphrase_buf_[256] = {}; + std::string lock_error_msg_; + float lock_error_timer_ = 0.0f; + int lock_attempts_ = 0; + float lock_lockout_timer_ = 0.0f; + bool lock_unlock_in_progress_ = false; + + // Encrypt wallet dialog state + bool show_encrypt_dialog_ = false; + bool show_change_passphrase_ = false; + EncryptDialogPhase encrypt_dialog_phase_ = EncryptDialogPhase::PassphraseEntry; + char encrypt_pass_buf_[256] = {}; + char encrypt_confirm_buf_[256] = {}; + char change_old_pass_buf_[256] = {}; + char change_new_pass_buf_[256] = {}; + char change_confirm_buf_[256] = {}; + std::string encrypt_status_; + bool encrypt_in_progress_ = false; + std::string enc_dlg_saved_passphrase_; // held for PIN setup after encrypt + char enc_dlg_pin_buf_[16] = {}; + char enc_dlg_pin_confirm_buf_[16] = {}; + std::string enc_dlg_pin_status_; + + // PIN setup dialog state (settings page) + bool show_pin_setup_ = false; + bool show_pin_change_ = false; + bool show_pin_remove_ = false; + char pin_buf_[16] = {}; + char pin_confirm_buf_[16] = {}; + char pin_old_buf_[16] = {}; + char pin_passphrase_buf_[256] = {}; + std::string pin_status_; + bool pin_in_progress_ = false; + + // Decrypt wallet dialog state + bool show_decrypt_dialog_ = false; + int decrypt_phase_ = 0; // 0=passphrase, 1=working, 2=done, 3=error + char decrypt_pass_buf_[256] = {}; + std::string decrypt_status_; + bool decrypt_in_progress_ = false; + + // Wizard PIN setup state + char wizard_pin_buf_[16] = {}; + char wizard_pin_confirm_buf_[16] = {}; + std::string wizard_pin_status_; + + // Auto-lock on idle + std::chrono::steady_clock::time_point last_interaction_ = std::chrono::steady_clock::now(); + + // Private methods - rendering + void renderStatusBar(); + void renderAboutDialog(); + void renderImportKeyDialog(); + void renderExportKeyDialog(); + void renderBackupDialog(); + void renderFirstRunWizard(); + void renderLockScreen(); + void renderEncryptWalletDialog(); + void renderDecryptWalletDialog(); + void renderPinDialogs(); + void renderAntivirusHelpDialog(); + void processDeferredEncryption(); + + // Private methods - connection + void tryConnect(); + void onConnected(); + void onDisconnected(const std::string& reason); + + // Private methods - data refresh + void refreshData(); + void refreshBalance(); + void refreshAddresses(); + void refreshTransactions(); + void refreshPrice(); + void refreshWalletEncryptionState(); + void checkAutoLock(); +}; + +} // namespace dragonx diff --git a/src/app_network.cpp b/src/app_network.cpp new file mode 100644 index 0000000..b50491d --- /dev/null +++ b/src/app_network.cpp @@ -0,0 +1,1216 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// app_network.cpp — RPC connection, data refresh, and network operations +// Split from app.cpp for maintainability. + +#include "app.h" +#include "rpc/rpc_client.h" +#include "rpc/rpc_worker.h" +#include "rpc/connection.h" +#include "config/settings.h" +#include "daemon/embedded_daemon.h" +#include "daemon/xmrig_manager.h" +#include "ui/notifications.h" +#include "util/platform.h" +#include "util/perf_log.h" + +#include +#include +#include + +namespace dragonx { + +using json = nlohmann::json; + +// ============================================================================ +// Connection Management +// ============================================================================ + +void App::tryConnect() +{ + if (connection_in_progress_) return; + + connection_in_progress_ = true; + connection_status_ = "Loading configuration..."; + + // Auto-detect configuration (file I/O — fast, safe on main thread) + auto config = rpc::Connection::autoDetectConfig(); + + if (config.rpcuser.empty() || config.rpcpassword.empty()) { + connection_in_progress_ = false; + DEBUG_LOGF("Could not find DRAGONX.conf or missing rpcuser/rpcpassword\n"); + + // If we already know an external daemon is on the port, just wait + // for the config file to appear (the daemon creates it on first run). + if (embedded_daemon_ && embedded_daemon_->externalDaemonDetected()) { + connection_status_ = "Waiting for daemon config..."; + return; + } + + connection_status_ = "No DRAGONX.conf found"; + + // Try to start embedded daemon if enabled + if (use_embedded_daemon_ && !isEmbeddedDaemonRunning()) { + connection_status_ = "Starting dragonxd..."; + if (startEmbeddedDaemon()) { + // Will retry connection after daemon starts + DEBUG_LOGF("Embedded daemon starting, will retry connection...\n"); + } else if (embedded_daemon_ && embedded_daemon_->externalDaemonDetected()) { + connection_status_ = "Waiting for daemon config..."; + DEBUG_LOGF("External daemon detected but no config yet, will retry...\n"); + } + } + return; + } + + connection_status_ = "Connecting to dragonxd..."; + DEBUG_LOGF("Connecting to %s:%s\n", config.host.c_str(), config.port.c_str()); + + // Run the blocking rpc_->connect() on the worker thread so the UI + // stays responsive (curl connect timeout can be up to 10 seconds). + if (!worker_) { + connection_in_progress_ = false; + return; + } + + // Capture daemon state before posting to worker + bool daemonStarting = embedded_daemon_ && + (embedded_daemon_->getState() == daemon::EmbeddedDaemon::State::Starting || + embedded_daemon_->getState() == daemon::EmbeddedDaemon::State::Running); + bool externalDetected = embedded_daemon_ && embedded_daemon_->externalDaemonDetected(); + + worker_->post([this, config, daemonStarting, externalDetected]() -> rpc::RPCWorker::MainCb { + bool connected = rpc_->connect(config.host, config.port, config.rpcuser, config.rpcpassword); + + return [this, connected, daemonStarting, externalDetected]() { + if (connected) { + onConnected(); + } else { + if (daemonStarting) { + state_.connected = false; + connection_status_ = "Waiting for dragonxd to start..."; + DEBUG_LOGF("Connection attempt failed — daemon still starting, will retry...\n"); + } else if (externalDetected) { + state_.connected = false; + connection_status_ = "Connecting to daemon..."; + DEBUG_LOGF("External daemon on port but RPC not ready yet, will retry...\n"); + } else { + onDisconnected("Connection failed"); + + if (use_embedded_daemon_ && !isEmbeddedDaemonRunning()) { + // Prevent infinite crash-restart loop + if (embedded_daemon_ && embedded_daemon_->getCrashCount() >= 3) { + connection_status_ = "Daemon crashed " + std::to_string(embedded_daemon_->getCrashCount()) + " times"; + DEBUG_LOGF("Daemon crashed %d times — not restarting (use Settings > Restart Daemon to retry)\n", + embedded_daemon_->getCrashCount()); + } else { + connection_status_ = "Starting dragonxd..."; + if (startEmbeddedDaemon()) { + DEBUG_LOGF("Embedded daemon starting, will retry connection...\n"); + } else if (embedded_daemon_ && embedded_daemon_->externalDaemonDetected()) { + connection_status_ = "Connecting to daemon..."; + DEBUG_LOGF("External daemon detected, will connect via RPC...\n"); + } + } + } + } + } + connection_in_progress_ = false; + }; + }); +} + +void App::onConnected() +{ + state_.connected = true; + connection_status_ = "Connected"; + + // Reset crash counter on successful connection + if (embedded_daemon_) { + embedded_daemon_->resetCrashCount(); + } + + // Get daemon info + wallet encryption state on the worker thread. + // Fetching getwalletinfo here (before refreshData) ensures the lock + // screen appears immediately instead of after 6+ queued RPC calls. + if (worker_ && rpc_) { + worker_->post([this]() -> rpc::RPCWorker::MainCb { + json info, walletInfo; + bool infoOk = false, walletOk = false; + try { + info = rpc_->call("getinfo"); + infoOk = true; + } catch (...) {} + try { + walletInfo = rpc_->call("getwalletinfo"); + walletOk = true; + } catch (...) {} + return [this, info, walletInfo, infoOk, walletOk]() { + if (infoOk) { + try { + if (info.contains("version")) + state_.daemon_version = info["version"].get(); + if (info.contains("protocolversion")) + state_.protocol_version = info["protocolversion"].get(); + if (info.contains("p2pport")) + state_.p2p_port = info["p2pport"].get(); + if (info.contains("longestchain")) + state_.longestchain = info["longestchain"].get(); + if (info.contains("notarized")) + state_.notarized = info["notarized"].get(); + if (info.contains("blocks")) + state_.sync.blocks = info["blocks"].get(); + } catch (const std::exception& e) { + DEBUG_LOGF("[onConnected] getinfo callback error: %s\n", e.what()); + } + } + // Apply encryption/lock state immediately so the lock + // screen shows on the very first frame after connect. + if (walletOk) { + try { + if (walletInfo.contains("unlocked_until")) { + state_.encrypted = true; + int64_t until = walletInfo["unlocked_until"].get(); + state_.unlocked_until = until; + state_.locked = (until == 0); + } else { + state_.encrypted = false; + state_.locked = false; + state_.unlocked_until = 0; + } + state_.encryption_state_known = true; + } catch (...) {} + } + }; + }); + } + + // Initial data refresh + refreshData(); + refreshMarketData(); +} + +void App::onDisconnected(const std::string& reason) +{ + state_.connected = false; + state_.clear(); + connection_status_ = reason; +} + +// ============================================================================ +// Data Refresh +// ============================================================================ + +void App::refreshData() +{ + if (!state_.connected || !rpc_ || !worker_) return; + + // Prevent overlapping refreshes — skip if one is still running + if (refresh_in_progress_.exchange(true)) return; + + refreshBalance(); + refreshAddresses(); + refreshTransactions(); + refreshMiningInfo(); + refreshPeerInfo(); + refreshWalletEncryptionState(); + + // Clear the guard after all tasks are posted (they'll execute sequentially + // on the worker thread, so the last one to finish signals completion). + // We post a sentinel task that clears the flag after all refresh work. + worker_->post([this]() -> rpc::RPCWorker::MainCb { + return [this]() { + refresh_in_progress_.store(false, std::memory_order_release); + }; + }); +} + +void App::refreshBalance() +{ + if (!worker_ || !rpc_) return; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + // --- Worker thread: do blocking RPC --- + json totalBal, blockInfo; + bool balOk = false, blockOk = false; + + try { + totalBal = rpc_->call("z_gettotalbalance"); + balOk = true; + } catch (const std::exception& e) { + DEBUG_LOGF("Balance error: %s\n", e.what()); + } + + try { + blockInfo = rpc_->call("getblockchaininfo"); + blockOk = true; + } catch (const std::exception& e) { + DEBUG_LOGF("BlockchainInfo error: %s\n", e.what()); + } + + // --- Main thread: apply results to state_ --- + return [this, totalBal, blockInfo, balOk, blockOk]() { + try { + if (balOk) { + if (totalBal.contains("private")) + state_.shielded_balance = std::stod(totalBal["private"].get()); + if (totalBal.contains("transparent")) + state_.transparent_balance = std::stod(totalBal["transparent"].get()); + if (totalBal.contains("total")) + state_.total_balance = std::stod(totalBal["total"].get()); + state_.last_balance_update = std::time(nullptr); + } + if (blockOk) { + if (blockInfo.contains("blocks")) + state_.sync.blocks = blockInfo["blocks"].get(); + if (blockInfo.contains("headers")) + state_.sync.headers = blockInfo["headers"].get(); + if (blockInfo.contains("verificationprogress")) + state_.sync.verification_progress = blockInfo["verificationprogress"].get(); + state_.sync.syncing = (state_.sync.blocks < state_.sync.headers - 2); + } + + // Auto-shield transparent funds if enabled + if (balOk && settings_ && settings_->getAutoShield() && + state_.transparent_balance > 0.0001 && !state_.sync.syncing && + !auto_shield_pending_.exchange(true)) { + // Find first shielded address as target + std::string targetZAddr; + for (const auto& addr : state_.addresses) { + if (addr.isShielded()) { + targetZAddr = addr.address; + break; + } + } + if (!targetZAddr.empty() && rpc_) { + DEBUG_LOGF("[AutoShield] Shielding %.8f DRGX to %s\n", + state_.transparent_balance, targetZAddr.c_str()); + rpc_->z_shieldCoinbase("*", targetZAddr, 0.0001, 50, + [this](const json& result) { + if (result.contains("opid")) { + DEBUG_LOGF("[AutoShield] Started: %s\n", + result["opid"].get().c_str()); + } + auto_shield_pending_ = false; + }, + [this](const std::string& err) { + DEBUG_LOGF("[AutoShield] Error: %s\n", err.c_str()); + auto_shield_pending_ = false; + }); + } else { + auto_shield_pending_ = false; + } + } + } catch (const std::exception& e) { + DEBUG_LOGF("[refreshBalance] callback error: %s\n", e.what()); + } + }; + }); +} + +void App::refreshAddresses() +{ + if (!worker_ || !rpc_) return; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + // --- Worker thread: fetch all address data with minimal RPC calls --- + std::vector zAddrs, tAddrs; + + // 1. Get z-addresses + try { + json zList = rpc_->call("z_listaddresses"); + for (const auto& addr : zList) { + AddressInfo info; + info.address = addr.get(); + info.type = "shielded"; + zAddrs.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("z_listaddresses error: %s\n", e.what()); + } + + // 2. P3: Use z_listUnspent (single call) instead of per-addr z_getbalance + try { + json unspent = rpc_->call("z_listunspent"); + std::map zBalances; + for (const auto& utxo : unspent) { + if (utxo.contains("address") && utxo.contains("amount")) { + zBalances[utxo["address"].get()] += utxo["amount"].get(); + } + } + for (auto& info : zAddrs) { + auto it = zBalances.find(info.address); + if (it != zBalances.end()) { + info.balance = it->second; + } + } + } catch (const std::exception& e) { + // Fallback: z_listUnspent might not be available — use batched z_getbalance + DEBUG_LOGF("z_listunspent unavailable (%s), falling back to z_getbalance\n", e.what()); + for (auto& info : zAddrs) { + try { + json bal = rpc_->call("z_getbalance", json::array({info.address})); + if (!bal.is_null()) info.balance = bal.get(); + } catch (...) {} + } + } + + // 3. Get t-addresses + try { + json tList = rpc_->call("getaddressesbyaccount", json::array({""})); + for (const auto& addr : tList) { + AddressInfo info; + info.address = addr.get(); + info.type = "transparent"; + tAddrs.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("getaddressesbyaccount error: %s\n", e.what()); + } + + // 4. Get unspent for t-address balances + try { + json utxos = rpc_->call("listunspent"); + std::map tBalances; + for (const auto& utxo : utxos) { + tBalances[utxo["address"].get()] += utxo["amount"].get(); + } + for (auto& info : tAddrs) { + auto it = tBalances.find(info.address); + if (it != tBalances.end()) info.balance = it->second; + } + } catch (const std::exception& e) { + DEBUG_LOGF("listunspent error: %s\n", e.what()); + } + + // --- Main thread: apply results and rebuild address list once --- + return [this, zAddrs = std::move(zAddrs), tAddrs = std::move(tAddrs)]() { + state_.z_addresses = std::move(zAddrs); + state_.t_addresses = std::move(tAddrs); + // P8: single rebuild via dirty flag (drains in update()) + address_list_dirty_ = true; + }; + }); +} + +void App::refreshTransactions() +{ + if (!worker_ || !rpc_) return; + + // P4a: Skip if no new blocks since last full fetch + int currentBlocks = state_.sync.blocks; + bool fullRefresh = (last_tx_block_height_ < 0 || currentBlocks != last_tx_block_height_ + || state_.transactions.empty()); + if (!fullRefresh) return; + + // Capture the z-addresses list for the worker thread + std::vector zAddrs; + for (const auto& za : state_.z_addresses) { + if (!za.address.empty()) zAddrs.push_back(za.address); + } + + worker_->post([this, zAddrs = std::move(zAddrs), currentBlocks]() -> rpc::RPCWorker::MainCb { + // --- Worker thread: all blocking RPC calls happen here --- + std::vector txns; + std::set knownTxids; + + // P4b: Collect txids that are fully enriched (skip re-enrichment) + std::set fullyEnriched; + for (const auto& tx : state_.transactions) { + if (tx.confirmations > 6 && tx.timestamp != 0) { + fullyEnriched.insert(tx.txid); + } + } + + // ---- Phase 1: transparent transactions from listtransactions ---- + try { + json result = rpc_->call("listtransactions", json::array({"", 9999})); + for (const auto& tx : result) { + TransactionInfo info; + if (tx.contains("txid")) info.txid = tx["txid"].get(); + if (tx.contains("category")) info.type = tx["category"].get(); + if (tx.contains("amount")) info.amount = tx["amount"].get(); + if (tx.contains("time")) info.timestamp = tx["time"].get(); + if (tx.contains("confirmations")) info.confirmations = tx["confirmations"].get(); + if (tx.contains("address")) info.address = tx["address"].get(); + knownTxids.insert(info.txid); + txns.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("listtransactions error: %s\n", e.what()); + } + + // ---- Phase 2: shielded receives via z_listreceivedbyaddress ---- + for (const auto& addr : zAddrs) { + try { + json zresult = rpc_->call("z_listreceivedbyaddress", json::array({addr, 0})); + if (zresult.is_null() || !zresult.is_array()) continue; + + for (const auto& note : zresult) { + std::string txid; + if (note.contains("txid")) txid = note["txid"].get(); + if (txid.empty()) continue; + if (note.contains("change") && note["change"].get()) continue; + + bool dominated = false; + for (const auto& existing : txns) { + if (existing.txid == txid && existing.type == "receive") { + dominated = true; break; + } + } + if (dominated) continue; + + TransactionInfo info; + info.txid = txid; + info.type = "receive"; + info.address = addr; + if (note.contains("amount")) info.amount = note["amount"].get(); + if (note.contains("confirmations")) info.confirmations = note["confirmations"].get(); + if (note.contains("time")) info.timestamp = note["time"].get(); + if (note.contains("memoStr")) info.memo = note["memoStr"].get(); + knownTxids.insert(txid); + txns.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("z_listreceivedbyaddress error for %s: %s\n", + addr.substr(0, 12).c_str(), e.what()); + } + } + + // ---- Phase 3: detect shielded sends via z_viewtransaction ---- + // P4d: Only check new/unconfirmed txids + for (const std::string& txid : knownTxids) { + if (fullyEnriched.count(txid)) continue; // P4b: skip already-enriched + + try { + json vtx = rpc_->call("z_viewtransaction", json::array({txid})); + if (vtx.is_null() || !vtx.is_object()) continue; + + if (vtx.contains("outputs") && vtx["outputs"].is_array()) { + for (const auto& output : vtx["outputs"]) { + bool outgoing = false; + if (output.contains("outgoing")) + outgoing = output["outgoing"].get(); + if (!outgoing) continue; + + std::string destAddr; + if (output.contains("address")) + destAddr = output["address"].get(); + double value = 0.0; + if (output.contains("value")) + value = output["value"].get(); + + bool alreadyTracked = false; + for (const auto& existing : txns) { + if (existing.txid == txid && existing.type == "send" + && std::abs(existing.amount + value) < 0.00000001) { + alreadyTracked = true; break; + } + } + if (alreadyTracked) continue; + + TransactionInfo info; + info.txid = txid; + info.type = "send"; + info.address = destAddr; + info.amount = -value; + if (output.contains("memoStr")) + info.memo = output["memoStr"].get(); + + // Get confirmations/time from existing entry + for (const auto& existing : txns) { + if (existing.txid == txid) { + info.confirmations = existing.confirmations; + info.timestamp = existing.timestamp; + break; + } + } + + if (info.timestamp == 0) { + try { + json rawtx = rpc_->call("gettransaction", json::array({txid})); + if (!rawtx.is_null() && rawtx.contains("time")) + info.timestamp = rawtx["time"].get(); + if (!rawtx.is_null() && rawtx.contains("confirmations")) + info.confirmations = rawtx["confirmations"].get(); + } catch (...) {} + } + + if (vtx.contains("spends") && vtx["spends"].is_array()) { + for (const auto& spend : vtx["spends"]) { + if (spend.contains("address")) { + info.from_address = spend["address"].get(); + break; + } + } + } + + txns.push_back(info); + } + } + } catch (const std::exception& e) { + // z_viewtransaction may not be available for all txids + } + } + + // Sort by timestamp descending + std::sort(txns.begin(), txns.end(), + [](const TransactionInfo& a, const TransactionInfo& b) { + return a.timestamp > b.timestamp; + }); + + // --- Main thread: apply results --- + return [this, txns = std::move(txns), currentBlocks]() { + state_.transactions = std::move(txns); + state_.last_tx_update = std::time(nullptr); + last_tx_block_height_ = currentBlocks; // P4a: track last-fetched height + }; + }); +} + +void App::refreshMiningInfo() +{ + if (!worker_ || !rpc_) return; + + // Prevent worker queue pileup — skip if previous refresh hasn't finished + if (mining_refresh_in_progress_.exchange(true)) return; + + // Capture daemon memory outside (may be accessed on main thread) + double daemonMemMb = 0.0; + if (embedded_daemon_) { + daemonMemMb = embedded_daemon_->getMemoryUsageMB(); + } + + // Slow-tick counter: run full getmininginfo + getinfo every ~5 seconds + // to reduce RPC overhead. getlocalsolps (returns H/s for RandomX) runs every tick (1s). + bool doSlowRefresh = (mining_slow_counter_++ % 5 == 0); + + worker_->post([this, daemonMemMb, doSlowRefresh]() -> rpc::RPCWorker::MainCb { + json miningInfo, localHashrateJson, nodeInfo; + bool miningOk = false, hashrateOk = false, nodeOk = false; + + // Fast path: only getlocalsolps (single RPC call, ~1ms) — returns H/s (RandomX) + try { + localHashrateJson = rpc_->call("getlocalsolps"); + hashrateOk = true; + } catch (const std::exception& e) { + DEBUG_LOGF("getLocalHashrate error: %s\n", e.what()); + } + + // Slow path: getmininginfo + getinfo every ~5s + if (doSlowRefresh) { + try { + miningInfo = rpc_->call("getmininginfo"); + miningOk = true; + } catch (const std::exception& e) { + DEBUG_LOGF("getMiningInfo error: %s\n", e.what()); + } + + try { + nodeInfo = rpc_->call("getinfo"); + nodeOk = true; + } catch (const std::exception& e) { + DEBUG_LOGF("getInfo error: %s\n", e.what()); + } + } + + return [this, miningInfo, localHashrateJson, nodeInfo, miningOk, hashrateOk, nodeOk, daemonMemMb]() { + try { + if (hashrateOk) { + state_.mining.localHashrate = localHashrateJson.get(); + state_.mining.hashrate_history.push_back(state_.mining.localHashrate); + if (state_.mining.hashrate_history.size() > MiningInfo::MAX_HISTORY) { + state_.mining.hashrate_history.erase(state_.mining.hashrate_history.begin()); + } + } + if (miningOk) { + if (miningInfo.contains("generate")) + state_.mining.generate = miningInfo["generate"].get(); + if (miningInfo.contains("genproclimit")) + state_.mining.genproclimit = miningInfo["genproclimit"].get(); + if (miningInfo.contains("blocks")) + state_.mining.blocks = miningInfo["blocks"].get(); + if (miningInfo.contains("difficulty")) + state_.mining.difficulty = miningInfo["difficulty"].get(); + if (miningInfo.contains("networkhashps")) + state_.mining.networkHashrate = miningInfo["networkhashps"].get(); + if (miningInfo.contains("chain")) + state_.mining.chain = miningInfo["chain"].get(); + state_.last_mining_update = std::time(nullptr); + } + if (nodeOk) { + if (nodeInfo.contains("version")) + state_.daemon_version = nodeInfo["version"].get(); + if (nodeInfo.contains("protocolversion")) + state_.protocol_version = nodeInfo["protocolversion"].get(); + if (nodeInfo.contains("p2pport")) + state_.p2p_port = nodeInfo["p2pport"].get(); + if (nodeInfo.contains("longestchain")) + state_.longestchain = nodeInfo["longestchain"].get(); + if (nodeInfo.contains("notarized")) + state_.notarized = nodeInfo["notarized"].get(); + } + } catch (const std::exception& e) { + DEBUG_LOGF("[refreshMiningInfo] callback error: %s\n", e.what()); + } + state_.mining.daemon_memory_mb = daemonMemMb; + mining_refresh_in_progress_.store(false); + }; + }); +} + +void App::refreshPeerInfo() +{ + if (!worker_ || !rpc_) return; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + std::vector peers; + std::vector bannedPeers; + + try { + json result = rpc_->call("getpeerinfo"); + for (const auto& peer : result) { + PeerInfo info; + if (peer.contains("id")) info.id = peer["id"].get(); + if (peer.contains("addr")) info.addr = peer["addr"].get(); + if (peer.contains("subver")) info.subver = peer["subver"].get(); + if (peer.contains("services")) info.services = peer["services"].get(); + if (peer.contains("version")) info.version = peer["version"].get(); + if (peer.contains("conntime")) info.conntime = peer["conntime"].get(); + if (peer.contains("banscore")) info.banscore = peer["banscore"].get(); + if (peer.contains("pingtime")) info.pingtime = peer["pingtime"].get(); + if (peer.contains("bytessent")) info.bytessent = peer["bytessent"].get(); + if (peer.contains("bytesrecv")) info.bytesrecv = peer["bytesrecv"].get(); + if (peer.contains("startingheight")) info.startingheight = peer["startingheight"].get(); + if (peer.contains("synced_headers")) info.synced_headers = peer["synced_headers"].get(); + if (peer.contains("synced_blocks")) info.synced_blocks = peer["synced_blocks"].get(); + if (peer.contains("inbound")) info.inbound = peer["inbound"].get(); + if (peer.contains("tls_cipher")) info.tls_cipher = peer["tls_cipher"].get(); + if (peer.contains("tls_verified")) info.tls_verified = peer["tls_verified"].get(); + peers.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("getPeerInfo error: %s\n", e.what()); + } + + try { + json result = rpc_->call("listbanned"); + for (const auto& ban : result) { + BannedPeer info; + if (ban.contains("address")) info.address = ban["address"].get(); + if (ban.contains("banned_until")) info.banned_until = ban["banned_until"].get(); + bannedPeers.push_back(info); + } + } catch (const std::exception& e) { + DEBUG_LOGF("listBanned error: %s\n", e.what()); + } + + return [this, peers = std::move(peers), bannedPeers = std::move(bannedPeers)]() { + state_.peers = std::move(peers); + state_.bannedPeers = std::move(bannedPeers); + state_.last_peer_update = std::time(nullptr); + }; + }); +} + +void App::refreshPrice() +{ + // Skip if price fetching is disabled + if (!settings_->getFetchPrices()) return; + if (!worker_) return; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + // --- Worker thread: blocking HTTP GET to CoinGecko --- + MarketInfo market; + bool ok = false; + + try { + CURL* curl = curl_easy_init(); + if (!curl) { + DEBUG_LOGF("Failed to initialize curl for price fetch\n"); + return nullptr; + } + + std::string response_data; + const char* url = "https://api.coingecko.com/api/v3/simple/price?ids=hush&vs_currencies=usd,btc&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true"; + + auto write_callback = [](void* contents, size_t size, size_t nmemb, std::string* userp) -> size_t { + size_t totalSize = size * nmemb; + userp->append((char*)contents, totalSize); + return totalSize; + }; + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, +write_callback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "DragonX-Wallet/1.0"); + + CURLcode res = curl_easy_perform(curl); + long http_code = 0; + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); + curl_easy_cleanup(curl); + + if (res == CURLE_OK && http_code == 200) { + auto j = json::parse(response_data); + if (j.contains("hush")) { + const auto& data = j["hush"]; + market.price_usd = data.value("usd", 0.0); + market.price_btc = data.value("btc", 0.0); + market.change_24h = data.value("usd_24h_change", 0.0); + market.volume_24h = data.value("usd_24h_vol", 0.0); + market.market_cap = data.value("usd_market_cap", 0.0); + + auto now = std::chrono::system_clock::now(); + auto time_t = std::chrono::system_clock::to_time_t(now); + char buf[64]; + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&time_t)); + market.last_updated = buf; + ok = true; + DEBUG_LOGF("Price updated: $%.6f USD\n", market.price_usd); + } + } else { + DEBUG_LOGF("Price fetch failed: %s (HTTP %ld)\n", + res != CURLE_OK ? curl_easy_strerror(res) : "OK", http_code); + } + } catch (const std::exception& e) { + DEBUG_LOGF("Price fetch error: %s\n", e.what()); + } + + if (!ok) return nullptr; + + return [this, market]() { + state_.market.price_usd = market.price_usd; + state_.market.price_btc = market.price_btc; + state_.market.change_24h = market.change_24h; + state_.market.volume_24h = market.volume_24h; + state_.market.market_cap = market.market_cap; + state_.market.last_updated = market.last_updated; + + state_.market.price_history.push_back(market.price_usd); + if (state_.market.price_history.size() > MarketInfo::MAX_HISTORY) { + state_.market.price_history.erase(state_.market.price_history.begin()); + } + }; + }); +} + +void App::refreshMarketData() +{ + refreshPrice(); +} + +// ============================================================================ +// Mining Operations +// ============================================================================ + +void App::startMining(int threads) +{ + if (!state_.connected || !rpc_ || !worker_) return; + if (mining_toggle_in_progress_.exchange(true)) return; // already in progress + + worker_->post([this, threads]() -> rpc::RPCWorker::MainCb { + bool ok = false; + std::string errMsg; + try { + rpc_->call("setgenerate", {true, threads}); + ok = true; + } catch (const std::exception& e) { + errMsg = e.what(); + } + return [this, threads, ok, errMsg]() { + mining_toggle_in_progress_.store(false); + if (ok) { + state_.mining.generate = true; + state_.mining.genproclimit = threads; + DEBUG_LOGF("Mining started with %d threads\n", threads); + } else { + DEBUG_LOGF("Failed to start mining: %s\n", errMsg.c_str()); + ui::Notifications::instance().error("Mining failed: " + errMsg); + } + }; + }); +} + +void App::stopMining() +{ + if (!state_.connected || !rpc_ || !worker_) return; + if (mining_toggle_in_progress_.exchange(true)) return; // already in progress + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + bool ok = false; + try { + rpc_->call("setgenerate", {false, 0}); + ok = true; + } catch (const std::exception& e) { + DEBUG_LOGF("Failed to stop mining: %s\n", e.what()); + } + return [this, ok]() { + mining_toggle_in_progress_.store(false); + if (ok) { + state_.mining.generate = false; + state_.mining.localHashrate = 0.0; + DEBUG_LOGF("Mining stopped\n"); + } + }; + }); +} + +void App::startPoolMining(int threads) +{ + if (!xmrig_manager_) + xmrig_manager_ = std::make_unique(); + + // If already running, stop first (e.g. thread count change) + if (xmrig_manager_->isRunning()) { + xmrig_manager_->stop(); + } + + // Stop solo mining first if active + if (state_.mining.generate) stopMining(); + + daemon::XmrigManager::Config cfg; + cfg.pool_url = settings_->getPoolUrl(); + cfg.worker_name = settings_->getPoolWorker(); + cfg.algo = settings_->getPoolAlgo(); + cfg.threads = threads; // Use the same thread selection as solo mining + cfg.tls = settings_->getPoolTls(); + cfg.hugepages = settings_->getPoolHugepages(); + + // Use first transparent address as the mining wallet address + for (const auto& addr : state_.addresses) { + if (addr.type == "transparent" && !addr.address.empty()) { + cfg.wallet_address = addr.address; + break; + } + } + if (cfg.wallet_address.empty() && !state_.z_addresses.empty()) { + cfg.wallet_address = state_.z_addresses[0].address; + } + + if (cfg.wallet_address.empty()) { + DEBUG_LOGF("[ERROR] Pool mining: No wallet address available\n"); + ui::Notifications::instance().error("No wallet address available for pool mining"); + return; + } + + if (!xmrig_manager_->start(cfg)) { + std::string err = xmrig_manager_->getLastError(); + DEBUG_LOGF("[ERROR] Pool mining: %s\n", err.c_str()); + + // Check for Windows Defender blocking (error 225 = ERROR_VIRUS_INFECTED) + if (err.find("error 225") != std::string::npos || + err.find("virus") != std::string::npos) { + ui::Notifications::instance().error( + "Windows Defender blocked xmrig. Add exclusion for %APPDATA%\\ObsidianDragon"); +#ifdef _WIN32 + // Offer to open Windows Security settings + pending_antivirus_dialog_ = true; +#endif + } else { + ui::Notifications::instance().error("Failed to start pool miner: " + err); + } + } +} + +void App::stopPoolMining() +{ + if (xmrig_manager_ && xmrig_manager_->isRunning()) { + xmrig_manager_->stop(3000); + } +} + +// ============================================================================ +// Peer Operations +// ============================================================================ + +void App::banPeer(const std::string& ip, int duration_seconds) +{ + if (!state_.connected || !rpc_) return; + + rpc_->setBan(ip, "add", [this](const json&) { + refreshPeerInfo(); + }, nullptr, duration_seconds); +} + +void App::unbanPeer(const std::string& ip) +{ + if (!state_.connected || !rpc_) return; + + rpc_->setBan(ip, "remove", [this](const json&) { + refreshPeerInfo(); + }); +} + +void App::clearBans() +{ + if (!state_.connected || !rpc_) return; + + rpc_->clearBanned([this](const json&) { + state_.banned_peers.clear(); + }); +} + +// ============================================================================ +// Address Operations +// ============================================================================ + +void App::createNewZAddress(std::function callback) +{ + if (!state_.connected || !rpc_) return; + + rpc_->z_getNewAddress([this, callback](const json& result) { + std::string addr = result.get(); + refreshAddresses(); + if (callback) callback(addr); + }); +} + +void App::createNewTAddress(std::function callback) +{ + if (!state_.connected || !rpc_) return; + + rpc_->getNewAddress([this, callback](const json& result) { + std::string addr = result.get(); + refreshAddresses(); + if (callback) callback(addr); + }); +} + +void App::hideAddress(const std::string& addr) +{ + if (settings_) { + settings_->hideAddress(addr); + settings_->save(); + } +} + +void App::unhideAddress(const std::string& addr) +{ + if (settings_) { + settings_->unhideAddress(addr); + settings_->save(); + } +} + +bool App::isAddressHidden(const std::string& addr) const +{ + return settings_ && settings_->isAddressHidden(addr); +} + +int App::getHiddenAddressCount() const +{ + return settings_ ? settings_->getHiddenAddressCount() : 0; +} + +void App::favoriteAddress(const std::string& addr) +{ + if (settings_) { + settings_->favoriteAddress(addr); + settings_->save(); + } +} + +void App::unfavoriteAddress(const std::string& addr) +{ + if (settings_) { + settings_->unfavoriteAddress(addr); + settings_->save(); + } +} + +bool App::isAddressFavorite(const std::string& addr) const +{ + return settings_ && settings_->isAddressFavorite(addr); +} + +// ============================================================================ +// Key Export/Import Operations +// ============================================================================ + +void App::exportPrivateKey(const std::string& address, std::function callback) +{ + if (!state_.connected || !rpc_) { + if (callback) callback(""); + return; + } + + // Check if it's a z-address or t-address + if (address.length() > 0 && address[0] == 'z') { + // Z-address: use z_exportkey + rpc_->z_exportKey(address, [callback](const json& result) { + if (callback) callback(result.get()); + }, [callback](const std::string& error) { + DEBUG_LOGF("Export z-key error: %s\n", error.c_str()); + ui::Notifications::instance().error("Key export failed: " + error); + if (callback) callback(""); + }); + } else { + // T-address: use dumpprivkey + rpc_->dumpPrivKey(address, [callback](const json& result) { + if (callback) callback(result.get()); + }, [callback](const std::string& error) { + DEBUG_LOGF("Export t-key error: %s\n", error.c_str()); + ui::Notifications::instance().error("Key export failed: " + error); + if (callback) callback(""); + }); + } +} + +void App::exportAllKeys(std::function callback) +{ + if (!state_.connected || !rpc_) { + if (callback) callback(""); + return; + } + + // Collect all keys into a string + auto keys_result = std::make_shared(); + auto pending = std::make_shared(0); + auto total = std::make_shared(0); + + // First get all addresses + auto all_addresses = std::make_shared>(); + + // Add t-addresses + for (const auto& addr : state_.t_addresses) { + all_addresses->push_back(addr.address); + } + // Add z-addresses + for (const auto& addr : state_.z_addresses) { + all_addresses->push_back(addr.address); + } + + *total = all_addresses->size(); + *pending = *total; + + if (*total == 0) { + if (callback) callback("# No addresses to export\n"); + return; + } + + *keys_result = "# DragonX Wallet Private Keys Export\n"; + *keys_result += "# WARNING: Keep this file secure! Anyone with these keys can spend your coins!\n\n"; + + for (const auto& addr : *all_addresses) { + exportPrivateKey(addr, [keys_result, pending, total, callback, addr](const std::string& key) { + if (!key.empty()) { + *keys_result += "# " + addr + "\n"; + *keys_result += key + "\n\n"; + } + (*pending)--; + if (*pending == 0 && callback) { + callback(*keys_result); + } + }); + } +} + +void App::importPrivateKey(const std::string& key, std::function callback) +{ + if (!state_.connected || !rpc_) { + if (callback) callback(false, "Not connected"); + return; + } + + // Detect key type based on prefix + bool is_zkey = (key.length() > 0 && key[0] == 's'); // z-address keys start with 'secret-extended-key' + + if (is_zkey) { + rpc_->z_importKey(key, true, [this, callback](const json& result) { + refreshAddresses(); + if (callback) callback(true, "Z-address key imported successfully. Wallet is rescanning."); + }, [callback](const std::string& error) { + if (callback) callback(false, error); + }); + } else { + rpc_->importPrivKey(key, true, [this, callback](const json& result) { + refreshAddresses(); + if (callback) callback(true, "T-address key imported successfully. Wallet is rescanning."); + }, [callback](const std::string& error) { + if (callback) callback(false, error); + }); + } +} + +void App::backupWallet(const std::string& destination, std::function callback) +{ + if (!state_.connected || !rpc_) { + if (callback) callback(false, "Not connected"); + return; + } + + // Use z_exportwallet or similar to export all keys + // For now, we'll use exportAllKeys and save to file + exportAllKeys([destination, callback](const std::string& keys) { + if (keys.empty()) { + if (callback) callback(false, "Failed to export keys"); + return; + } + + // Write to file + std::ofstream file(destination); + if (!file.is_open()) { + if (callback) callback(false, "Could not open file: " + destination); + return; + } + + file << keys; + file.close(); + + if (callback) callback(true, "Wallet backup saved to: " + destination); + }); +} + +// ============================================================================ +// Transaction Operations +// ============================================================================ + +void App::sendTransaction(const std::string& from, const std::string& to, + double amount, double fee, const std::string& memo, + std::function callback) +{ + if (!state_.connected || !rpc_) { + if (callback) callback(false, "Not connected"); + return; + } + + // Build recipients array + nlohmann::json recipients = nlohmann::json::array(); + nlohmann::json recipient; + recipient["address"] = to; + // Format amount to exactly 8 decimal places (satoshi precision). + // Sending a raw double can produce 15+ decimal digits which the + // daemon's ParseFixedPoint rejects with "Invalid amount". + char amt_buf[32]; + snprintf(amt_buf, sizeof(amt_buf), "%.8f", amount); + recipient["amount"] = std::string(amt_buf); + if (!memo.empty()) { + recipient["memo"] = memo; + } + recipients.push_back(recipient); + + // Run z_sendmany on worker thread to avoid blocking UI + if (worker_) { + worker_->post([this, from, recipients, callback]() -> rpc::RPCWorker::MainCb { + bool ok = false; + std::string result_str; + try { + auto result = rpc_->call("z_sendmany", {from, recipients}); + result_str = result.get(); + ok = true; + } catch (const std::exception& e) { + result_str = e.what(); + } + return [callback, ok, result_str]() { + if (callback) callback(ok, result_str); + }; + }); + } +} + +} // namespace dragonx diff --git a/src/app_security.cpp b/src/app_security.cpp new file mode 100644 index 0000000..00c57c8 --- /dev/null +++ b/src/app_security.cpp @@ -0,0 +1,1487 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// app_security.cpp — Wallet encryption, lock screen, PIN management +// Split from app.cpp for maintainability. + +#include "app.h" +#include "rpc/rpc_client.h" +#include "rpc/rpc_worker.h" +#include "config/settings.h" +#include "daemon/embedded_daemon.h" +#include "ui/notifications.h" +#include "ui/material/color_theme.h" +#include "ui/material/type.h" +#include "ui/material/typography.h" +#include "ui/material/draw_helpers.h" +#include "ui/schema/ui_schema.h" +#include "util/platform.h" +#include "util/secure_vault.h" +#include "util/perf_log.h" +#include "embedded/IconsMaterialDesign.h" + +#include "imgui.h" +#include +#include +#include + +namespace dragonx { + +using json = nlohmann::json; + + +// =========================================================================== +// Wallet encryption helpers +// =========================================================================== + +void App::encryptWalletWithPassphrase(const std::string& passphrase) { + if (!rpc_ || !rpc_->isConnected()) return; + encrypt_in_progress_ = true; + encrypt_status_ = "Encrypting wallet..."; + + if (worker_) { + worker_->post([this, passphrase]() -> rpc::RPCWorker::MainCb { + try { + auto result = rpc_->call("encryptwallet", {passphrase}); + return [this]() { + encrypt_in_progress_ = false; + encrypt_status_ = "Wallet encrypted. Restarting daemon..."; + DEBUG_LOGF("[App] Wallet encrypted — restarting daemon\n"); + + // Transition settings dialog to PIN setup phase + if (show_encrypt_dialog_ && + encrypt_dialog_phase_ == EncryptDialogPhase::Encrypting) { + encrypt_dialog_phase_ = EncryptDialogPhase::PinSetup; + } + + // The daemon shuts itself down after encryptwallet + if (isUsingEmbeddedDaemon()) { + // Give daemon a moment to shut down, then restart + // (do this off the main thread to avoid stalling the UI) + std::thread([this]() { + std::this_thread::sleep_for(std::chrono::seconds(2)); + stopEmbeddedDaemon(); + startEmbeddedDaemon(); + // tryConnect will be called by the update loop + }).detach(); + } else { + ui::Notifications::instance().warning( + "Wallet encrypted. Please restart your daemon."); + } + }; + } catch (const std::exception& e) { + std::string err = e.what(); + return [this, err]() { + encrypt_in_progress_ = false; + encrypt_status_ = "Encryption failed: " + err; + DEBUG_LOGF("[App] encryptwallet failed: %s\n", err.c_str()); + + // Return to passphrase entry on failure + if (show_encrypt_dialog_ && + encrypt_dialog_phase_ == EncryptDialogPhase::Encrypting) { + encrypt_dialog_phase_ = EncryptDialogPhase::PassphraseEntry; + } + }; + } + }); + } +} + +// --------------------------------------------------------------------------- +// Deferred encryption — runs after wizard exits, encrypts wallet in background +// Called every frame from render() until the task completes. +// --------------------------------------------------------------------------- +void App::processDeferredEncryption() { + if (!deferred_encrypt_pending_) return; + + // Phase 1: wait for daemon connection + if (!state_.connected || !rpc_ || !rpc_->isConnected()) { + // Throttle connection attempts to every 3 seconds + static double s_lastAttempt = -10.0; + double now = ImGui::GetTime(); + if (now - s_lastAttempt >= 3.0) { + s_lastAttempt = now; + if (!connection_in_progress_) { + // Just try to connect — tryConnect is now async + tryConnect(); + if (!isEmbeddedDaemonRunning() && isUsingEmbeddedDaemon()) { + startEmbeddedDaemon(); + } + } + } + return; // try again next frame + } + + // Phase 2: connected — launch encryption + if (!encrypt_in_progress_) { + std::string passphrase = deferred_encrypt_passphrase_; + std::string pin = deferred_encrypt_pin_; + + encrypt_in_progress_ = true; + encrypt_status_ = "Encrypting wallet..."; + + if (worker_) { + worker_->post([this, passphrase, pin]() -> rpc::RPCWorker::MainCb { + try { + rpc_->call("encryptwallet", {passphrase}); + + // Store PIN vault on the worker thread (Argon2id is expensive) + bool pinStored = false; + if (!pin.empty() && vault_) { + pinStored = vault_->store(pin, passphrase); + } + + return [this, pinStored, pin]() { + encrypt_in_progress_ = false; + encrypt_status_.clear(); + DEBUG_LOGF("[App] Wallet encrypted (deferred)\n"); + + // Finalize PIN settings on main thread + if (!pin.empty()) { + if (pinStored) { + settings_->setPinEnabled(true); + settings_->save(); + ui::Notifications::instance().info("Wallet encrypted & PIN set"); + } else { + ui::Notifications::instance().warning( + "Wallet encrypted but PIN vault failed"); + } + } else { + ui::Notifications::instance().info("Wallet encrypted successfully"); + } + + // Securely clear deferred state + if (!deferred_encrypt_passphrase_.empty()) { + util::SecureVault::secureZero( + &deferred_encrypt_passphrase_[0], + deferred_encrypt_passphrase_.size()); + deferred_encrypt_passphrase_.clear(); + } + if (!deferred_encrypt_pin_.empty()) { + util::SecureVault::secureZero( + &deferred_encrypt_pin_[0], + deferred_encrypt_pin_.size()); + deferred_encrypt_pin_.clear(); + } + deferred_encrypt_pending_ = false; + + // Restart daemon (it shuts itself down after encryptwallet) + if (isUsingEmbeddedDaemon()) { + std::thread([this]() { + std::this_thread::sleep_for(std::chrono::seconds(2)); + stopEmbeddedDaemon(); + startEmbeddedDaemon(); + // tryConnect will be called by the update loop + }).detach(); + } else { + ui::Notifications::instance().warning( + "Please restart your daemon for encryption to take effect."); + } + }; + } catch (const std::exception& e) { + std::string err = e.what(); + return [this, err]() { + encrypt_in_progress_ = false; + encrypt_status_ = "Encryption failed: " + err; + deferred_encrypt_pending_ = false; + DEBUG_LOGF("[App] Deferred encryptwallet failed: %s\n", err.c_str()); + ui::Notifications::instance().error("Encryption failed: " + err); + + // Clean up sensitive data on failure + if (!deferred_encrypt_passphrase_.empty()) { + util::SecureVault::secureZero( + &deferred_encrypt_passphrase_[0], + deferred_encrypt_passphrase_.size()); + deferred_encrypt_passphrase_.clear(); + } + if (!deferred_encrypt_pin_.empty()) { + util::SecureVault::secureZero( + &deferred_encrypt_pin_[0], + deferred_encrypt_pin_.size()); + deferred_encrypt_pin_.clear(); + } + }; + } + }); + } + } +} + +void App::unlockWallet(const std::string& passphrase, int timeout) { + if (!rpc_ || !rpc_->isConnected() || !worker_) return; + lock_unlock_in_progress_ = true; + + worker_->post([this, passphrase, timeout]() -> rpc::RPCWorker::MainCb { + bool ok = false; + std::string err_msg; + try { + rpc_->call("walletpassphrase", {passphrase, timeout}); + ok = true; + } catch (const std::exception& e) { + err_msg = e.what(); + } + + return [this, ok, err_msg, timeout]() { + lock_unlock_in_progress_ = false; + if (ok) { + lock_error_msg_.clear(); + lock_attempts_ = 0; + memset(lock_passphrase_buf_, 0, sizeof(lock_passphrase_buf_)); + last_interaction_ = std::chrono::steady_clock::now(); + // Set unlock state immediately — walletpassphrase + // already succeeded, no need for another RPC round-trip. + state_.encrypted = true; + state_.locked = false; + state_.unlocked_until = std::time(nullptr) + timeout; + } else { + lock_attempts_++; + lock_error_msg_ = "Incorrect passphrase"; + lock_error_timer_ = 3.0f; + memset(lock_passphrase_buf_, 0, sizeof(lock_passphrase_buf_)); + + float baseDelay = ui::schema::UI().drawElement("security", "lockout-base-delay").sizeOr(2.0f); + int maxAttempts = (int)ui::schema::UI().drawElement("security", "max-attempts-before-lockout").sizeOr(5.0f); + if (lock_attempts_ >= maxAttempts) { + lock_lockout_timer_ = baseDelay * (float)(1 << std::min(lock_attempts_ - maxAttempts, 8)); + } + DEBUG_LOGF("[App] Wallet unlock failed (attempt %d): %s\n", lock_attempts_, err_msg.c_str()); + } + }; + }); +} + +void App::lockWallet() { + if (!rpc_ || !rpc_->isConnected() || !worker_) return; + if (lock_unlock_in_progress_) return; // Prevent duplicate async calls + lock_unlock_in_progress_ = true; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + bool ok = false; + try { + rpc_->call("walletlock"); + ok = true; + } catch (...) {} + + return [this, ok]() { + lock_unlock_in_progress_ = false; + if (ok) { + state_.locked = true; + state_.unlocked_until = 0; + DEBUG_LOGF("[App] Wallet locked\n"); + } + }; + }); +} + +void App::changePassphrase(const std::string& oldPass, const std::string& newPass) { + if (!rpc_ || !rpc_->isConnected() || !worker_) return; + encrypt_in_progress_ = true; + encrypt_status_ = "Changing passphrase..."; + + worker_->post([this, oldPass, newPass]() -> rpc::RPCWorker::MainCb { + bool ok = false; + std::string err_msg; + try { + rpc_->call("walletpassphrasechange", {oldPass, newPass}); + ok = true; + } catch (const std::exception& e) { + err_msg = e.what(); + } + + return [this, ok, err_msg]() { + encrypt_in_progress_ = false; + if (ok) { + encrypt_status_.clear(); + show_change_passphrase_ = false; + memset(change_old_pass_buf_, 0, sizeof(change_old_pass_buf_)); + memset(change_new_pass_buf_, 0, sizeof(change_new_pass_buf_)); + memset(change_confirm_buf_, 0, sizeof(change_confirm_buf_)); + ui::Notifications::instance().info("Passphrase changed successfully"); + } else { + encrypt_status_ = "Failed: " + err_msg; + } + }; + }); +} + +// =========================================================================== +// Refresh wallet encryption state (from getwalletinfo) +// =========================================================================== + +void App::refreshWalletEncryptionState() { + if (!rpc_ || !rpc_->isConnected() || !worker_) return; + + worker_->post([this]() -> rpc::RPCWorker::MainCb { + json result; + bool ok = false; + try { + result = rpc_->call("getwalletinfo"); + ok = true; + } catch (...) {} + + if (!ok) return nullptr; + + return [this, result]() { + try { + if (result.contains("unlocked_until")) { + state_.encrypted = true; + int64_t until = result["unlocked_until"].get(); + state_.unlocked_until = until; + state_.locked = (until == 0); + } else { + state_.encrypted = false; + state_.locked = false; + state_.unlocked_until = 0; + + // Wallet is no longer encrypted — if a PIN vault exists, + // it's stale (passphrase it protects is gone). Reset PIN + // as if it were never set. + if (vault_ && vault_->hasVault()) { + DEBUG_LOGF("[App] Wallet unencrypted but PIN vault exists — removing stale vault\n"); + vault_->removeVault(); + } + if (settings_ && settings_->getPinEnabled()) { + settings_->setPinEnabled(false); + settings_->save(); + } + } + state_.encryption_state_known = true; + } catch (...) {} + }; + }); +} + +// =========================================================================== +// Auto-lock on idle +// =========================================================================== + +void App::checkAutoLock() { + if (!state_.isEncrypted() || state_.isLocked()) return; + + // Don't auto-lock while mining — mining is a long-running intentional + // operation and locking the wallet on the daemon side stops solo mining. + bool miningActive = state_.mining.generate + || (xmrig_manager_ && xmrig_manager_->isRunning()); + if (miningActive) { + // Keep resetting the idle timer so we don't lock the instant mining stops + last_interaction_ = std::chrono::steady_clock::now(); + return; + } + + int timeout = settings_ ? settings_->getAutoLockTimeout() : 300; + if (timeout <= 0) return; // disabled + + auto now = std::chrono::steady_clock::now(); + float elapsed = std::chrono::duration(now - last_interaction_).count(); + + if (elapsed >= (float)timeout) { + lockWallet(); + DEBUG_LOGF("[App] Auto-locked wallet after %d seconds idle\n", timeout); + } +} + +// =========================================================================== +// Restart Setup Wizard (from Settings) +// =========================================================================== + + + +// =========================================================================== +// Lock Screen Rendering +// =========================================================================== + +void App::renderLockScreen() { + using namespace ui::material; + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 winPos = ImGui::GetWindowPos(); + ImVec2 winSize = ImGui::GetWindowSize(); + + // Optional backdrop (0 = no darkening) + float backdropAlpha = ui::schema::UI().drawElement("screens.lock-screen", "backdrop-alpha").opacity; + if (backdropAlpha > 0.0f) { + ImU32 backdropCol = IM_COL32(0, 0, 0, (int)(255 * backdropAlpha)); + dl->AddRectFilled(winPos, ImVec2(winPos.x + winSize.x, winPos.y + winSize.y), backdropCol); + } + + // Card + const auto& S = ui::schema::UI(); + float cardW = S.drawElement("screens.lock-screen", "card").getFloat("width", 400.0f); + float cardH = S.drawElement("screens.lock-screen", "card").height; + if (cardW <= 0) cardW = 400.0f; + if (cardH <= 0) cardH = 320.0f; + + float cardX = winPos.x + (winSize.x - cardW) * 0.5f; + float cardY = winPos.y + (winSize.y - cardH) * 0.5f; + ImVec2 cardMin(cardX, cardY); + ImVec2 cardMax(cardX + cardW, cardY + cardH); + + ImU32 cardBg = ui::material::SurfaceVariant(); + dl->AddRectFilled(cardMin, cardMax, cardBg, 16.0f); + + float cy = cardY + 24.0f; + + // Logo + float logoSize = S.drawElement("screens.lock-screen", "logo").sizeOr(64.0f); + if (logo_tex_ != 0) { + float aspect = (logo_h_ > 0) ? (float)logo_w_ / (float)logo_h_ : 1.0f; + float logoW = logoSize * aspect; + float logoX = cardX + (cardW - logoW) * 0.5f; + dl->AddImage(logo_tex_, ImVec2(logoX, cy), ImVec2(logoX + logoW, cy + logoSize)); + } + cy += logoSize + 16.0f; + + // Title + ImFont* titleFont = S.resolveFont(S.label("screens.lock-screen", "title").font); + if (!titleFont) titleFont = ui::material::Type().h5(); + ImFont* captionFont = S.resolveFont(S.label("screens.lock-screen", "error-text").font); + if (!captionFont) captionFont = ui::material::Type().caption(); + ImU32 textCol = ui::material::OnSurface(); + + { + const char* title = "Wallet Locked"; + ImVec2 ts = titleFont->CalcTextSizeA(titleFont->LegacySize, FLT_MAX, 0, title); + dl->AddText(titleFont, titleFont->LegacySize, + ImVec2(cardX + (cardW - ts.x) * 0.5f, cy), textCol, title); + cy += ts.y + 20.0f; + } + + // Lockout timer + if (lock_lockout_timer_ > 0.0f) { + lock_lockout_timer_ -= ImGui::GetIO().DeltaTime; + if (lock_lockout_timer_ < 0) lock_lockout_timer_ = 0; + + char msg[128]; + snprintf(msg, sizeof(msg), "Too many attempts. Wait %.0f seconds...", lock_lockout_timer_); + ImVec2 ms = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, msg); + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cardX + (cardW - ms.x) * 0.5f, cy), ui::material::Warning(), msg); + cy += captionFont->LegacySize + 12.0f; + } + + // Check if PIN vault is available + bool hasPinVault = vault_ && vault_->hasVault() && settings_ && settings_->getPinEnabled(); + + // Mode toggle (PIN / Passphrase) — only show if PIN vault exists + if (hasPinVault) { + const char* modeIcon = lock_use_pin_ ? ICON_MD_DIALPAD : ICON_MD_PASSWORD; + const char* modeText = lock_use_pin_ ? " PIN" : " Passphrase"; + const char* switchLabel = lock_use_pin_ + ? "Use passphrase instead" + : "Use PIN instead"; + + // Current mode indicator — icon with icon font, text with caption font + ImFont* iconFont = ui::material::Type().iconSmall(); + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, modeIcon); + ImVec2 textSize = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, modeText); + float totalW = iconSize.x + textSize.x; + float startX = cardX + (cardW - totalW) * 0.5f; + float textY = cy + (iconSize.y - textSize.y) * 0.5f; // vertically align text to icon + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(startX, cy), IM_COL32(255,255,255,120), modeIcon); + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(startX + iconSize.x, textY), IM_COL32(255,255,255,120), modeText); + cy += std::max(iconSize.y, textSize.y) + 8.0f; + + // Switch link + ImVec2 sls = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, switchLabel); + float switchX = cardX + (cardW - sls.x) * 0.5f; + ImGui::SetCursorScreenPos(ImVec2(switchX, cy)); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + if (ImGui::InvisibleButton("##switch_mode", sls)) { + lock_use_pin_ = !lock_use_pin_; + memset(lock_passphrase_buf_, 0, sizeof(lock_passphrase_buf_)); + memset(lock_pin_buf_, 0, sizeof(lock_pin_buf_)); + lock_error_msg_.clear(); + lock_screen_was_visible_ = false; // re-trigger auto-focus for new input + } + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(switchX, cy), ui::material::Primary(), switchLabel); + ImGui::PopStyleColor(); + cy += captionFont->LegacySize + 12.0f; + } else { + // No PIN vault — don't show toggle, force passphrase mode + lock_use_pin_ = false; + } + + // Input field + float inputW = S.drawElement("screens.lock-screen", "input").getFloat("width", 320.0f); + if (inputW <= 0) inputW = 320.0f; + float inputX = cardX + (cardW - inputW) * 0.5f; + + bool canSubmit = lock_lockout_timer_ <= 0.0f && !lock_unlock_in_progress_; + bool submitted = false; + + if (lock_use_pin_ && hasPinVault) { + // PIN input + ImGui::SetCursorScreenPos(ImVec2(inputX, cy)); + ImGui::PushItemWidth(inputW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f); + ImGuiInputTextFlags pinFlags = ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal; + if (canSubmit) pinFlags |= ImGuiInputTextFlags_EnterReturnsTrue; + submitted = ImGui::InputText("##lock_pin", lock_pin_buf_, + sizeof(lock_pin_buf_), pinFlags); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + } else { + // Passphrase input (original) + ImGui::SetCursorScreenPos(ImVec2(inputX, cy)); + ImGui::PushItemWidth(inputW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f); + ImGuiInputTextFlags inputFlags = ImGuiInputTextFlags_Password; + if (canSubmit) inputFlags |= ImGuiInputTextFlags_EnterReturnsTrue; + submitted = ImGui::InputText("##lock_pass", lock_passphrase_buf_, + sizeof(lock_passphrase_buf_), inputFlags); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + } + cy += 40.0f + 12.0f; + + // Focus the input when the lock screen first appears. + // IsWindowAppearing() does not work here because the lock screen is + // rendered inside ##ContentArea which has already been alive since the + // first frame. Instead we track the hidden→visible transition ourselves. + if (!lock_screen_was_visible_) { + ImGui::SetKeyboardFocusHere(-1); + lock_screen_was_visible_ = true; + } + + // Error message + if (!lock_error_msg_.empty() && lock_error_timer_ > 0) { + lock_error_timer_ -= ImGui::GetIO().DeltaTime; + ImVec2 es = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, lock_error_msg_.c_str()); + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cardX + (cardW - es.x) * 0.5f, cy), ui::material::Error(), + lock_error_msg_.c_str()); + cy += captionFont->LegacySize + 8.0f; + } + + // "Unlocking..." feedback while worker thread is running + // Always reserve the vertical space so the button doesn't shift. + { + float rowH = captionFont->LegacySize + 8.0f; + if (lock_unlock_in_progress_) { + // Animated spinner dots + int dots = ((int)(ImGui::GetTime() * 3.0f)) % 4; + const char* dotStr[] = {"", ".", "..", "..."}; + char msg[64]; + snprintf(msg, sizeof(msg), "Unlocking%s", dotStr[dots]); + ImVec2 ms = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, msg); + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cardX + (cardW - ms.x) * 0.5f, cy), + ui::material::Primary(), msg); + } + cy += rowH; + } + + // Unlock button + float unlockW = S.drawElement("screens.lock-screen", "unlock-button").getFloat("width", 320.0f); + float unlockH = S.drawElement("screens.lock-screen", "unlock-button").height; + if (unlockW <= 0) unlockW = 320.0f; + if (unlockH <= 0) unlockH = 44.0f; + float unlockX = cardX + (cardW - unlockW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(unlockX, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f); + ImGui::BeginDisabled(!canSubmit); + bool btnClicked = ImGui::Button("Unlock", ImVec2(unlockW, unlockH)); + ImGui::EndDisabled(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + + // Handle submit (Enter key or button click) + if ((submitted || btnClicked) && canSubmit) { + // Derive daemon unlock timeout from auto-lock setting: + // 2x the idle timeout so the daemon stays unlocked longer than + // the GUI auto-lock, acting as a safety net if the GUI crashes. + // Floor of 600s (10 min) when auto-lock is off or very short. + int autoLock = settings_ ? settings_->getAutoLockTimeout() : 300; + int timeout = (autoLock > 0) ? std::max(600, autoLock * 2) : 86400; + + if (lock_use_pin_ && hasPinVault && strlen(lock_pin_buf_) > 0) { + // PIN unlock — run Argon2id key derivation + RPC off the main + // thread so the UI stays responsive instead of freezing. + std::string pin(lock_pin_buf_); + memset(lock_pin_buf_, 0, sizeof(lock_pin_buf_)); + lock_unlock_in_progress_ = true; + + if (worker_) { + worker_->post([this, pin, timeout]() -> rpc::RPCWorker::MainCb { + // Heavy Argon2id derivation runs here (worker thread) + std::string passphrase; + bool vaultOk = vault_ && vault_->retrieve(pin, passphrase); + + if (!vaultOk) { + return [this]() { + lock_unlock_in_progress_ = false; + lock_attempts_++; + lock_error_msg_ = "Incorrect PIN"; + lock_error_timer_ = 3.0f; + + float baseDelay = ui::schema::UI().drawElement("security", "lockout-base-delay").sizeOr(2.0f); + int maxAttempts = (int)ui::schema::UI().drawElement("security", "max-attempts-before-lockout").sizeOr(5.0f); + if (lock_attempts_ >= maxAttempts) { + lock_lockout_timer_ = baseDelay * (float)(1 << std::min(lock_attempts_ - maxAttempts, 8)); + } + }; + } + + // Vault decrypted — now unlock wallet via RPC (also on worker thread) + bool rpcOk = false; + std::string rpcErr; + try { + if (rpc_ && rpc_->isConnected()) { + rpc_->call("walletpassphrase", {passphrase, timeout}); + rpcOk = true; + } else { + rpcErr = "Not connected to daemon"; + } + } catch (const std::exception& e) { + rpcErr = e.what(); + } + + // Securely wipe passphrase + util::SecureVault::secureZero(&passphrase[0], passphrase.size()); + + if (rpcOk) { + return [this, timeout]() { + lock_unlock_in_progress_ = false; + lock_error_msg_.clear(); + lock_attempts_ = 0; + memset(lock_passphrase_buf_, 0, sizeof(lock_passphrase_buf_)); + last_interaction_ = std::chrono::steady_clock::now(); + // Set unlock state immediately — walletpassphrase + // already succeeded, no need for another RPC round-trip. + state_.encrypted = true; + state_.locked = false; + state_.unlocked_until = std::time(nullptr) + timeout; + }; + } else { + return [this, rpcErr]() { + lock_unlock_in_progress_ = false; + lock_attempts_++; + lock_error_msg_ = "Unlock failed: " + rpcErr; + lock_error_timer_ = 3.0f; + }; + } + }); + } + } else if (strlen(lock_passphrase_buf_) > 0) { + // Direct passphrase unlock + unlockWallet(std::string(lock_passphrase_buf_), timeout); + } + } +} + +// =========================================================================== +// Encrypt Wallet Dialog (post-first-run, from Settings) +// =========================================================================== + +void App::renderEncryptWalletDialog() { + if (!show_encrypt_dialog_ && !show_change_passphrase_) return; + + // Encrypt wallet dialog — multi-phase: passphrase → encrypting → PIN setup + if (show_encrypt_dialog_) { + const char* dlgTitle = (encrypt_dialog_phase_ == EncryptDialogPhase::PinSetup) + ? "Quick-Unlock PIN##EncDlg" : "Encrypt Wallet##EncDlg"; + + // Prevent closing via X button while encrypting + bool canClose = (encrypt_dialog_phase_ != EncryptDialogPhase::Encrypting); + bool* pOpen = canClose ? &show_encrypt_dialog_ : nullptr; + + ImGui::SetNextWindowSize(ImVec2(460, 0), ImGuiCond_FirstUseEver); + ImGuiWindowFlags dlgFlags = ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoDocking | + ImGuiWindowFlags_AlwaysAutoResize; + if (ImGui::Begin(dlgTitle, pOpen, dlgFlags)) { + + // ---- Phase 1: Passphrase entry ---- + if (encrypt_dialog_phase_ == EncryptDialogPhase::PassphraseEntry) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 0.7f, 0.3f, 1)); + ImGui::TextWrapped(ICON_MD_WARNING + " If you lose your passphrase, you lose access to your funds."); + ImGui::PopStyleColor(); + ImGui::Spacing(); + + ImGui::TextWrapped("Encrypting your wallet protects your private keys " + "with a passphrase. After encryption, the daemon will restart."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Passphrase:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##enc_pass", encrypt_pass_buf_, sizeof(encrypt_pass_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + ImGui::Text("Confirm:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##enc_confirm", encrypt_confirm_buf_, sizeof(encrypt_confirm_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + // Strength meter bar + { + size_t len = strlen(encrypt_pass_buf_); + const char* strengthLabel = "Weak"; + ImVec4 strengthCol(0.9f, 0.2f, 0.2f, 1.0f); + float strengthPct = 0.25f; + if (len >= 16) { strengthLabel = "Strong"; strengthCol = ImVec4(0.3f,0.9f,0.5f,1); strengthPct = 1.0f; } + else if (len >= 12) { strengthLabel = "Good"; strengthCol = ImVec4(0.3f,0.9f,0.5f,1); strengthPct = 0.75f; } + else if (len >= 8) { strengthLabel = "Fair"; strengthCol = ImVec4(1,0.7f,0.3f,1); strengthPct = 0.5f; } + + float barW = ImGui::GetContentRegionAvail().x; + float barH = 4.0f; + ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + dl->AddRectFilled(p, ImVec2(p.x + barW, p.y + barH), + IM_COL32(255,255,255,30), 2.0f); + if (len > 0) + dl->AddRectFilled(p, ImVec2(p.x + barW * strengthPct, p.y + barH), + ImGui::ColorConvertFloat4ToU32(strengthCol), 2.0f); + ImGui::Dummy(ImVec2(barW, barH)); + ImGui::Text("Strength: %s", strengthLabel); + } + + if (!encrypt_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", encrypt_status_.c_str()); + } + + ImGui::Spacing(); + bool valid = strlen(encrypt_pass_buf_) >= 8 && + strcmp(encrypt_pass_buf_, encrypt_confirm_buf_) == 0; + + float btnW = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f; + ImGui::BeginDisabled(!valid || encrypt_in_progress_); + if (ImGui::Button("Encrypt Wallet", ImVec2(btnW, 40))) { + std::string pass(encrypt_pass_buf_); + enc_dlg_saved_passphrase_ = pass; + memset(encrypt_pass_buf_, 0, sizeof(encrypt_pass_buf_)); + memset(encrypt_confirm_buf_, 0, sizeof(encrypt_confirm_buf_)); + encrypt_dialog_phase_ = EncryptDialogPhase::Encrypting; + encryptWalletWithPassphrase(pass); + util::SecureVault::secureZero(&pass[0], pass.size()); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(btnW, 40))) { + memset(encrypt_pass_buf_, 0, sizeof(encrypt_pass_buf_)); + memset(encrypt_confirm_buf_, 0, sizeof(encrypt_confirm_buf_)); + show_encrypt_dialog_ = false; + } + + // ---- Phase 2: Encrypting in progress ---- + } else if (encrypt_dialog_phase_ == EncryptDialogPhase::Encrypting) { + const char* statusTitle = encrypt_in_progress_ + ? "Encrypting wallet..." : encrypt_status_.c_str(); + ImGui::Text("%s", statusTitle); + ImGui::Spacing(); + + // Indeterminate progress bar + { + float barW = ImGui::GetContentRegionAvail().x; + float barH = 6.0f; + ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + dl->AddRectFilled(p, ImVec2(p.x + barW, p.y + barH), + IM_COL32(255,255,255,25), 3.0f); + float t = (float)ImGui::GetTime(); + float pulse = 0.5f + 0.5f * sinf(t * 2.0f); + float segW = barW * 0.3f; + float segX = p.x + (barW - segW) * pulse; + dl->AddRectFilled(ImVec2(segX, p.y), ImVec2(segX + segW, p.y + barH), + ImGui::ColorConvertFloat4ToU32(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]), + 3.0f); + ImGui::Dummy(ImVec2(barW, barH)); + } + + if (!encrypt_status_.empty()) { + ImGui::TextColored(ImVec4(1, 1, 1, 0.6f), "%s", encrypt_status_.c_str()); + } + + ImGui::Spacing(); + ImGui::TextColored(ImVec4(1,1,1,0.4f), "Please wait, do not close the application."); + + // Transition to PIN phase when encryption finishes successfully + if (!encrypt_in_progress_ && encrypt_dialog_phase_ == EncryptDialogPhase::Encrypting) { + // encryptWalletWithPassphrase callback handles the transition + } + + // ---- Phase 3: PIN setup (after successful encryption) ---- + } else if (encrypt_dialog_phase_ == EncryptDialogPhase::PinSetup) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.3f, 0.9f, 0.5f, 1)); + ImGui::Text(ICON_MD_CHECK_CIRCLE " Wallet encrypted successfully!"); + ImGui::PopStyleColor(); + ImGui::Spacing(); + + ImGui::TextWrapped("A 4-8 digit PIN lets you unlock your wallet " + "without typing the full passphrase every time."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("PIN (4-8 digits):"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##enc_dlg_pin", enc_dlg_pin_buf_, sizeof(enc_dlg_pin_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + ImGui::Text("Confirm PIN:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##enc_dlg_pin_confirm", enc_dlg_pin_confirm_buf_, + sizeof(enc_dlg_pin_confirm_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + if (!enc_dlg_pin_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", enc_dlg_pin_status_.c_str()); + } + + ImGui::Spacing(); + std::string pinStr(enc_dlg_pin_buf_); + std::string pinConfirm(enc_dlg_pin_confirm_buf_); + bool pinValid = util::SecureVault::isValidPin(pinStr) && pinStr == pinConfirm; + bool hasPassphrase = !enc_dlg_saved_passphrase_.empty(); + + float btnW = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f; + + ImGui::BeginDisabled(!pinValid || !hasPassphrase || pin_in_progress_); + if (ImGui::Button("Set PIN", ImVec2(btnW, 40))) { + pin_in_progress_ = true; + enc_dlg_pin_status_.clear(); + std::string savedPass = enc_dlg_saved_passphrase_; + if (worker_ && vault_) { + worker_->post([this, pinStr, savedPass]() -> rpc::RPCWorker::MainCb { + // Argon2id runs here (worker thread) + bool ok = vault_->store(pinStr, savedPass); + return [this, ok]() { + if (ok) { + settings_->setPinEnabled(true); + settings_->save(); + pin_in_progress_ = false; + ui::Notifications::instance().info("PIN set successfully"); + // Clean up + if (!enc_dlg_saved_passphrase_.empty()) { + util::SecureVault::secureZero(&enc_dlg_saved_passphrase_[0], + enc_dlg_saved_passphrase_.size()); + enc_dlg_saved_passphrase_.clear(); + } + memset(enc_dlg_pin_buf_, 0, sizeof(enc_dlg_pin_buf_)); + memset(enc_dlg_pin_confirm_buf_, 0, sizeof(enc_dlg_pin_confirm_buf_)); + show_encrypt_dialog_ = false; + } else { + enc_dlg_pin_status_ = "Failed to create PIN vault"; + pin_in_progress_ = false; + } + }; + }); + } else { + enc_dlg_pin_status_ = "Failed to create PIN vault"; + pin_in_progress_ = false; + } + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + if (ImGui::Button("Skip", ImVec2(btnW, 40))) { + if (!enc_dlg_saved_passphrase_.empty()) { + util::SecureVault::secureZero(&enc_dlg_saved_passphrase_[0], + enc_dlg_saved_passphrase_.size()); + enc_dlg_saved_passphrase_.clear(); + } + memset(enc_dlg_pin_buf_, 0, sizeof(enc_dlg_pin_buf_)); + memset(enc_dlg_pin_confirm_buf_, 0, sizeof(enc_dlg_pin_confirm_buf_)); + show_encrypt_dialog_ = false; + } + } + } + ImGui::End(); + + // Clean up saved passphrase if dialog was closed via X button + if (!show_encrypt_dialog_ && !enc_dlg_saved_passphrase_.empty()) { + util::SecureVault::secureZero(&enc_dlg_saved_passphrase_[0], + enc_dlg_saved_passphrase_.size()); + enc_dlg_saved_passphrase_.clear(); + } + } + + // Change passphrase dialog + if (show_change_passphrase_) { + ImGui::SetNextWindowSize(ImVec2(440, 320), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Change Passphrase##ChgDlg", &show_change_passphrase_, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) { + ImGui::Text("Current Passphrase:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##chg_old", change_old_pass_buf_, sizeof(change_old_pass_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + ImGui::Text("New Passphrase:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##chg_new", change_new_pass_buf_, sizeof(change_new_pass_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + ImGui::Text("Confirm New:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##chg_confirm", change_confirm_buf_, sizeof(change_confirm_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + if (!encrypt_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", encrypt_status_.c_str()); + } + + ImGui::Spacing(); + bool valid = strlen(change_old_pass_buf_) > 0 && + strlen(change_new_pass_buf_) >= 8 && + strcmp(change_new_pass_buf_, change_confirm_buf_) == 0; + ImGui::BeginDisabled(!valid || encrypt_in_progress_); + if (ImGui::Button("Change Passphrase", ImVec2(-1, 40))) { + changePassphrase(std::string(change_old_pass_buf_), + std::string(change_new_pass_buf_)); + } + ImGui::EndDisabled(); + } + ImGui::End(); + } +} + +// =========================================================================== +// Decrypt (Remove Encryption) Dialog +// =========================================================================== +// Flow: +// Phase 0: Enter current passphrase +// Phase 1: Working — unlock → export → stop → rename → restart → import +// Phase 2: Success +// Phase 3: Error +// =========================================================================== + +void App::renderDecryptWalletDialog() { + if (!show_decrypt_dialog_) return; + using namespace ui::material; + + const char* title = "Remove Wallet Encryption##DecryptDlg"; + bool canClose = (decrypt_phase_ != 1); // don't close while working + bool* pOpen = canClose ? &show_decrypt_dialog_ : nullptr; + + ImGui::SetNextWindowSize(ImVec2(480, 0), ImGuiCond_FirstUseEver); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoDocking | + ImGuiWindowFlags_AlwaysAutoResize; + + if (ImGui::Begin(title, pOpen, flags)) { + + // ---- Phase 0: Passphrase entry ---- + if (decrypt_phase_ == 0) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 0.7f, 0.3f, 1)); + ImGui::TextWrapped(ICON_MD_WARNING + " This will remove encryption from your wallet. " + "Your private keys will be stored unprotected on disk."); + ImGui::PopStyleColor(); + ImGui::Spacing(); + + ImGui::TextWrapped( + "The wallet will be exported, the daemon restarted with a fresh " + "unencrypted wallet, and all keys re-imported. This may take " + "several minutes depending on wallet size."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Current Passphrase:"); + ImGui::PushItemWidth(-1); + bool enterPressed = ImGui::InputText("##decrypt_pass", decrypt_pass_buf_, + sizeof(decrypt_pass_buf_), ImGuiInputTextFlags_Password | + ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + + if (!decrypt_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", decrypt_status_.c_str()); + } + + ImGui::Spacing(); + bool valid = strlen(decrypt_pass_buf_) >= 1; + + float btnW = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f; + ImGui::BeginDisabled(!valid || decrypt_in_progress_); + if (ImGui::Button("Remove Encryption", ImVec2(btnW, 40)) || (enterPressed && valid)) { + std::string passphrase(decrypt_pass_buf_); + memset(decrypt_pass_buf_, 0, sizeof(decrypt_pass_buf_)); + decrypt_phase_ = 1; + decrypt_in_progress_ = true; + decrypt_status_ = "Unlocking wallet..."; + + // Run entire decrypt flow on worker thread + if (worker_) { + worker_->post([this, passphrase]() -> rpc::RPCWorker::MainCb { + // Step 1: Unlock wallet + try { + rpc_->call("walletpassphrase", {passphrase, 600}); + } catch (const std::exception& e) { + std::string err = e.what(); + return [this, err]() { + decrypt_in_progress_ = false; + decrypt_status_ = "Incorrect passphrase"; + decrypt_phase_ = 0; // back to entry + }; + } + + // Step 2: Export wallet to temp file + std::string exportFile = "obsidian_decrypt_export_" + + std::to_string(std::time(nullptr)); + + // Update status on main thread + // (we can't easily do mid-flow updates from worker, + // so we just proceed — the UI shows "working") + + try { + rpc_->call("z_exportwallet", {exportFile}); + } catch (const std::exception& e) { + std::string err = e.what(); + return [this, err]() { + decrypt_in_progress_ = false; + decrypt_status_ = "Export failed: " + err; + decrypt_phase_ = 3; + }; + } + + // Step 3: Stop daemon + try { + rpc_->call("stop"); + } catch (...) { + // stop often throws because connection drops + } + + // Wait for daemon to fully stop + std::this_thread::sleep_for(std::chrono::seconds(3)); + + // Step 4: Rename encrypted wallet.dat → wallet.dat.encrypted.bak + std::string dataDir = util::Platform::getDragonXDataDir(); + std::string walletPath = dataDir + "wallet.dat"; + std::string backupPath = dataDir + "wallet.dat.encrypted.bak"; + std::error_code ec; + if (std::filesystem::exists(walletPath, ec)) { + // Remove old backup if exists + std::filesystem::remove(backupPath, ec); + std::filesystem::rename(walletPath, backupPath, ec); + if (ec) { + std::string err = ec.message(); + return [this, err]() { + decrypt_in_progress_ = false; + decrypt_status_ = "Failed to rename wallet.dat: " + err; + decrypt_phase_ = 3; + }; + } + } + + // Step 5: Restart daemon (creates fresh unencrypted wallet) + return [this, exportFile]() { + decrypt_status_ = "Restarting daemon..."; + + auto restartAndImport = [this, exportFile]() { + // Give daemon time to stop fully + std::this_thread::sleep_for(std::chrono::seconds(2)); + + if (isUsingEmbeddedDaemon()) { + stopEmbeddedDaemon(); + std::this_thread::sleep_for(std::chrono::seconds(1)); + startEmbeddedDaemon(); + } + + // Wait for daemon to become available + int maxWait = 60; // seconds + bool daemonUp = false; + for (int i = 0; i < maxWait; i++) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + try { + rpc_->call("getinfo"); + daemonUp = true; + break; + } catch (...) {} + } + + if (!daemonUp) { + // Schedule error on main thread — can't directly update + // but we'll let the import attempt fail + } + + // Step 6: Import wallet (includes rescan) + try { + rpc_->call("z_importwallet", {exportFile}); + } catch (const std::exception& e) { + std::string err = e.what(); + // Post result back to main thread via worker + if (worker_) { + worker_->post([this, err]() -> rpc::RPCWorker::MainCb { + return [this, err]() { + decrypt_in_progress_ = false; + decrypt_status_ = "Import failed: " + err + + "\nYour encrypted wallet backup is at wallet.dat.encrypted.bak"; + decrypt_phase_ = 3; + }; + }); + } + return; + } + + // Success — post to main thread + if (worker_) { + worker_->post([this]() -> rpc::RPCWorker::MainCb { + return [this]() { + decrypt_in_progress_ = false; + decrypt_status_ = "Wallet decrypted successfully!"; + decrypt_phase_ = 2; + + // Clean up PIN vault since encryption is gone + if (vault_ && vault_->hasVault()) { + vault_->removeVault(); + } + if (settings_ && settings_->getPinEnabled()) { + settings_->setPinEnabled(false); + settings_->save(); + } + + refreshWalletEncryptionState(); + DEBUG_LOGF("[App] Wallet decrypted successfully\n"); + }; + }); + } + }; + + std::thread(restartAndImport).detach(); + }; + }); + } + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(btnW, 40))) { + memset(decrypt_pass_buf_, 0, sizeof(decrypt_pass_buf_)); + show_decrypt_dialog_ = false; + } + + // ---- Phase 1: Working ---- + } else if (decrypt_phase_ == 1) { + ImGui::Text("%s", decrypt_status_.empty() ? "Working..." : decrypt_status_.c_str()); + ImGui::Spacing(); + + // Indeterminate progress bar + { + float barW = ImGui::GetContentRegionAvail().x; + float barH = 6.0f; + ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + dl->AddRectFilled(p, ImVec2(p.x + barW, p.y + barH), + IM_COL32(255, 255, 255, 25), 3.0f); + float t = (float)ImGui::GetTime(); + float segW = barW * 0.3f; + float x0 = p.x + (barW + segW) * (0.5f + 0.5f * sinf(t * 2.0f)) - segW; + float x1 = x0 + segW; + x0 = std::max(x0, p.x); + x1 = std::min(x1, p.x + barW); + if (x1 > x0) { + dl->AddRectFilled(ImVec2(x0, p.y), ImVec2(x1, p.y + barH), + IM_COL32(255, 218, 0, 200), 3.0f); + } + ImGui::Dummy(ImVec2(barW, barH)); + } + + ImGui::Spacing(); + ImGui::TextWrapped("Please wait. The daemon is exporting keys, restarting, " + "and re-importing. This may take several minutes."); + + // ---- Phase 2: Success ---- + } else if (decrypt_phase_ == 2) { + ImGui::PushFont(Type().iconLarge()); + ImGui::TextColored(ImVec4(0.3f, 1.0f, 0.5f, 1.0f), ICON_MD_CHECK_CIRCLE); + ImGui::PopFont(); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(0.3f, 1.0f, 0.5f, 1.0f), "Wallet decrypted successfully!"); + + ImGui::Spacing(); + ImGui::TextWrapped( + "Your wallet is now unencrypted. A backup of the encrypted wallet " + "was saved as wallet.dat.encrypted.bak in your data directory."); + + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(-1, 40))) { + show_decrypt_dialog_ = false; + } + + // ---- Phase 3: Error ---- + } else if (decrypt_phase_ == 3) { + ImGui::PushFont(Type().iconLarge()); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), ICON_MD_ERROR); + ImGui::PopFont(); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "Decryption failed"); + + ImGui::Spacing(); + ImGui::TextWrapped("%s", decrypt_status_.c_str()); + + ImGui::Spacing(); + float btnW = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f; + if (ImGui::Button("Try Again", ImVec2(btnW, 40))) { + decrypt_phase_ = 0; + decrypt_status_.clear(); + } + ImGui::SameLine(); + if (ImGui::Button("Close", ImVec2(btnW, 40))) { + show_decrypt_dialog_ = false; + } + } + } + ImGui::End(); +} + +// =========================================================================== +// PIN Setup / Change / Remove Dialogs (from Settings page) +// =========================================================================== + +void App::renderPinDialogs() { + // ---- Set PIN dialog ---- + if (show_pin_setup_) { + ImGui::SetNextWindowSize(ImVec2(420, 340), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Set PIN##PinSetupDlg", &show_pin_setup_, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) { + ImGui::TextWrapped( + "Set a 4-8 digit PIN for quick wallet unlock. " + "Your wallet passphrase will be encrypted with this PIN " + "and stored locally."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Wallet Passphrase:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_passphrase", pin_passphrase_buf_, sizeof(pin_passphrase_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopItemWidth(); + + ImGui::Text("New PIN (4-8 digits):"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_new", pin_buf_, sizeof(pin_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + ImGui::Text("Confirm PIN:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_confirm", pin_confirm_buf_, sizeof(pin_confirm_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + if (!pin_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", pin_status_.c_str()); + } + + ImGui::Spacing(); + std::string pinStr(pin_buf_); + bool valid = strlen(pin_passphrase_buf_) > 0 && + util::SecureVault::isValidPin(pinStr) && + strcmp(pin_buf_, pin_confirm_buf_) == 0; + + ImGui::BeginDisabled(!valid || pin_in_progress_); + if (ImGui::Button("Set PIN", ImVec2(-1, 40))) { + pin_in_progress_ = true; + pin_status_ = "Verifying passphrase..."; + + // Verify passphrase + store vault on worker thread to avoid + // blocking the UI with Argon2id key derivation. + std::string passphrase(pin_passphrase_buf_); + std::string pin(pin_buf_); + memset(pin_passphrase_buf_, 0, sizeof(pin_passphrase_buf_)); + memset(pin_buf_, 0, sizeof(pin_buf_)); + memset(pin_confirm_buf_, 0, sizeof(pin_confirm_buf_)); + + if (rpc_ && rpc_->isConnected() && worker_) { + worker_->post([this, passphrase, pin]() -> rpc::RPCWorker::MainCb { + // Verify passphrase via RPC (worker thread) + try { + rpc_->call("walletpassphrase", {passphrase, 5}); + } catch (const std::exception& e) { + return [this]() { + pin_status_ = "Incorrect passphrase"; + pin_in_progress_ = false; + }; + } + + // Passphrase correct — store in vault (Argon2id, worker thread) + bool storeOk = vault_ && vault_->store(pin, passphrase); + + // Lock wallet back + try { + rpc_->call("walletlock"); + } catch (...) {} + + return [this, storeOk]() { + if (storeOk) { + settings_->setPinEnabled(true); + settings_->save(); + pin_status_.clear(); + pin_in_progress_ = false; + show_pin_setup_ = false; + ui::Notifications::instance().info("PIN set successfully"); + } else { + pin_status_ = "Failed to create vault"; + pin_in_progress_ = false; + } + }; + }); + } else { + pin_status_ = "Not connected to daemon"; + pin_in_progress_ = false; + } + } + ImGui::EndDisabled(); + } + ImGui::End(); + } + + // ---- Change PIN dialog ---- + if (show_pin_change_) { + ImGui::SetNextWindowSize(ImVec2(420, 300), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Change PIN##PinChangeDlg", &show_pin_change_, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) { + ImGui::TextWrapped("Change your unlock PIN. You need your current PIN and a new PIN."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Current PIN:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_old", pin_old_buf_, sizeof(pin_old_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + ImGui::Text("New PIN (4-8 digits):"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_change_new", pin_buf_, sizeof(pin_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + ImGui::Text("Confirm New PIN:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_change_confirm", pin_confirm_buf_, sizeof(pin_confirm_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + if (!pin_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", pin_status_.c_str()); + } + + ImGui::Spacing(); + std::string newPin(pin_buf_); + bool valid = strlen(pin_old_buf_) >= 4 && + util::SecureVault::isValidPin(newPin) && + strcmp(pin_buf_, pin_confirm_buf_) == 0; + + ImGui::BeginDisabled(!valid || pin_in_progress_); + if (ImGui::Button("Change PIN", ImVec2(-1, 40))) { + pin_in_progress_ = true; + pin_status_ = "Changing PIN..."; + std::string oldPin(pin_old_buf_); + std::string newPinCopy = newPin; + memset(pin_old_buf_, 0, sizeof(pin_old_buf_)); + memset(pin_buf_, 0, sizeof(pin_buf_)); + memset(pin_confirm_buf_, 0, sizeof(pin_confirm_buf_)); + + if (worker_ && vault_) { + worker_->post([this, oldPin, newPinCopy]() -> rpc::RPCWorker::MainCb { + // Argon2id runs here (worker thread) + bool ok = vault_->changePin(oldPin, newPinCopy); + return [this, ok]() { + if (ok) { + pin_status_.clear(); + pin_in_progress_ = false; + show_pin_change_ = false; + ui::Notifications::instance().info("PIN changed successfully"); + } else { + pin_status_ = "Incorrect current PIN"; + pin_in_progress_ = false; + } + }; + }); + } else { + pin_status_ = "Internal error"; + pin_in_progress_ = false; + } + } + ImGui::EndDisabled(); + } + ImGui::End(); + } + + // ---- Remove PIN dialog ---- + if (show_pin_remove_) { + ImGui::SetNextWindowSize(ImVec2(400, 220), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Remove PIN##PinRemoveDlg", &show_pin_remove_, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking)) { + ImGui::TextWrapped( + "Enter your current PIN to confirm removal. " + "You will need to use your full passphrase to unlock."); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Current PIN:"); + ImGui::PushItemWidth(-1); + ImGui::InputText("##pin_remove", pin_old_buf_, sizeof(pin_old_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopItemWidth(); + + if (!pin_status_.empty()) { + ImGui::TextColored(ImVec4(1, 0.7f, 0, 1), "%s", pin_status_.c_str()); + } + + ImGui::Spacing(); + bool valid = strlen(pin_old_buf_) >= 4; + ImGui::BeginDisabled(!valid || pin_in_progress_); + if (ImGui::Button("Remove PIN", ImVec2(-1, 40))) { + pin_in_progress_ = true; + pin_status_ = "Verifying PIN..."; + std::string oldPin(pin_old_buf_); + memset(pin_old_buf_, 0, sizeof(pin_old_buf_)); + + if (worker_ && vault_) { + worker_->post([this, oldPin]() -> rpc::RPCWorker::MainCb { + // Argon2id runs here (worker thread) + std::string passphrase; + bool ok = vault_->retrieve(oldPin, passphrase); + if (ok) { + util::SecureVault::secureZero(&passphrase[0], passphrase.size()); + } + return [this, ok]() { + if (ok) { + vault_->removeVault(); + settings_->setPinEnabled(false); + settings_->save(); + pin_status_.clear(); + pin_in_progress_ = false; + show_pin_remove_ = false; + ui::Notifications::instance().info("PIN removed"); + } else { + pin_status_ = "Incorrect PIN"; + pin_in_progress_ = false; + } + }; + }); + } else { + pin_status_ = "Internal error"; + pin_in_progress_ = false; + } + } + ImGui::EndDisabled(); + } + ImGui::End(); + } +} + +} // namespace dragonx diff --git a/src/app_wizard.cpp b/src/app_wizard.cpp new file mode 100644 index 0000000..e376426 --- /dev/null +++ b/src/app_wizard.cpp @@ -0,0 +1,1274 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// app_wizard.cpp — First-run setup wizard +// Split from app.cpp for maintainability. + +#include "app.h" +#include "rpc/rpc_client.h" +#include "rpc/rpc_worker.h" +#include "rpc/connection.h" +#include "config/settings.h" +#include "daemon/embedded_daemon.h" +#include "ui/notifications.h" +#include "ui/material/color_theme.h" +#include "ui/material/type.h" +#include "ui/material/typography.h" +#include "ui/material/draw_helpers.h" +#include "ui/schema/ui_schema.h" +#include "ui/schema/skin_manager.h" +#include "ui/effects/low_spec.h" +#include "ui/windows/balance_tab.h" +#include "util/platform.h" +#include "util/bootstrap.h" +#include "util/secure_vault.h" +#include "util/i18n.h" +#include "util/perf_log.h" +#include "embedded/IconsMaterialDesign.h" +#include "resources/embedded_resources.h" + +#include "imgui.h" +#include +#include +#include +#include +#include + +namespace dragonx { + +using json = nlohmann::json; + +void App::restartWizard() +{ + DEBUG_LOGF("[App] Restarting setup wizard — stopping daemon...\n"); + + // Reset crash counter for fresh wizard attempt + if (embedded_daemon_) { + embedded_daemon_->resetCrashCount(); + } + + // Disconnect RPC + if (rpc_ && rpc_->isConnected()) { + rpc_->disconnect(); + } + onDisconnected("Wizard restart"); + + // Stop the embedded daemon in a background thread to avoid + // blocking the UI for up to 32 seconds (RPC stop + process wait). + if (embedded_daemon_ && isEmbeddedDaemonRunning()) { + std::thread([this]() { + stopEmbeddedDaemon(); + }).detach(); + } + + // Enter wizard — the wizard completion handler already calls + // startEmbeddedDaemon() + tryConnect(), so no extra logic needed. + wizard_phase_ = WizardPhase::Appearance; +} + + +// =========================================================================== +// First-Run Wizard Rendering +// =========================================================================== + +void App::renderFirstRunWizard() { + ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->WorkPos); + ImGui::SetNextWindowSize(viewport->WorkSize); + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + ImGui::Begin("##FirstRunWizard", nullptr, flags); + ImGui::PopStyleVar(); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 winPos = ImGui::GetWindowPos(); + ImVec2 winSize = ImGui::GetWindowSize(); + + // Background fill + ImU32 bgCol = ui::material::Surface(); + dl->AddRectFilled(winPos, ImVec2(winPos.x + winSize.x, winPos.y + winSize.y), bgCol); + + // Handle Done/None — wizard complete + if (wizard_phase_ == WizardPhase::Done || wizard_phase_ == WizardPhase::None) { + wizard_phase_ = WizardPhase::None; + if (!state_.connected) { + if (isUsingEmbeddedDaemon() && !isEmbeddedDaemonRunning()) { + startEmbeddedDaemon(); + } + tryConnect(); + } + settings_->setWizardCompleted(true); + settings_->save(); + ImGui::End(); + return; + } + + // --- Determine which of the 3 masonry sections is focused --- + // 0 = Appearance, 1 = Bootstrap, 2 = Encrypt + PIN + int focusIdx = 0; + switch (wizard_phase_) { + case WizardPhase::Appearance: focusIdx = 0; break; + case WizardPhase::BootstrapOffer: + case WizardPhase::BootstrapInProgress: + case WizardPhase::BootstrapFailed: + focusIdx = 1; break; + case WizardPhase::EncryptOffer: + case WizardPhase::EncryptInProgress: + case WizardPhase::PinSetup: + focusIdx = 2; break; + default: focusIdx = 0; break; + } + + // Card visual state: 0 = not-reached, 1 = focused, 2 = completed + auto cardState = [&](int idx) -> int { + if (idx < focusIdx) return 2; + if (idx == focusIdx) return 1; + return 0; + }; + + // --- Fonts & Colors --- + const auto& S = ui::schema::UI(); + ImFont* titleFont = S.resolveFont(S.label("screens.first-run", "title").font); + if (!titleFont) titleFont = ui::material::Type().h5(); + ImFont* bodyFont = S.resolveFont(S.label("screens.first-run", "subtitle").font); + if (!bodyFont) bodyFont = ui::material::Type().body1(); + ImFont* captionFont = S.resolveFont(S.label("screens.first-run", "trust-warning").font); + if (!captionFont) captionFont = ui::material::Type().caption(); + + ImU32 textCol = ui::material::OnSurface(); + ImU32 dimCol = (textCol & 0x00FFFFFF) | (IM_COL32_A_MASK & IM_COL32(0,0,0,180)); + ImFont* iconFont = ui::material::Type().iconSmall(); + if (!iconFont) iconFont = captionFont; + + // DPI scale factor — multiply all pixel constants by dp + const float dp = ui::Layout::dpiScale(); + + // --- Header: Logo + Welcome --- + float headerCy = winPos.y + 20.0f * dp; + float logoSize = S.drawElement("screens.first-run", "logo").sizeOr(56.0f); + if (logo_tex_ != 0) { + float aspect = (logo_h_ > 0) ? (float)logo_w_ / (float)logo_h_ : 1.0f; + float logoW = logoSize * aspect; + float logoX = winPos.x + (winSize.x - logoW) * 0.5f; + dl->AddImage(logo_tex_, ImVec2(logoX, headerCy), ImVec2(logoX + logoW, headerCy + logoSize)); + } + headerCy += logoSize + 8.0f * dp; + + { + const char* welcomeTitle = "Welcome to ObsidianDragon!"; + ImVec2 wts = titleFont->CalcTextSizeA(titleFont->LegacySize, FLT_MAX, 0, welcomeTitle); + dl->AddText(titleFont, titleFont->LegacySize, + ImVec2(winPos.x + (winSize.x - wts.x) * 0.5f, headerCy), textCol, welcomeTitle); + headerCy += wts.y + 16.0f * dp; + } + + // --- Masonry: 2 columns --- + // Left column: Card 0 (Appearance) on top, Card 2 (Encrypt+PIN) below + // Right column: Card 1 (Bootstrap) + float totalW = std::min(920.0f * dp, winSize.x - 40.0f * dp); + float gap = 16.0f * dp; + float colW = (totalW - gap) * 0.5f; + float areaX = winPos.x + (winSize.x - totalW) * 0.5f; + float leftX = areaX; + float rightX = areaX + colW + gap; + float cardPad = 24.0f * dp; + float cardRound = 12.0f * dp; + float topY = headerCy; + + // Step icon helper + auto stepIcon = [](int state) -> const char* { + return (state == 2) ? ICON_MD_CHECK_CIRCLE : + (state == 1) ? ICON_MD_RADIO_BUTTON_CHECKED : + ICON_MD_RADIO_BUTTON_UNCHECKED; + }; + + // Split draw list: 0 = backgrounds, 1 = content, 2 = overlays/borders + dl->ChannelsSplit(3); + dl->ChannelsSetCurrent(1); + + // Helper: finalize card — draw background, accent border or dim overlay + auto finalizeCard = [&](float cardX_, float cardW_, float ytop, float ybot, int state) { + ImVec2 cMin(cardX_, ytop); + ImVec2 cMax(cardX_ + cardW_, ybot); + + // Background (channel 0) + dl->ChannelsSetCurrent(0); + if (state == 1) { + // Focused card: subtle drop shadow + float shadowOff = 3.0f * dp; + dl->AddRectFilled( + ImVec2(cMin.x + shadowOff, cMin.y + shadowOff), ImVec2(cMax.x + shadowOff, cMax.y + shadowOff), + IM_COL32(0, 0, 0, 35), cardRound); + } + // Use DrawGlassPanel for proper acrylic/opacity/noise/theme effects + ui::material::GlassPanelSpec glass; + glass.rounding = cardRound; + ui::material::DrawGlassPanel(dl, cMin, cMax, glass); + + // Overlays & borders (channel 2) + dl->ChannelsSetCurrent(2); + if (state == 1) { + // Focused: accent border + dl->AddRect(cMin, cMax, ui::material::Primary(), cardRound, 0, 2.0f * dp); + } else if (state == 2) { + // Completed: dim overlay (preserves color) + dl->AddRectFilled(cMin, cMax, (bgCol & 0x00FFFFFF) | IM_COL32(0, 0, 0, 110), cardRound); + } else { + // Not reached: heavy overlay (creates greyscale look) + dl->AddRectFilled(cMin, cMax, (bgCol & 0x00FFFFFF) | IM_COL32(0, 0, 0, 165), cardRound); + } + + dl->ChannelsSetCurrent(1); + }; + + + // ======================= CARD 0: Appearance ======================= + float card0Top = topY; + float card0Bot; + { + int state = cardState(0); + bool isFocused = (state == 1); + float cx = leftX + cardPad; + float cy = card0Top + cardPad; + float contentW = colW - 2 * cardPad; + + // Step indicator + { + float iconW = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, stepIcon(state)).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), dimCol, stepIcon(state)); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx + iconW + 4.0f * dp, cy), dimCol, "Step 1"); + cy += captionFont->LegacySize + 6.0f * dp; + } + + // Title + { + const char* t = "Appearance"; + dl->AddText(titleFont, titleFont->LegacySize, ImVec2(cx, cy), textCol, t); + cy += titleFont->LegacySize + 10.0f * dp; + } + + // Separator + dl->AddLine(ImVec2(cx, cy), ImVec2(cx + contentW, cy), + (textCol & 0x00FFFFFF) | IM_COL32(0,0,0,40), 1.0f * dp); + cy += 14.0f * dp; + + // Statics for appearance settings + static float wiz_blur_amount = 1.5f; + static bool wiz_theme_effects = true; + static float wiz_ui_opacity = 1.0f; + static bool wiz_low_spec = false; + static bool wiz_scanline = true; + static std::string wiz_balance_layout = "classic"; + static int wiz_language_index = 0; + static bool wiz_appearance_init = false; + if (!wiz_appearance_init) { + wiz_blur_amount = settings_->getBlurMultiplier(); + wiz_theme_effects = settings_->getThemeEffectsEnabled(); + wiz_ui_opacity = settings_->getUIOpacity(); + wiz_low_spec = settings_->getLowSpecMode(); + wiz_scanline = settings_->getScanlineEnabled(); + wiz_balance_layout = settings_->getBalanceLayout(); + // Find current language index + const auto& wiz_languages = util::I18n::instance().getAvailableLanguages(); + std::string wiz_cur_lang = settings_->getLanguage(); + if (wiz_cur_lang.empty()) wiz_cur_lang = "en"; + int idx = 0; + for (const auto& lang : wiz_languages) { + if (lang.first == wiz_cur_lang) { wiz_language_index = idx; break; } + idx++; + } + // Apply loaded settings to runtime so visuals match slider values + ui::effects::setLowSpecMode(wiz_low_spec); + ui::effects::ImGuiAcrylic::ApplyBlurAmount(wiz_blur_amount); + ui::effects::ImGuiAcrylic::SetUIOpacity(wiz_ui_opacity); + ui::effects::ThemeEffects::instance().setEnabled(wiz_theme_effects); + ui::effects::ThemeEffects::instance().setReducedTransparency(!wiz_theme_effects); + ui::ConsoleTab::s_scanline_enabled = wiz_scanline; + wiz_appearance_init = true; + } + + // Render controls always so content is visible under the dim + // overlay when not focused; disable interaction when not active. + ImGui::BeginDisabled(!isFocused); + + // --- Theme combo --- + { + auto& skinMgr = ui::schema::SkinManager::instance(); + const auto& skins = skinMgr.available(); + std::string activePreview = "DragonX"; + for (const auto& skin : skins) { + if (skin.id == skinMgr.activeSkinId()) { activePreview = skin.name; break; } + } + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy + 4.0f * dp), textCol, "Theme"); + float comboX = cx + 110.0f * dp; + float comboW = contentW - 110.0f * dp; + ImGui::SetCursorScreenPos(ImVec2(comboX, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + ImGui::SetNextItemWidth(comboW); + if (ImGui::BeginCombo("##wiz_theme", activePreview.c_str())) { + ImGui::TextDisabled("Built-in"); + ImGui::Separator(); + for (const auto& skin : skins) { + if (!skin.bundled) continue; + bool sel = (skin.id == skinMgr.activeSkinId()); + if (ImGui::Selectable(skin.name.c_str(), sel)) { + skinMgr.setActiveSkin(skin.id); + settings_->setSkinId(skin.id); + settings_->save(); + } + if (sel) ImGui::SetItemDefaultFocus(); + } + bool hasCustom = false; + for (const auto& skin : skins) { if (!skin.bundled) { hasCustom = true; break; } } + if (hasCustom) { + ImGui::Spacing(); + ImGui::TextDisabled("Custom"); + ImGui::Separator(); + for (const auto& skin : skins) { + if (skin.bundled) continue; + bool sel = (skin.id == skinMgr.activeSkinId()); + if (!skin.valid) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1,0.3f,0.3f,1)); + ImGui::BeginDisabled(true); + ImGui::Selectable((skin.name + " (invalid)").c_str(), false); + ImGui::EndDisabled(); + ImGui::PopStyleColor(); + } else { + std::string lbl = skin.name; + if (!skin.author.empty()) lbl += " (" + skin.author + ")"; + if (ImGui::Selectable(lbl.c_str(), sel)) { + skinMgr.setActiveSkin(skin.id); + settings_->setSkinId(skin.id); + settings_->save(); + } + if (sel) ImGui::SetItemDefaultFocus(); + } + } + } + ImGui::EndCombo(); + } + ImGui::PopStyleVar(); + cy += bodyFont->LegacySize + 16.0f * dp; + } + + // --- Balance Layout combo --- + { + const auto& layouts = ui::GetBalanceLayouts(); + std::string balPreview = wiz_balance_layout; + for (const auto& l : layouts) { + if (l.id == wiz_balance_layout) { balPreview = l.name; break; } + } + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy + 4.0f * dp), textCol, "Balance Layout"); + float comboX = cx + 110.0f * dp; + float comboW = contentW - 110.0f * dp; + ImGui::SetCursorScreenPos(ImVec2(comboX, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + ImGui::SetNextItemWidth(comboW); + if (ImGui::BeginCombo("##wiz_layout", balPreview.c_str())) { + for (const auto& l : layouts) { + if (!l.enabled) continue; + bool sel = (l.id == wiz_balance_layout); + if (ImGui::Selectable(l.name.c_str(), sel)) { + wiz_balance_layout = l.id; + settings_->setBalanceLayout(wiz_balance_layout); + settings_->save(); + } + if (sel) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + ImGui::PopStyleVar(); + cy += bodyFont->LegacySize + 16.0f * dp; + } + + // --- Language combo --- + { + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::vector langNames; + langNames.reserve(languages.size()); + for (const auto& lang : languages) langNames.push_back(lang.second.c_str()); + + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy + 4.0f * dp), textCol, "Language"); + float comboX = cx + 110.0f * dp; + float comboW = contentW - 110.0f * dp; + ImGui::SetCursorScreenPos(ImVec2(comboX, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + ImGui::SetNextItemWidth(comboW); + if (ImGui::Combo("##wiz_lang", &wiz_language_index, langNames.data(), + static_cast(langNames.size()))) { + auto it = languages.begin(); + std::advance(it, wiz_language_index); + i18n.loadLanguage(it->first); + } + ImGui::PopStyleVar(); + cy += bodyFont->LegacySize + 20.0f * dp; + } + + // --- Low-spec mode checkbox --- + // Snapshot for restoring settings when low-spec is turned off + static struct { bool valid; float blur; float uiOp; bool fx; bool scanline; } wiz_lsSnap = {}; + + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + if (ImGui::Checkbox("##wiz_lowspec", &wiz_low_spec)) { + ui::effects::setLowSpecMode(wiz_low_spec); + if (wiz_low_spec) { + // Save current effect settings before zeroing + wiz_lsSnap.valid = true; + wiz_lsSnap.blur = wiz_blur_amount; + wiz_lsSnap.uiOp = wiz_ui_opacity; + wiz_lsSnap.fx = wiz_theme_effects; + wiz_lsSnap.scanline = wiz_scanline; + // Disable all heavy effects + wiz_blur_amount = 0.0f; + wiz_ui_opacity = 1.0f; + wiz_theme_effects = false; + wiz_scanline = false; + ui::effects::ImGuiAcrylic::ApplyBlurAmount(0.0f); + ui::effects::ImGuiAcrylic::SetUIOpacity(1.0f); + settings_->setWindowOpacity(1.0f); + ui::effects::ThemeEffects::instance().setEnabled(false); + ui::effects::ThemeEffects::instance().setReducedTransparency(true); + ui::ConsoleTab::s_scanline_enabled = false; + } else if (wiz_lsSnap.valid) { + // Restore previous effect settings + wiz_blur_amount = wiz_lsSnap.blur; + wiz_ui_opacity = wiz_lsSnap.uiOp; + wiz_theme_effects = wiz_lsSnap.fx; + wiz_scanline = wiz_lsSnap.scanline; + ui::effects::ImGuiAcrylic::ApplyBlurAmount(wiz_blur_amount); + ui::effects::ImGuiAcrylic::SetUIOpacity(wiz_ui_opacity); + ui::effects::ThemeEffects::instance().setEnabled(wiz_theme_effects); + ui::effects::ThemeEffects::instance().setReducedTransparency(false); + ui::ConsoleTab::s_scanline_enabled = wiz_scanline; + wiz_lsSnap.valid = false; + } + // Persist immediately so effects read correct values + settings_->setAcrylicEnabled(wiz_blur_amount > 0.001f); + settings_->setAcrylicQuality(wiz_blur_amount > 0.001f + ? static_cast(ui::effects::AcrylicQuality::Low) + : static_cast(ui::effects::AcrylicQuality::Off)); + settings_->setBlurMultiplier(wiz_blur_amount); + settings_->setUIOpacity(wiz_ui_opacity); + settings_->setThemeEffectsEnabled(wiz_theme_effects); + settings_->setScanlineEnabled(wiz_scanline); + settings_->setLowSpecMode(wiz_low_spec); + settings_->save(); + } + ImGui::PopStyleVar(); + ImGui::SameLine(); + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, cy + 2.0f * dp), textCol, + "Low-spec mode"); + cy += bodyFont->LegacySize + 6.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx + 28.0f * dp, cy), dimCol, "Disable all heavy visual effects"); + cy += captionFont->LegacySize + 16.0f * dp; + + ImGui::BeginDisabled(wiz_low_spec); + + // Acrylic blur slider + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(cx, cy + 2.0f * dp), textCol, + "Acrylic glass effects"); + cy += bodyFont->LegacySize + 4.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx, cy), dimCol, "Translucent blur on panels (Off disables)"); + cy += captionFont->LegacySize + 10.0f * dp; + + { + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx + 4.0f * dp, cy), textCol, "Level:"); + ImGui::SetCursorScreenPos(ImVec2(cx + 72.0f * dp, cy - 2.0f * dp)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + float sliderW = contentW - 72.0f * dp; + ImGui::SetNextItemWidth(std::max(80.0f * dp, sliderW)); + { + char blur_fmt[16]; + if (wiz_blur_amount < 0.01f) + snprintf(blur_fmt, sizeof(blur_fmt), "Off"); + else + snprintf(blur_fmt, sizeof(blur_fmt), "%.0f%%%%", wiz_blur_amount * 25.0f); + if (ImGui::SliderFloat("##wiz_blur", &wiz_blur_amount, 0.0f, 4.0f, blur_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + if (wiz_blur_amount > 0.0f && wiz_blur_amount < 0.15f) wiz_blur_amount = 0.0f; + ui::effects::ImGuiAcrylic::ApplyBlurAmount(wiz_blur_amount); + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) { + settings_->setAcrylicEnabled(wiz_blur_amount > 0.001f); + settings_->setAcrylicQuality(wiz_blur_amount > 0.001f + ? static_cast(ui::effects::AcrylicQuality::Low) + : static_cast(ui::effects::AcrylicQuality::Off)); + settings_->setBlurMultiplier(wiz_blur_amount); + settings_->save(); + } + ImGui::PopStyleVar(); + cy += bodyFont->LegacySize + 16.0f * dp; + } + + // Theme effects checkbox + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + if (ImGui::Checkbox("##wiz_fx", &wiz_theme_effects)) { + ui::effects::ThemeEffects::instance().setEnabled(wiz_theme_effects); + ui::effects::ThemeEffects::instance().setReducedTransparency(!wiz_theme_effects); + settings_->setThemeEffectsEnabled(wiz_theme_effects); + settings_->save(); + } + ImGui::PopStyleVar(); + ImGui::SameLine(); + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, cy + 2.0f * dp), textCol, + "Theme visual effects"); + cy += bodyFont->LegacySize + 6.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx + 28.0f * dp, cy), dimCol, "Animated borders, color wash"); + cy += captionFont->LegacySize + 16.0f * dp; + + // UI Opacity slider + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(cx, cy + 2.0f * dp), textCol, + "UI Opacity"); + cy += bodyFont->LegacySize + 4.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx, cy), dimCol, "Card & sidebar transparency (1.0 = solid)"); + cy += captionFont->LegacySize + 10.0f * dp; + { + ImGui::SetCursorScreenPos(ImVec2(cx, cy - 2.0f * dp)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + ImGui::SetNextItemWidth(std::max(80.0f * dp, contentW)); + if (ImGui::SliderFloat("##wiz_ui_opacity", &wiz_ui_opacity, 0.3f, 1.0f, "%.2f")) { + ui::effects::ImGuiAcrylic::SetUIOpacity(wiz_ui_opacity); + } + if (ImGui::IsItemDeactivatedAfterEdit()) { + settings_->setUIOpacity(wiz_ui_opacity); + settings_->save(); + } + ImGui::PopStyleVar(); + cy += bodyFont->LegacySize + 16.0f * dp; + } + + // Console scanline checkbox + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + if (ImGui::Checkbox("##wiz_scanline", &wiz_scanline)) { + ui::ConsoleTab::s_scanline_enabled = wiz_scanline; + settings_->setScanlineEnabled(wiz_scanline); + settings_->save(); + } + ImGui::PopStyleVar(); + ImGui::SameLine(); + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, cy + 2.0f * dp), textCol, + "Console scanline"); + cy += bodyFont->LegacySize + 6.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, + ImVec2(cx + 28.0f * dp, cy), dimCol, "CRT scanline effect in console"); + cy += captionFont->LegacySize + 24.0f * dp; + + ImGui::EndDisabled(); // low-spec + + ImGui::EndDisabled(); // !isFocused + + // Continue button (only when focused) + if (isFocused) { + float btnW = 140.0f * dp; + float btnH = 40.0f * dp; + float btnX = leftX + (colW - btnW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(btnX, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Continue##app", ImVec2(btnW, btnH))) { + // Save appearance choices, advance to Bootstrap + settings_->setAcrylicEnabled(wiz_blur_amount > 0.001f); + settings_->setAcrylicQuality(wiz_blur_amount > 0.001f + ? static_cast(ui::effects::AcrylicQuality::Low) + : static_cast(ui::effects::AcrylicQuality::Off)); + settings_->setBlurMultiplier(wiz_blur_amount); + settings_->setThemeEffectsEnabled(wiz_theme_effects); + settings_->setUIOpacity(wiz_ui_opacity); + settings_->setLowSpecMode(wiz_low_spec); + settings_->setScanlineEnabled(wiz_scanline); + settings_->setBalanceLayout(wiz_balance_layout); + settings_->save(); + wizard_phase_ = WizardPhase::BootstrapOffer; + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + cy += btnH; + } + + cy += cardPad; + // Lock card height to the tallest content ever seen + static float card0MaxH = 0.0f; + card0MaxH = std::max(card0MaxH, cy - card0Top); + card0Bot = card0Top + card0MaxH; + + // Card 0 finalization deferred until after cards 1+2 are sized + } + + + // ======================= CARD 1: Bootstrap ======================= + float card1Top = topY; + float card1Bot; + { + int state = cardState(1); + bool isFocused = (state == 1); + bool isCollapsed = (state == 2 && cardState(2) == 1); // Minimize when step 3 active + float cx = rightX + cardPad; + float cy = card1Top + cardPad; + float contentW = colW - 2 * cardPad; + + // Step indicator + title (inline when collapsed) + if (isCollapsed) { + // Compact single-line: icon + "Step 2" + "Bootstrap" + checkmark + float iconW = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, stepIcon(state)).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), dimCol, stepIcon(state)); + float labelX = cx + iconW + 4.0f * dp; + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(labelX, cy), dimCol, "Step 2"); + float step2W = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, 0, "Step 2").x; + float titleX = labelX + step2W + 12.0f * dp; + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(titleX, cy), dimCol, "Bootstrap"); + cy += captionFont->LegacySize + 4.0f * dp; + } else { + // Step indicator + { + float iconW = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, stepIcon(state)).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), dimCol, stepIcon(state)); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx + iconW + 4.0f * dp, cy), dimCol, "Step 2"); + cy += captionFont->LegacySize + 4.0f * dp; + } + + // Title + { + const char* t = "Bootstrap"; + dl->AddText(titleFont, titleFont->LegacySize, ImVec2(cx, cy), textCol, t); + cy += titleFont->LegacySize + 6.0f * dp; + } + + // Separator + dl->AddLine(ImVec2(cx, cy), ImVec2(cx + contentW, cy), + (textCol & 0x00FFFFFF) | IM_COL32(0,0,0,40), 1.0f * dp); + cy += 10.0f * dp; + } + + // --- Content varies by sub-state (only when focused, skip when collapsed) --- + if (isCollapsed) { + // No content — card is minimized + } else if (isFocused && wizard_phase_ == WizardPhase::BootstrapInProgress) { + // ---- Bootstrap download in progress ---- + if (!bootstrap_) { + wizard_phase_ = WizardPhase::EncryptOffer; + } else { + auto prog = bootstrap_->getProgress(); + + const char* statusTitle = (prog.state == util::Bootstrap::State::Downloading) + ? "Downloading bootstrap..." : "Extracting blockchain data..."; + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), textCol, statusTitle); + cy += bodyFont->LegacySize + 12.0f * dp; + + // Progress bar + float barH = 8.0f * dp, barR = 4.0f * dp; + dl->AddRectFilled(ImVec2(cx, cy), ImVec2(cx + contentW, cy + barH), + IM_COL32(255,255,255,30), barR); + float fillW = contentW * (prog.percent / 100.0f); + if (fillW > 0) { + dl->AddRectFilled(ImVec2(cx, cy), ImVec2(cx + fillW, cy + barH), + ui::material::Primary(), barR); + } + cy += barH + 8.0f * dp; + + // Status text + percent + { + char pctText[64]; + snprintf(pctText, sizeof(pctText), "%.1f%%", prog.percent); + ImVec2 pts = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, 0, pctText); + dl->AddText(bodyFont, bodyFont->LegacySize, + ImVec2(cx + contentW - pts.x, cy), textCol, pctText); + } + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, + prog.status_text.c_str()); + cy += bodyFont->LegacySize + 6.0f * dp; + + if (prog.state == util::Bootstrap::State::Extracting) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + dimCol, "(wallet.dat is protected)"); + cy += captionFont->LegacySize + 6.0f * dp; + } + cy += 12.0f * dp; + + // Cancel button + float cancelW = 100.0f * dp; + float cancelH = 36.0f * dp; + float cancelBX = rightX + (colW - cancelW) * 0.5f; + ImGui::SetCursorScreenPos(ImVec2(cancelBX, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Cancel##bs", ImVec2(cancelW, cancelH))) { + bootstrap_->cancel(); + } + ImGui::PopStyleVar(); + cy += cancelH; + + // Check completion + if (bootstrap_->isDone()) { + auto finalProg = bootstrap_->getProgress(); + if (finalProg.state == util::Bootstrap::State::Completed) { + bootstrap_.reset(); + wizard_phase_ = WizardPhase::EncryptOffer; + } else { + wizard_phase_ = WizardPhase::BootstrapFailed; + } + } + } + + } else if (isFocused && wizard_phase_ == WizardPhase::BootstrapFailed) { + // ---- Bootstrap failed ---- + std::string errMsg; + if (bootstrap_) { + errMsg = bootstrap_->getProgress().error; + bootstrap_.reset(); + } + if (errMsg.empty()) errMsg = "Bootstrap failed"; + + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), + ui::material::Error(), "Download Failed"); + cy += bodyFont->LegacySize + 8.0f * dp; + + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), textCol, + errMsg.c_str()); + cy += captionFont->LegacySize + 16.0f * dp; + + // Retry / Skip + float btnW2 = 120.0f * dp; + float btnH2 = 40.0f * dp; + float totalBW = btnW2 * 2 + 12.0f * dp; + float bx = rightX + (colW - totalBW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(bx, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Retry##bs", ImVec2(btnW2, btnH2))) { + bootstrap_ = std::make_unique(); + std::string dataDir = util::Platform::getDragonXDataDir(); + bootstrap_->start(dataDir); + wizard_phase_ = WizardPhase::BootstrapInProgress; + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + + ImGui::SetCursorScreenPos(ImVec2(bx + btnW2 + 12.0f * dp, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Skip##bsfail", ImVec2(btnW2, btnH2))) { + wizard_phase_ = WizardPhase::EncryptOffer; + } + ImGui::PopStyleVar(); + cy += btnH2; + + } else { + // ---- Bootstrap offer (default view, also for non-focused) ---- + + // External daemon check (async — avoids blocking UI thread). + // On Windows isRpcPortInUse() creates a TCP socket + connect() + // which can block for seconds when the port is not listening. + bool externalRunning = false; + if (isFocused) { + static std::atomic s_extCached{false}; + static std::atomic s_checkInFlight{false}; + static double s_extLastCheck = -10.0; + double now = ImGui::GetTime(); + if (now - s_extLastCheck >= 2.0 && !s_checkInFlight.load()) { + s_extLastCheck = now; + bool embeddedRunning = isEmbeddedDaemonRunning(); + s_checkInFlight.store(true); + std::thread([embeddedRunning]() { + bool inUse = daemon::EmbeddedDaemon::isRpcPortInUse(); + s_extCached.store(inUse && !embeddedRunning); + s_checkInFlight.store(false); + }).detach(); + } + externalRunning = s_extCached.load(); + } + + if (isFocused && (externalRunning || wizard_stopping_external_)) { + // --- External daemon warning --- + ImU32 warnCol = ui::material::Warning(); + { + float iw = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, ICON_MD_WARNING).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), warnCol, ICON_MD_WARNING); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx + iw + 4.0f * dp, cy), warnCol, "External daemon running"); + } + cy += bodyFont->LegacySize + 4.0f * dp; + { + const char* warnBody = "It must be stopped before downloading a bootstrap, otherwise chain data could be corrupted."; + ImVec2 ws = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, contentW, warnBody); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), textCol, warnBody, nullptr, contentW); + cy += ws.y + 12.0f * dp; + } + + if (wizard_stopping_external_) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, + wizard_stop_status_.c_str()); + cy += captionFont->LegacySize + 8.0f * dp; + } else { + float stopW = 150.0f * dp; + float skipW2 = 100.0f * dp; + float btnH2 = 40.0f * dp; + float totalBW = stopW + 12.0f * dp + skipW2; + float bx = rightX + (colW - totalBW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(bx, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Error())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4( + IM_COL32(220, 60, 60, 255))); + ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 255, 255, 255)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Stop Daemon##wiz", ImVec2(stopW, btnH2))) { + wizard_stopping_external_ = true; + wizard_stop_status_ = "Sending stop command..."; + if (wizard_stop_thread_.joinable()) wizard_stop_thread_.join(); + wizard_stop_thread_ = std::thread([this]() { + auto config = rpc::Connection::autoDetectConfig(); + if (!config.rpcuser.empty() && !config.rpcpassword.empty()) { + auto tmp_rpc = std::make_unique(); + if (tmp_rpc->connect(config.host, config.port, + config.rpcuser, config.rpcpassword)) { + try { tmp_rpc->call("stop"); } catch (...) {} + tmp_rpc->disconnect(); + } + } + wizard_stop_status_ = "Waiting for daemon to shut down..."; + for (int i = 0; i < 60; i++) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (!daemon::EmbeddedDaemon::isRpcPortInUse()) { + wizard_stop_status_ = "Daemon stopped."; + wizard_stopping_external_ = false; + return; + } + } + wizard_stop_status_ = "Daemon did not stop — try manually."; + wizard_stopping_external_ = false; + }); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + + ImGui::SetCursorScreenPos(ImVec2(bx + stopW + 12.0f * dp, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Skip##extd", ImVec2(skipW2, btnH2))) { + wizard_phase_ = WizardPhase::EncryptOffer; + } + ImGui::PopStyleVar(); + cy += btnH2; + } + } else { + // --- Normal bootstrap offer --- + { + const char* bsText = "Download a blockchain bootstrap to dramatically speed up initial sync.\n\nYour existing wallet.dat will NOT be modified or replaced."; + ImVec2 bsSize = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, contentW, bsText); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), textCol, bsText, nullptr, contentW); + cy += bsSize.y + 8.0f * dp; + } + + // Trust warning + { + float warnOpacity = S.drawElement("screens.first-run", "trust-warning").opacity; + if (warnOpacity <= 0) warnOpacity = 0.7f; + ImU32 warnCol = (textCol & 0x00FFFFFF) | ((ImU32)(255 * warnOpacity) << 24); + float iw = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, ICON_MD_WARNING).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), warnCol, ICON_MD_WARNING); + const char* twText = "Only use bootstrap.dragonx.is. Using files from untrusted sources could compromise your node."; + float twWrap = contentW - iw - 4.0f * dp; + ImVec2 twSize = captionFont->CalcTextSizeA(captionFont->LegacySize, FLT_MAX, twWrap, twText); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx + iw + 4.0f * dp, cy), warnCol, twText, nullptr, twWrap); + cy += twSize.y + 12.0f * dp; + } + + // Buttons (only when focused) + if (isFocused) { + float dlBtnW = 180.0f * dp; + float skipW2 = 80.0f * dp; + float btnH2 = 40.0f * dp; + float totalBW = dlBtnW + 12.0f * dp + skipW2; + float bx = rightX + (colW - totalBW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(bx, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Download##bs", ImVec2(dlBtnW, btnH2))) { + bootstrap_ = std::make_unique(); + std::string dataDir = util::Platform::getDragonXDataDir(); + bootstrap_->start(dataDir); + wizard_phase_ = WizardPhase::BootstrapInProgress; + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + + ImGui::SetCursorScreenPos(ImVec2(bx + dlBtnW + 12.0f * dp, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Skip##bs", ImVec2(skipW2, btnH2))) { + wizard_phase_ = WizardPhase::EncryptOffer; + } + ImGui::PopStyleVar(); + cy += btnH2; + } + } + } + + cy += cardPad; + // Lock card height to the tallest content ever seen (but not when collapsed) + static float card1MaxH = 0.0f; + if (isCollapsed) { + card1Bot = card1Top + (cy - card1Top); + } else { + card1MaxH = std::max(card1MaxH, cy - card1Top); + card1Bot = card1Top + card1MaxH; + } + + finalizeCard(rightX, colW, card1Top, card1Bot, state); + } + + + // ======================= CARD 2: Encrypt + PIN ======================= + float card2Top = card1Bot + gap; + float card2Bot; + { + int state = cardState(2); + bool isFocused = (state == 1); + float cx = rightX + cardPad; + float cy = card2Top + cardPad; + float contentW = colW - 2 * cardPad; + + // Pre-start daemon when encrypt card becomes focused so it's ready + // by the time the user finishes typing their passphrase + if (isFocused) { + static bool wiz_daemon_prestarted = false; + if (!wiz_daemon_prestarted) { + wiz_daemon_prestarted = true; + if (!state_.connected && isUsingEmbeddedDaemon() && !isEmbeddedDaemonRunning()) { + startEmbeddedDaemon(); + } + if (!state_.connected && !connection_in_progress_) { + tryConnect(); + } + } + } + + // Step indicator + { + float iconW = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, stepIcon(state)).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), dimCol, stepIcon(state)); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx + iconW + 4.0f * dp, cy), dimCol, "Step 3"); + cy += captionFont->LegacySize + 4.0f * dp; + } + + // Title (changes for PinSetup sub-state) + { + const char* t = (isFocused && wizard_phase_ == WizardPhase::PinSetup) + ? "Quick-Unlock PIN" : "Encryption"; + dl->AddText(titleFont, titleFont->LegacySize, ImVec2(cx, cy), textCol, t); + cy += titleFont->LegacySize + 6.0f * dp; + } + + // Separator + dl->AddLine(ImVec2(cx, cy), ImVec2(cx + contentW, cy), + (textCol & 0x00FFFFFF) | IM_COL32(0,0,0,40), 1.0f * dp); + cy += 10.0f * dp; + + // --- Content varies by sub-state --- + if (isFocused && state_.isEncrypted()) { + // ---- Wallet already encrypted ---- + { + ImU32 okCol = ui::material::Secondary(); + float iw = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, ICON_MD_VERIFIED_USER).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), okCol, ICON_MD_VERIFIED_USER); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx + iw + 6.0f * dp, cy), okCol, "Wallet is already encrypted"); + cy += bodyFont->LegacySize + 12.0f * dp; + } + { + const char* desc = "Your wallet is protected with a passphrase. No further action is needed."; + ImVec2 ds = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, contentW, desc); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), textCol, desc, nullptr, contentW); + cy += ds.y + 20.0f * dp; + } + + // Continue button — skip to Done + float btnW2 = 140.0f * dp; + float btnH2 = 40.0f * dp; + float bx = rightX + (colW - btnW2) * 0.5f; + ImGui::SetCursorScreenPos(ImVec2(bx, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(ui::material::Primary())); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Continue##encok", ImVec2(btnW2, btnH2))) { + wizard_phase_ = WizardPhase::Done; + settings_->setWizardCompleted(true); + settings_->save(); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + cy += btnH2; + + } else if (isFocused) { + // ---- Encryption offer + optional PIN (combined) ---- + { + const char* encDesc = "Encrypt your wallet to protect private keys with a passphrase."; + ImVec2 edSize = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, contentW, encDesc); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), textCol, encDesc, nullptr, contentW); + cy += edSize.y + 6.0f * dp; + } + { + ImU32 warnCol2 = ui::material::Warning(); + float iw = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, ICON_MD_WARNING).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx, cy), warnCol2, ICON_MD_WARNING); + const char* warnLoss = "If you lose your passphrase, you lose access to your funds."; + float wlWrap = contentW - iw - 4.0f * dp; + ImVec2 wlSize = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, wlWrap, warnLoss); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx + iw + 4.0f * dp, cy), warnCol2, warnLoss, nullptr, wlWrap); + cy += wlSize.y + 8.0f * dp; + } + + // Passphrase input + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, "Passphrase:"); + cy += captionFont->LegacySize + 4.0f * dp; + + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushItemWidth(contentW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f * dp); + ImGui::InputText("##wiz_pass", encrypt_pass_buf_, sizeof(encrypt_pass_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + cy += 36.0f * dp + 6.0f * dp; + + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, "Confirm:"); + cy += captionFont->LegacySize + 4.0f * dp; + + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushItemWidth(contentW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f * dp); + ImGui::InputText("##wiz_confirm", encrypt_confirm_buf_, sizeof(encrypt_confirm_buf_), + ImGuiInputTextFlags_Password); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + cy += 36.0f * dp + 6.0f * dp; + + // Strength meter + { + size_t len = strlen(encrypt_pass_buf_); + const char* strengthLabel = "Weak"; + ImU32 strengthCol = ui::material::Error(); + float strengthPct = 0.25f; + + if (len >= 16) { + strengthLabel = "Strong"; strengthCol = ui::material::Secondary(); strengthPct = 1.0f; + } else if (len >= 12) { + strengthLabel = "Good"; strengthCol = ui::material::Secondary(); strengthPct = 0.75f; + } else if (len >= 8) { + strengthLabel = "Fair"; strengthCol = ui::material::Warning(); strengthPct = 0.5f; + } + + float sBarH = 4.0f * dp, sBarR = 2.0f * dp; + dl->AddRectFilled(ImVec2(cx, cy), ImVec2(cx + contentW, cy + sBarH), + IM_COL32(255,255,255,30), sBarR); + if (len > 0) { + dl->AddRectFilled(ImVec2(cx, cy), ImVec2(cx + contentW * strengthPct, cy + sBarH), + strengthCol, sBarR); + } + cy += sBarH + 4.0f * dp; + + char slabel[64]; + snprintf(slabel, sizeof(slabel), "Strength: %s", strengthLabel); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, slabel); + cy += captionFont->LegacySize + 10.0f * dp; + } + + // Feedback on why Encrypt is disabled + { + size_t pLen = strlen(encrypt_pass_buf_); + if (pLen > 0 && pLen < 8) { + char fb[80]; + snprintf(fb, sizeof(fb), "Passphrase must be at least 8 characters (%zu/8)", pLen); + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + ui::material::Error(), fb); + cy += captionFont->LegacySize + 6.0f * dp; + } else if (pLen >= 8 && strlen(encrypt_confirm_buf_) > 0 && + strcmp(encrypt_pass_buf_, encrypt_confirm_buf_) != 0) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + ui::material::Error(), "Passphrases do not match"); + cy += captionFont->LegacySize + 6.0f * dp; + } + } + + // ---- Optional PIN section ---- + cy += 4.0f * dp; + dl->AddLine(ImVec2(cx, cy), ImVec2(cx + contentW, cy), + (textCol & 0x00FFFFFF) | IM_COL32(0,0,0,40), 1.0f * dp); + cy += 8.0f * dp; + + { + const char* pinTitle = "Quick-Unlock PIN (optional)"; + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), textCol, pinTitle); + cy += captionFont->LegacySize + 4.0f * dp; + } + + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, "PIN (4-8 digits):"); + cy += captionFont->LegacySize + 4.0f * dp; + + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushItemWidth(contentW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f * dp); + ImGui::InputText("##wiz_pin", wizard_pin_buf_, sizeof(wizard_pin_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + cy += 36.0f * dp + 6.0f * dp; + + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), dimCol, "Confirm PIN:"); + cy += captionFont->LegacySize + 4.0f * dp; + + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::PushItemWidth(contentW); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 6.0f * dp); + ImGui::InputText("##wiz_pin_confirm", wizard_pin_confirm_buf_, sizeof(wizard_pin_confirm_buf_), + ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsDecimal); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + cy += 36.0f * dp + 6.0f * dp; + + // PIN validation feedback + { + std::string pinStr(wizard_pin_buf_); + if (!pinStr.empty() && !util::SecureVault::isValidPin(pinStr)) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + ui::material::Error(), "PIN must be 4-8 digits"); + cy += captionFont->LegacySize + 6.0f * dp; + } else if (!pinStr.empty() && strlen(wizard_pin_confirm_buf_) > 0 && + pinStr != std::string(wizard_pin_confirm_buf_)) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + ui::material::Error(), "PINs do not match"); + cy += captionFont->LegacySize + 6.0f * dp; + } + } + + // Status + if (!encrypt_status_.empty()) { + dl->AddText(captionFont, captionFont->LegacySize, ImVec2(cx, cy), + ui::material::Warning(), encrypt_status_.c_str()); + cy += captionFont->LegacySize + 6.0f * dp; + } + + // Buttons + { + bool passValid = strlen(encrypt_pass_buf_) >= 8 && + strcmp(encrypt_pass_buf_, encrypt_confirm_buf_) == 0; + // PIN is optional: if entered, must be valid + confirmed + std::string pinStr(wizard_pin_buf_); + bool pinEntered = !pinStr.empty(); + bool pinOk = !pinEntered || + (util::SecureVault::isValidPin(pinStr) && + pinStr == std::string(wizard_pin_confirm_buf_)); + bool canEncrypt = passValid && pinOk && !encrypt_in_progress_; + + float encBtnW = 180.0f * dp; + float skipW2 = 80.0f * dp; + float btnH2 = 40.0f * dp; + float totalBW = encBtnW + 12.0f * dp + skipW2; + float bx = rightX + (colW - totalBW) * 0.5f; + + ImGui::SetCursorScreenPos(ImVec2(bx, cy)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4( + canEncrypt ? ui::material::Primary() : IM_COL32(128,128,128,128))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(ui::material::PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::material::OnPrimary())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + ImGui::BeginDisabled(!canEncrypt); + if (ImGui::Button("Encrypt & Continue##wiz", ImVec2(encBtnW, btnH2))) { + // Save passphrase + optional PIN for background processing + deferred_encrypt_passphrase_ = std::string(encrypt_pass_buf_); + if (pinEntered && pinOk) + deferred_encrypt_pin_ = pinStr; + deferred_encrypt_pending_ = true; + + // Clear sensitive buffers + memset(encrypt_pass_buf_, 0, sizeof(encrypt_pass_buf_)); + memset(encrypt_confirm_buf_, 0, sizeof(encrypt_confirm_buf_)); + memset(wizard_pin_buf_, 0, sizeof(wizard_pin_buf_)); + memset(wizard_pin_confirm_buf_, 0, sizeof(wizard_pin_confirm_buf_)); + + // Start daemon + finish wizard immediately + if (!isEmbeddedDaemonRunning() && isUsingEmbeddedDaemon()) { + startEmbeddedDaemon(); + } + tryConnect(); + wizard_phase_ = WizardPhase::Done; + settings_->setWizardCompleted(true); + settings_->save(); + ui::Notifications::instance().info("Encryption will complete in the background"); + } + ImGui::EndDisabled(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + + ImGui::SetCursorScreenPos(ImVec2(bx + encBtnW + 12.0f * dp, cy)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f * dp); + if (ImGui::Button("Skip##enc", ImVec2(skipW2, btnH2))) { + wizard_phase_ = WizardPhase::Done; + settings_->setWizardCompleted(true); + settings_->save(); + if (!isEmbeddedDaemonRunning() && isUsingEmbeddedDaemon()) { + startEmbeddedDaemon(); + } + tryConnect(); + } + ImGui::PopStyleVar(); + cy += btnH2; + } + } else { + // ---- Not focused: show static description ---- + const char* encDesc = "Encrypt your wallet to protect private keys with a passphrase."; + ImVec2 edSize = bodyFont->CalcTextSizeA(bodyFont->LegacySize, FLT_MAX, contentW, encDesc); + dl->AddText(bodyFont, bodyFont->LegacySize, ImVec2(cx, cy), dimCol, encDesc, nullptr, contentW); + cy += edSize.y + 6.0f * dp; + } + + cy += cardPad; + { + card2Bot = card2Top + (cy - card2Top); + // Stretch card 2 so its bottom sits flush with card 0 (left column) + if (card0Bot > card2Bot) + card2Bot = card0Bot; + } + + finalizeCard(rightX, colW, card2Top, card2Bot, state); + } + + // --- Deferred Card 0 finalization: match right column total height --- + { + float rightColBot = card2Bot; + if (rightColBot > card0Bot) card0Bot = rightColBot; + finalizeCard(leftX, colW, card0Top, card0Bot, cardState(0)); + } + + // Merge channels: backgrounds → content → overlays + dl->ChannelsMerge(); + + ImGui::End(); +} + +} // namespace dragonx diff --git a/src/config/settings.cpp b/src/config/settings.cpp new file mode 100644 index 0000000..15985b3 --- /dev/null +++ b/src/config/settings.cpp @@ -0,0 +1,242 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "settings.h" +#include "version.h" + +#include +#include +#include + +#include "../util/logger.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +namespace fs = std::filesystem; +using json = nlohmann::json; + +namespace dragonx { +namespace config { + +Settings::Settings() = default; +Settings::~Settings() = default; + +std::string Settings::getDefaultPath() +{ +#ifdef _WIN32 + char path[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, path))) { + std::string dir = std::string(path) + "\\ObsidianDragon"; + fs::create_directories(dir); + return dir + "\\settings.json"; + } + return "settings.json"; +#elif defined(__APPLE__) + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + std::string dir = std::string(home) + "/Library/Application Support/ObsidianDragon"; + fs::create_directories(dir); + return dir + "/settings.json"; +#else + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + std::string dir = std::string(home) + "/.config/ObsidianDragon"; + fs::create_directories(dir); + return dir + "/settings.json"; +#endif +} + +bool Settings::load() +{ + return load(getDefaultPath()); +} + +bool Settings::load(const std::string& path) +{ + settings_path_ = path; + + std::ifstream file(path); + if (!file.is_open()) { + return false; + } + + try { + json j; + file >> j; + + if (j.contains("theme")) theme_ = j["theme"].get(); + if (j.contains("save_ztxs")) save_ztxs_ = j["save_ztxs"].get(); + if (j.contains("auto_shield")) auto_shield_ = j["auto_shield"].get(); + if (j.contains("use_tor")) use_tor_ = j["use_tor"].get(); + if (j.contains("allow_custom_fees")) allow_custom_fees_ = j["allow_custom_fees"].get(); + if (j.contains("default_fee")) default_fee_ = j["default_fee"].get(); + if (j.contains("fetch_prices")) fetch_prices_ = j["fetch_prices"].get(); + if (j.contains("tx_explorer_url")) tx_explorer_url_ = j["tx_explorer_url"].get(); + if (j.contains("address_explorer_url")) address_explorer_url_ = j["address_explorer_url"].get(); + if (j.contains("language")) language_ = j["language"].get(); + if (j.contains("skin_id")) skin_id_ = j["skin_id"].get(); + if (j.contains("acrylic_enabled")) acrylic_enabled_ = j["acrylic_enabled"].get(); + if (j.contains("acrylic_quality")) acrylic_quality_ = j["acrylic_quality"].get(); + if (j.contains("blur_multiplier")) blur_multiplier_ = j["blur_multiplier"].get(); + if (j.contains("noise_opacity")) noise_opacity_ = j["noise_opacity"].get(); + if (j.contains("gradient_background")) gradient_background_ = j["gradient_background"].get(); + // Migrate legacy reduced_transparency bool -> ui_opacity float + if (j.contains("ui_opacity")) { + ui_opacity_ = j["ui_opacity"].get(); + } else if (j.contains("reduced_transparency") && j["reduced_transparency"].get()) { + ui_opacity_ = 1.0f; // legacy: reduced = fully opaque + } + if (j.contains("window_opacity")) window_opacity_ = j["window_opacity"].get(); + if (j.contains("balance_layout")) { + if (j["balance_layout"].is_string()) + balance_layout_ = j["balance_layout"].get(); + else if (j["balance_layout"].is_number_integer()) { + // Legacy migration: convert old int index to string ID + static const char* legacyIds[] = { + "classic","donut","consolidated","dashboard", + "vertical-stack","shield","timeline","two-row","minimal" + }; + int idx = j["balance_layout"].get(); + if (idx >= 0 && idx < 9) balance_layout_ = legacyIds[idx]; + } + } + if (j.contains("scanline_enabled")) scanline_enabled_ = j["scanline_enabled"].get(); + if (j.contains("hidden_addresses") && j["hidden_addresses"].is_array()) { + hidden_addresses_.clear(); + for (const auto& a : j["hidden_addresses"]) + if (a.is_string()) hidden_addresses_.insert(a.get()); + } + if (j.contains("favorite_addresses") && j["favorite_addresses"].is_array()) { + favorite_addresses_.clear(); + for (const auto& a : j["favorite_addresses"]) + if (a.is_string()) favorite_addresses_.insert(a.get()); + } + if (j.contains("wizard_completed")) wizard_completed_ = j["wizard_completed"].get(); + if (j.contains("auto_lock_timeout")) auto_lock_timeout_ = j["auto_lock_timeout"].get(); + if (j.contains("unlock_duration")) unlock_duration_ = j["unlock_duration"].get(); + if (j.contains("pin_enabled")) pin_enabled_ = j["pin_enabled"].get(); + if (j.contains("keep_daemon_running")) keep_daemon_running_ = j["keep_daemon_running"].get(); + if (j.contains("stop_external_daemon")) stop_external_daemon_ = j["stop_external_daemon"].get(); + if (j.contains("debug_categories") && j["debug_categories"].is_array()) { + debug_categories_.clear(); + for (const auto& c : j["debug_categories"]) + if (c.is_string()) debug_categories_.insert(c.get()); + } + if (j.contains("theme_effects_enabled")) theme_effects_enabled_ = j["theme_effects_enabled"].get(); + if (j.contains("low_spec_mode")) low_spec_mode_ = j["low_spec_mode"].get(); + if (j.contains("selected_exchange")) selected_exchange_ = j["selected_exchange"].get(); + if (j.contains("selected_pair")) selected_pair_ = j["selected_pair"].get(); + if (j.contains("pool_url")) pool_url_ = j["pool_url"].get(); + if (j.contains("pool_algo")) pool_algo_ = j["pool_algo"].get(); + if (j.contains("pool_worker")) pool_worker_ = j["pool_worker"].get(); + if (j.contains("pool_threads")) pool_threads_ = j["pool_threads"].get(); + if (j.contains("pool_tls")) pool_tls_ = j["pool_tls"].get(); + if (j.contains("pool_hugepages")) pool_hugepages_ = j["pool_hugepages"].get(); + if (j.contains("pool_mode")) pool_mode_ = j["pool_mode"].get(); + if (j.contains("window_width") && j["window_width"].is_number_integer()) + window_width_ = j["window_width"].get(); + if (j.contains("window_height") && j["window_height"].is_number_integer()) + window_height_ = j["window_height"].get(); + + return true; + } catch (const std::exception& e) { + DEBUG_LOGF("Failed to parse settings: %s\n", e.what()); + return false; + } +} + +bool Settings::save() +{ + if (settings_path_.empty()) { + settings_path_ = getDefaultPath(); + } + return save(settings_path_); +} + +bool Settings::save(const std::string& path) +{ + json j; + + j["theme"] = theme_; + j["save_ztxs"] = save_ztxs_; + j["auto_shield"] = auto_shield_; + j["use_tor"] = use_tor_; + j["allow_custom_fees"] = allow_custom_fees_; + j["default_fee"] = default_fee_; + j["fetch_prices"] = fetch_prices_; + j["tx_explorer_url"] = tx_explorer_url_; + j["address_explorer_url"] = address_explorer_url_; + j["language"] = language_; + j["skin_id"] = skin_id_; + j["acrylic_enabled"] = acrylic_enabled_; + j["acrylic_quality"] = acrylic_quality_; + j["blur_multiplier"] = blur_multiplier_; + j["noise_opacity"] = noise_opacity_; + j["gradient_background"] = gradient_background_; + j["ui_opacity"] = ui_opacity_; + j["window_opacity"] = window_opacity_; + j["balance_layout"] = balance_layout_; // saved as string ID + j["scanline_enabled"] = scanline_enabled_; + j["hidden_addresses"] = json::array(); + for (const auto& addr : hidden_addresses_) + j["hidden_addresses"].push_back(addr); + j["favorite_addresses"] = json::array(); + for (const auto& addr : favorite_addresses_) + j["favorite_addresses"].push_back(addr); + j["wizard_completed"] = wizard_completed_; + j["auto_lock_timeout"] = auto_lock_timeout_; + j["unlock_duration"] = unlock_duration_; + j["pin_enabled"] = pin_enabled_; + j["keep_daemon_running"] = keep_daemon_running_; + j["stop_external_daemon"] = stop_external_daemon_; + j["debug_categories"] = json::array(); + for (const auto& cat : debug_categories_) + j["debug_categories"].push_back(cat); + j["theme_effects_enabled"] = theme_effects_enabled_; + j["low_spec_mode"] = low_spec_mode_; + j["selected_exchange"] = selected_exchange_; + j["selected_pair"] = selected_pair_; + j["pool_url"] = pool_url_; + j["pool_algo"] = pool_algo_; + j["pool_worker"] = pool_worker_; + j["pool_threads"] = pool_threads_; + j["pool_tls"] = pool_tls_; + j["pool_hugepages"] = pool_hugepages_; + j["pool_mode"] = pool_mode_; + if (window_width_ > 0 && window_height_ > 0) { + j["window_width"] = window_width_; + j["window_height"] = window_height_; + } + + try { + // Ensure directory exists + fs::path p(path); + fs::create_directories(p.parent_path()); + + std::ofstream file(path); + if (!file.is_open()) { + return false; + } + + file << j.dump(4); + return true; + } catch (const std::exception& e) { + DEBUG_LOGF("Failed to save settings: %s\n", e.what()); + return false; + } +} + +} // namespace config +} // namespace dragonx diff --git a/src/config/settings.h b/src/config/settings.h new file mode 100644 index 0000000..8d4542f --- /dev/null +++ b/src/config/settings.h @@ -0,0 +1,263 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include + +namespace dragonx { +namespace config { + +/** + * @brief Application settings manager + * + * Handles loading and saving of user preferences. + */ +class Settings { +public: + Settings(); + ~Settings(); + + /** + * @brief Load settings from default location + * @return true if loaded successfully + */ + bool load(); + + /** + * @brief Load settings from specific path + * @param path Path to settings file + * @return true if loaded successfully + */ + bool load(const std::string& path); + + /** + * @brief Save settings to default location + * @return true if saved successfully + */ + bool save(); + + /** + * @brief Save settings to specific path + * @param path Path to settings file + * @return true if saved successfully + */ + bool save(const std::string& path); + + /** + * @brief Get default settings file path + */ + static std::string getDefaultPath(); + + // Theme + std::string getTheme() const { return theme_; } + void setTheme(const std::string& theme) { theme_ = theme; } + + // Unified skin + std::string getSkinId() const { return skin_id_; } + void setSkinId(const std::string& id) { skin_id_ = id; } + + // Privacy + bool getSaveZtxs() const { return save_ztxs_; } + void setSaveZtxs(bool save) { save_ztxs_ = save; } + + bool getAutoShield() const { return auto_shield_; } + void setAutoShield(bool shield) { auto_shield_ = shield; } + + bool getUseTor() const { return use_tor_; } + void setUseTor(bool tor) { use_tor_ = tor; } + + // Fees + bool getAllowCustomFees() const { return allow_custom_fees_; } + void setAllowCustomFees(bool allow) { allow_custom_fees_ = allow; } + + double getDefaultFee() const { return default_fee_; } + void setDefaultFee(double fee) { default_fee_ = fee; } + + // Price + bool getFetchPrices() const { return fetch_prices_; } + void setFetchPrices(bool fetch) { fetch_prices_ = fetch; } + + // Explorer URLs + std::string getTxExplorerUrl() const { return tx_explorer_url_; } + void setTxExplorerUrl(const std::string& url) { tx_explorer_url_ = url; } + + std::string getAddressExplorerUrl() const { return address_explorer_url_; } + void setAddressExplorerUrl(const std::string& url) { address_explorer_url_ = url; } + + // Language + std::string getLanguage() const { return language_; } + void setLanguage(const std::string& lang) { language_ = lang; } + + // Visual effects + bool getAcrylicEnabled() const { return acrylic_enabled_; } + void setAcrylicEnabled(bool v) { acrylic_enabled_ = v; } + + int getAcrylicQuality() const { return acrylic_quality_; } + void setAcrylicQuality(int v) { acrylic_quality_ = v; } + + float getBlurMultiplier() const { return blur_multiplier_; } + void setBlurMultiplier(float v) { blur_multiplier_ = v; } + + bool getReducedTransparency() const { return ui_opacity_ >= 0.99f; } + void setReducedTransparency(bool v) { if (v) ui_opacity_ = 1.0f; } + + float getUIOpacity() const { return ui_opacity_; } + void setUIOpacity(float v) { ui_opacity_ = std::max(0.3f, std::min(1.0f, v)); } + + float getWindowOpacity() const { return window_opacity_; } + void setWindowOpacity(float v) { window_opacity_ = std::max(0.3f, std::min(1.0f, v)); } + + float getNoiseOpacity() const { return noise_opacity_; } + void setNoiseOpacity(float v) { noise_opacity_ = v; } + + // Gradient background mode (use gradient variant of theme background) + bool getGradientBackground() const { return gradient_background_; } + void setGradientBackground(bool v) { gradient_background_ = v; } + + // Balance layout (string ID, e.g. "classic", "donut") + std::string getBalanceLayout() const { return balance_layout_; } + void setBalanceLayout(const std::string& v) { balance_layout_ = v; } + + // Console scanline effect + bool getScanlineEnabled() const { return scanline_enabled_; } + void setScanlineEnabled(bool v) { scanline_enabled_ = v; } + + // Hidden addresses (addresses hidden from the UI by the user) + const std::set& getHiddenAddresses() const { return hidden_addresses_; } + bool isAddressHidden(const std::string& addr) const { return hidden_addresses_.count(addr) > 0; } + void hideAddress(const std::string& addr) { hidden_addresses_.insert(addr); } + void unhideAddress(const std::string& addr) { hidden_addresses_.erase(addr); } + int getHiddenAddressCount() const { return (int)hidden_addresses_.size(); } + + // Favorite addresses (pinned to top of address list) + const std::set& getFavoriteAddresses() const { return favorite_addresses_; } + bool isAddressFavorite(const std::string& addr) const { return favorite_addresses_.count(addr) > 0; } + void favoriteAddress(const std::string& addr) { favorite_addresses_.insert(addr); } + void unfavoriteAddress(const std::string& addr) { favorite_addresses_.erase(addr); } + int getFavoriteAddressCount() const { return (int)favorite_addresses_.size(); } + + // First-run wizard + bool getWizardCompleted() const { return wizard_completed_; } + void setWizardCompleted(bool v) { wizard_completed_ = v; } + + // Security — auto-lock timeout (seconds; 0 = disabled) + int getAutoLockTimeout() const { return auto_lock_timeout_; } + void setAutoLockTimeout(int seconds) { auto_lock_timeout_ = seconds; } + + // Security — unlock duration (seconds) for walletpassphrase + int getUnlockDuration() const { return unlock_duration_; } + void setUnlockDuration(int seconds) { unlock_duration_ = seconds; } + + // Security — PIN unlock enabled + bool getPinEnabled() const { return pin_enabled_; } + void setPinEnabled(bool v) { pin_enabled_ = v; } + + // Daemon — keep running in background when closing the app + bool getKeepDaemonRunning() const { return keep_daemon_running_; } + void setKeepDaemonRunning(bool v) { keep_daemon_running_ = v; } + + // Daemon — stop externally-started daemons on exit (default: false) + bool getStopExternalDaemon() const { return stop_external_daemon_; } + void setStopExternalDaemon(bool v) { stop_external_daemon_ = v; } + + // Daemon — debug logging categories + const std::set& getDebugCategories() const { return debug_categories_; } + void setDebugCategories(const std::set& cats) { debug_categories_ = cats; } + bool hasDebugCategory(const std::string& cat) const { return debug_categories_.count(cat) > 0; } + void toggleDebugCategory(const std::string& cat) { + if (debug_categories_.count(cat)) debug_categories_.erase(cat); + else debug_categories_.insert(cat); + } + + // Visual effects — animated theme effects (hue cycling, shimmer, glow, etc.) + bool getThemeEffectsEnabled() const { return theme_effects_enabled_; } + void setThemeEffectsEnabled(bool v) { theme_effects_enabled_ = v; } + + // Low-spec mode — disables heavy visual effects for better performance + bool getLowSpecMode() const { return low_spec_mode_; } + void setLowSpecMode(bool v) { low_spec_mode_ = v; } + + // Market — last selected exchange + pair + std::string getSelectedExchange() const { return selected_exchange_; } + void setSelectedExchange(const std::string& v) { selected_exchange_ = v; } + std::string getSelectedPair() const { return selected_pair_; } + void setSelectedPair(const std::string& v) { selected_pair_ = v; } + + // Pool mining + std::string getPoolUrl() const { return pool_url_; } + void setPoolUrl(const std::string& v) { pool_url_ = v; } + std::string getPoolAlgo() const { return pool_algo_; } + void setPoolAlgo(const std::string& v) { pool_algo_ = v; } + std::string getPoolWorker() const { return pool_worker_; } + void setPoolWorker(const std::string& v) { pool_worker_ = v; } + int getPoolThreads() const { return pool_threads_; } + void setPoolThreads(int v) { pool_threads_ = v; } + bool getPoolTls() const { return pool_tls_; } + void setPoolTls(bool v) { pool_tls_ = v; } + bool getPoolHugepages() const { return pool_hugepages_; } + void setPoolHugepages(bool v) { pool_hugepages_ = v; } + bool getPoolMode() const { return pool_mode_; } + void setPoolMode(bool v) { pool_mode_ = v; } + + // Window size persistence (logical pixels at 1x scale) + int getWindowWidth() const { return window_width_; } + int getWindowHeight() const { return window_height_; } + void setWindowSize(int w, int h) { window_width_ = w; window_height_ = h; } + +private: + std::string settings_path_; + + // Settings values + std::string theme_ = "dragonx"; + std::string skin_id_ = "dragonx"; + bool save_ztxs_ = true; + bool auto_shield_ = true; + bool use_tor_ = false; + bool allow_custom_fees_ = false; + double default_fee_ = 0.0001; + bool fetch_prices_ = true; + std::string tx_explorer_url_ = "https://explorer.dragonx.is/tx/"; + std::string address_explorer_url_ = "https://explorer.dragonx.is/address/"; + std::string language_ = "en"; + bool acrylic_enabled_ = true; + int acrylic_quality_ = 2; + float blur_multiplier_ = 0.10f; + float noise_opacity_ = 0.5f; + bool gradient_background_ = false; + float ui_opacity_ = 0.50f; // Card/sidebar opacity (0.3–1.0, 1.0 = opaque) + float window_opacity_ = 0.75f; // Background alpha (0.3–1.0, <1 = desktop visible) + std::string balance_layout_ = "classic"; + bool scanline_enabled_ = true; + std::set hidden_addresses_; + std::set favorite_addresses_; + bool wizard_completed_ = false; + int auto_lock_timeout_ = 900; // 15 minutes + int unlock_duration_ = 600; // 10 minutes + bool pin_enabled_ = false; + bool keep_daemon_running_ = false; + bool stop_external_daemon_ = false; + std::set debug_categories_; + bool theme_effects_enabled_ = true; + bool low_spec_mode_ = false; + std::string selected_exchange_ = "TradeOgre"; + std::string selected_pair_ = "DRGX/BTC"; + + // Pool mining + std::string pool_url_ = "pool.dragonx.is"; + std::string pool_algo_ = "rx/hush"; + std::string pool_worker_ = "x"; + int pool_threads_ = 0; + bool pool_tls_ = false; + bool pool_hugepages_ = true; + bool pool_mode_ = false; // false=solo, true=pool + + // Window size (logical pixels at 1x scale; 0 = use default 1200×775) + int window_width_ = 0; + int window_height_ = 0; +}; + +} // namespace config +} // namespace dragonx diff --git a/src/config/version.h b/src/config/version.h new file mode 100644 index 0000000..ea631cf --- /dev/null +++ b/src/config/version.h @@ -0,0 +1,28 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#define DRAGONX_VERSION "1.0.0" +#define DRAGONX_VERSION_MAJOR 1 +#define DRAGONX_VERSION_MINOR 0 +#define DRAGONX_VERSION_PATCH 0 + +#define DRAGONX_APP_NAME "ObsidianDragon" +#define DRAGONX_ORG_NAME "Hush" + +// Default RPC settings +#define DRAGONX_DEFAULT_RPC_HOST "127.0.0.1" +#define DRAGONX_DEFAULT_RPC_PORT "21769" + +// Coin parameters +#define DRAGONX_TICKER "DRGX" +#define DRAGONX_COIN_NAME "DragonX" +#define DRAGONX_URI_SCHEME "drgx" +#define DRAGONX_ZATOSHI_PER_COIN 100000000 +#define DRAGONX_DEFAULT_FEE 0.0001 + +// Config file names +#define DRAGONX_CONF_FILENAME "DRAGONX.conf" +#define DRAGONX_WALLET_FILENAME "wallet.dat" diff --git a/src/daemon/embedded_daemon.cpp b/src/daemon/embedded_daemon.cpp new file mode 100644 index 0000000..3206203 --- /dev/null +++ b/src/daemon/embedded_daemon.cpp @@ -0,0 +1,1011 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "embedded_daemon.h" +#include "../config/version.h" +#include "../resources/embedded_resources.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "../util/logger.h" + +#ifdef _WIN32 +#include +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace fs = std::filesystem; + +namespace dragonx { +namespace daemon { + +EmbeddedDaemon::EmbeddedDaemon() = default; + +EmbeddedDaemon::~EmbeddedDaemon() +{ + stop(3000); // Wait up to 3 seconds for clean shutdown +} + +std::string EmbeddedDaemon::findDaemonBinary() +{ + // Get the directory where the wallet binary is located + std::string exe_dir; +#ifdef _WIN32 + char exe_path[MAX_PATH]; + GetModuleFileNameA(NULL, exe_path, MAX_PATH); + exe_dir = fs::path(exe_path).parent_path().string(); +#else + char exe_path[4096]; + ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); + if (len != -1) { + exe_path[len] = '\0'; + exe_dir = fs::path(exe_path).parent_path().string(); + } +#endif + + // --------------------------------------------------------------- + // 1. Check wallet's own directory first — allows bundling binaries + // alongside the wallet executable (highest priority). + // --------------------------------------------------------------- + if (!exe_dir.empty()) { +#ifdef _WIN32 + // Check wallet's own directory for manually placed binaries + std::vector localPaths = { + exe_dir + "\\hushd.exe", + exe_dir + "\\hush-arrakis-chain.exe", + exe_dir + "\\dragonxd.exe", + exe_dir + "\\dragonxd.bat", + }; +#else + std::vector localPaths = { + exe_dir + "/hush-arrakis-chain", + exe_dir + "/hushd", + exe_dir + "/dragonxd", + }; +#endif + for (const auto& path : localPaths) { + if (fs::exists(path)) { + DEBUG_LOGF("[INFO] Found daemon in wallet directory: %s\n", path.c_str()); + return path; + } + } + } + + // --------------------------------------------------------------- + // 2. Check if we have an embedded daemon that needs extraction + // --------------------------------------------------------------- + std::string embeddedPath = resources::getDaemonPath(); + if (!embeddedPath.empty() && fs::exists(embeddedPath)) { + DEBUG_LOGF("[INFO] Using extracted daemon at: %s\n", embeddedPath.c_str()); + return embeddedPath; + } + + // --------------------------------------------------------------- + // 3. Search additional well-known locations + // --------------------------------------------------------------- + // IMPORTANT: Always prefer hushd.exe directly over dragonxd.bat + // Using .bat files causes issues because cmd.exe exits immediately + // while hushd.exe continues running, making process monitoring fail. + std::vector search_paths; + +#ifdef _WIN32 + // Parent directory + if (!exe_dir.empty()) { + search_paths.push_back(exe_dir + "\\..\\hushd.exe"); + search_paths.push_back(exe_dir + "\\..\\dragonxd.bat"); + search_paths.push_back(exe_dir + "\\..\\dragonxd.exe"); + } + search_paths.push_back("C:\\Program Files\\DragonX\\hushd.exe"); +#else + if (!exe_dir.empty()) { + search_paths.push_back(exe_dir + "/../hush-arrakis-chain"); + search_paths.push_back(exe_dir + "/../bin/hush-arrakis-chain"); + search_paths.push_back(exe_dir + "/../dragonxd"); + } + + // Standard Linux locations + search_paths.push_back("/usr/local/bin/hush-arrakis-chain"); + search_paths.push_back("/usr/bin/hush-arrakis-chain"); + + // Home directory + const char* home = getenv("HOME"); + if (home) { + search_paths.push_back(std::string(home) + "/hush3/src/hush-arrakis-chain"); + search_paths.push_back(std::string(home) + "/hush3/src/dragonxd"); + search_paths.push_back(std::string(home) + "/bin/hush-arrakis-chain"); + } + +#ifdef __APPLE__ + // macOS app bundle + search_paths.push_back("/Applications/DragonX.app/Contents/MacOS/hush-arrakis-chain"); +#endif +#endif + + // Check each path + for (const auto& path : search_paths) { + if (fs::exists(path)) { + DEBUG_LOGF("[INFO] Found daemon launcher at: %s\n", path.c_str()); + return path; + } + } + + DEBUG_LOGF("[ERROR] Daemon launcher not found in any standard location\n"); + return ""; +} + +std::vector EmbeddedDaemon::getChainParams() +{ + // DragonX chain parameters. + // On Windows, omit -printtoconsole: we tail debug.log instead of piping stdout. + // On Linux, -printtoconsole is used for pipe-based output capture. + return { + "-tls=only", +#ifndef _WIN32 + "-printtoconsole", +#endif + "-clientname=DragonXImGui", + "-ac_name=DRAGONX", + "-ac_algo=randomx", + "-ac_halving=3500000", + "-ac_reward=300000000", + "-ac_blocktime=36", + "-ac_private=1", + "-addnode=176.126.87.241", + "-experimentalfeatures", + "-developerencryptwallet" + }; +} + +void EmbeddedDaemon::setState(State s, const std::string& message) +{ + state_ = s; + if (!message.empty()) { + if (s == State::Error) { + last_error_ = message; + } + } + + if (state_callback_) { + state_callback_(s, message); + } +} + +// Cap process_output_ to prevent unbounded memory growth. +// Keeps the most recent MAX_OUTPUT_BYTES, trimming at a newline boundary. +static constexpr size_t MAX_OUTPUT_BYTES = 1024 * 1024; // 1 MB + +void EmbeddedDaemon::appendOutput(const char* data, size_t len) +{ + // Caller must hold output_mutex_ + process_output_.append(data, len); + if (process_output_.size() > MAX_OUTPUT_BYTES + MAX_OUTPUT_BYTES / 4) { + // Trim to MAX_OUTPUT_BYTES, cutting at a newline boundary + size_t trim_to = process_output_.size() - MAX_OUTPUT_BYTES; + size_t nl = process_output_.find('\n', trim_to); + if (nl != std::string::npos && nl < process_output_.size() - 1) { + process_output_.erase(0, nl + 1); + } else { + process_output_.erase(0, trim_to); + } + } +} + +std::vector EmbeddedDaemon::getRecentLines(int maxLines) const +{ + std::vector lines; + std::lock_guard lk(output_mutex_); + const std::string& out = process_output_; + if (out.empty()) return lines; + + // Walk backwards collecting up to maxLines newline-delimited lines + size_t end = out.size(); + // Skip trailing newline + if (end > 0 && out[end - 1] == '\n') --end; + + for (int i = 0; i < maxLines && end > 0; ++i) { + size_t nl = out.rfind('\n', end - 1); + size_t start = (nl == std::string::npos) ? 0 : nl + 1; + std::string line = out.substr(start, end - start); + if (!line.empty()) lines.push_back(std::move(line)); + end = (nl == std::string::npos) ? 0 : nl; + } + // Reverse so oldest is first + std::reverse(lines.begin(), lines.end()); + return lines; +} + +// Check if a TCP port is already in use (something is LISTENING) +static bool isPortInUse(int port) +{ +#ifdef _WIN32 + WSADATA wsa; + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false; + SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock == INVALID_SOCKET) { WSACleanup(); return false; } + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(static_cast(port)); + addr.sin_addr.s_addr = inet_addr("127.0.0.1"); + int result = connect(sock, (struct sockaddr*)&addr, sizeof(addr)); + closesocket(sock); + WSACleanup(); + return (result == 0); +#else + // Read /proc/net/tcp to check for listeners — avoids creating sockets + // which would add conntrack entries and consume ephemeral ports. + FILE* fp = fopen("/proc/net/tcp", "r"); + if (!fp) return false; + char line[256]; + unsigned int localPort, state; + bool found = false; + while (fgets(line, sizeof(line), fp)) { + // Format: sl local_address rem_address st ... + // local_address is HEXIP:HEXPORT, state 0x0A = TCP_LISTEN + if (sscanf(line, " %*d: %*X:%X %*X:%*X %X", &localPort, &state) == 2) { + if (localPort == static_cast(port) && state == 0x0A) { + found = true; + break; + } + } + } + fclose(fp); + return found; +#endif +} + +bool EmbeddedDaemon::start(const std::string& binary_path) +{ + // Don't start if already running or starting + if (state_ == State::Starting || state_ == State::Running) { + DEBUG_LOGF("[INFO] Daemon already %s\n", state_ == State::Starting ? "starting" : "running"); + return true; + } + + if (isRunning()) { + DEBUG_LOGF("[INFO] Daemon process already running\n"); + return true; + } + + // Check if something is already listening on the RPC port + int rpc_port = std::atoi(DRAGONX_DEFAULT_RPC_PORT); + if (isPortInUse(rpc_port)) { + DEBUG_LOGF("[INFO] Port %d is already in use — external daemon detected, will connect to it.\\n", rpc_port); + external_daemon_detected_ = true; + // Don't set Error — the wallet will connect to the running daemon. + setState(State::Stopped, "External daemon detected on port " + std::string(DRAGONX_DEFAULT_RPC_PORT)); + return false; + } + external_daemon_detected_ = false; + + setState(State::Starting, "Looking for dragonxd binary..."); + + std::string daemon_path = binary_path; + if (daemon_path.empty()) { + daemon_path = findDaemonBinary(); + } + + if (daemon_path.empty() || !fs::exists(daemon_path)) { + DEBUG_LOGF("[ERROR] dragonxd binary not found\\n"); + setState(State::Error, "dragonxd binary not found.\n\nTo use embedded daemon, place dragonxd.exe (or dragonxd.bat) in the same directory as the wallet.\n\nAlternatively, start dragonxd manually and the wallet will connect to it."); + return false; + } + + DEBUG_LOGF("[INFO] Starting dragonxd from: %s\\n", daemon_path.c_str()); + + auto args = getChainParams(); + + // Append debug logging flags from user settings + for (const auto& cat : debug_categories_) { + args.push_back("-debug=" + cat); + } + + if (!startProcess(daemon_path, args)) { + DEBUG_LOGF("[ERROR] Failed to start dragonxd process: %s\\n", last_error_.c_str()); + setState(State::Error, "Failed to start dragonxd process"); + return false; + } + + setState(State::Running, "dragonxd started"); + DEBUG_LOGF("[INFO] dragonxd process started successfully\\n"); + + // Start monitor thread (if not already running) + should_stop_ = false; + if (!monitor_thread_.joinable()) { + monitor_thread_ = std::thread(&EmbeddedDaemon::monitorProcess, this); + } + + return true; +} + +#ifdef _WIN32 + +// Forward declaration — defined after startProcess +static DWORD findProcessByName(const char* name); + +bool EmbeddedDaemon::startProcess(const std::string& binary_path, const std::vector& args) +{ + // Build command line + std::string cmd = "\"" + binary_path + "\""; + for (const auto& arg : args) { + cmd += " " + arg; + } + DEBUG_LOGF("[INFO] Starting daemon: %s\n", cmd.c_str()); + + // Set working directory to the daemon binary's directory + std::string work_dir = fs::path(binary_path).parent_path().string(); + if (work_dir.empty()) { + work_dir = "."; + } + DEBUG_LOGF("[INFO] Working directory: %s\n", work_dir.c_str()); + + // Store launch info for diagnostics (shown in error messages if crash occurs) + launch_cmd_ = cmd; + launch_binary_ = binary_path; + launch_workdir_ = work_dir; + + // Log binary file size for corruption detection + { + std::error_code ec; + auto fsize = fs::file_size(binary_path, ec); + if (!ec) { + DEBUG_LOGF("[INFO] Daemon binary size: %llu bytes\n", (unsigned long long)fsize); + } + } + + // Determine debug.log path for output tailing. + // The daemon writes to %APPDATA%\Hush\DRAGONX\debug.log when -printtoconsole is NOT used. + { + char appdata[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, appdata))) { + debug_log_path_ = std::string(appdata) + "\\Hush\\DRAGONX\\debug.log"; + } else { + const char* home = getenv("APPDATA"); + if (home) { + debug_log_path_ = std::string(home) + "\\Hush\\DRAGONX\\debug.log"; + } + } + + // Record current file size so we only read NEW output from this launch + if (!debug_log_path_.empty() && fs::exists(debug_log_path_)) { + debug_log_offset_ = static_cast(fs::file_size(debug_log_path_)); + } else { + debug_log_offset_ = 0; + } + DEBUG_LOGF("[INFO] Will tail daemon output from: %s (offset %zu)\n", + debug_log_path_.c_str(), debug_log_offset_); + } + + // Launch daemon with CREATE_NEW_CONSOLE (hidden via SW_HIDE). + // The daemon binary must NOT be in the data directory (%APPDATA%\Hush\DRAGONX) + // — it must be in /hush3/ to avoid conflicts with lock files and data. + STARTUPINFOA si; + PROCESS_INFORMATION pi; + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + ZeroMemory(&pi, sizeof(pi)); + + char* cmd_line = _strdup(cmd.c_str()); + BOOL success = CreateProcessA( + NULL, + cmd_line, + NULL, + NULL, + FALSE, + CREATE_NEW_CONSOLE, + NULL, + work_dir.c_str(), + &si, + &pi + ); + free(cmd_line); + + if (!success) { + DWORD err = GetLastError(); + char errBuf[256] = {0}; + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, err, 0, errBuf, sizeof(errBuf), NULL); + last_error_ = "CreateProcess failed with error " + std::to_string(err) + ": " + errBuf; + DEBUG_LOGF("[ERROR] CreateProcess failed: error %lu - %s\nCommand: %s\n", err, errBuf, cmd.c_str()); + return false; + } + + process_handle_ = pi.hProcess; + CloseHandle(pi.hThread); + + return true; +} + +bool EmbeddedDaemon::isRunning() const +{ + if (process_handle_ == nullptr) return false; + + DWORD exit_code; + if (GetExitCodeProcess(process_handle_, &exit_code)) { + return exit_code == STILL_ACTIVE; + } + return false; +} + +// Find a running process by executable name, return its PID (0 if not found) +static DWORD findProcessByName(const char* name) +{ + HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snap == INVALID_HANDLE_VALUE) return 0; + + PROCESSENTRY32 entry; + entry.dwSize = sizeof(entry); + + DWORD pid = 0; + if (Process32First(snap, &entry)) { + do { + if (_stricmp(entry.szExeFile, name) == 0) { + pid = entry.th32ProcessID; + break; + } + } while (Process32Next(snap, &entry)); + } + CloseHandle(snap); + return pid; +} + +double EmbeddedDaemon::getMemoryUsageMB() const +{ + if (process_handle_ == nullptr) return 0.0; + + PROCESS_MEMORY_COUNTERS pmc; + ZeroMemory(&pmc, sizeof(pmc)); + pmc.cb = sizeof(pmc); + if (GetProcessMemoryInfo(process_handle_, &pmc, sizeof(pmc))) { + return static_cast(pmc.WorkingSetSize) / (1024.0 * 1024.0); + } + return 0.0; +} + +void EmbeddedDaemon::drainOutput() +{ + // Read new content from debug.log (tail-follow approach) + if (debug_log_path_.empty()) return; + + HANDLE hFile = CreateFileA(debug_log_path_.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) return; + + // Get current file size + LARGE_INTEGER fileSize; + if (!GetFileSizeEx(hFile, &fileSize)) { + CloseHandle(hFile); + return; + } + + size_t currentSize = static_cast(fileSize.QuadPart); + if (currentSize <= debug_log_offset_) { + CloseHandle(hFile); + return; // No new data + } + + // Seek to where we left off + LARGE_INTEGER seekPos; + seekPos.QuadPart = static_cast(debug_log_offset_); + SetFilePointerEx(hFile, seekPos, NULL, FILE_BEGIN); + + // Read new content in chunks + char buffer[4096]; + DWORD bytes_read; + while (debug_log_offset_ < currentSize) { + DWORD toRead = static_cast(std::min(sizeof(buffer) - 1, currentSize - debug_log_offset_)); + if (!ReadFile(hFile, buffer, toRead, &bytes_read, NULL) || bytes_read == 0) break; + + buffer[bytes_read] = '\0'; + { + std::lock_guard lk(output_mutex_); + appendOutput(buffer, bytes_read); + } + DEBUG_LOGF("[dragonxd] %s", buffer); + debug_log_offset_ += bytes_read; + } + + CloseHandle(hFile); +} + +void EmbeddedDaemon::stop(int wait_ms) +{ + should_stop_ = true; + setState(State::Stopping, "Stopping dragonxd..."); + + // Check if our tracked process handle is still alive + bool tracked_alive = false; + if (process_handle_ != nullptr) { + DWORD exit_code; + if (GetExitCodeProcess(process_handle_, &exit_code) && exit_code == STILL_ACTIVE) { + tracked_alive = true; + } + } + + // Helper: poll-wait for a process handle, draining stdout each iteration + auto pollWait = [&](HANDLE hProc, int ms) -> bool { + auto start = std::chrono::steady_clock::now(); + while (true) { + drainOutput(); + DWORD res = WaitForSingleObject(hProc, 200); + if (res == WAIT_OBJECT_0) return true; // exited + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); + if (elapsed >= ms) return false; // timeout + } + }; + + if (tracked_alive) { + // Our tracked process (hushd.exe launched directly) is still alive. + // The RPC "stop" was already sent by the caller — wait for it to exit. + DEBUG_LOGF("Waiting up to %d ms for tracked daemon process to exit...\n", wait_ms); + if (!pollWait(process_handle_, wait_ms)) { + DEBUG_LOGF("Timeout — forcing daemon termination...\n"); + TerminateProcess(process_handle_, 1); + WaitForSingleObject(process_handle_, 2000); + } + drainOutput(); + CloseHandle(process_handle_); + process_handle_ = nullptr; + } else { + // Tracked handle is dead (batch file case: cmd.exe already exited). + // The real hushd.exe may still be running as an orphan. + if (process_handle_ != nullptr) { + CloseHandle(process_handle_); + process_handle_ = nullptr; + } + + // Find the real hushd.exe process by name + DWORD hushd_pid = findProcessByName("hushd.exe"); + if (hushd_pid != 0) { + DEBUG_LOGF("Found orphaned hushd.exe (PID %lu) — waiting for RPC stop to take effect...\n", hushd_pid); + HANDLE hProc = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, hushd_pid); + if (hProc) { + // RPC stop was already sent — wait for graceful exit + if (!pollWait(hProc, wait_ms)) { + DEBUG_LOGF("Timeout — forcing hushd.exe (PID %lu) termination...\n", hushd_pid); + TerminateProcess(hProc, 1); + WaitForSingleObject(hProc, 2000); + } + drainOutput(); + CloseHandle(hProc); + DEBUG_LOGF("hushd.exe stopped\n"); + } else { + DEBUG_LOGF("Could not open hushd.exe process (PID %lu), error %lu\n", + hushd_pid, GetLastError()); + } + } else { + DEBUG_LOGF("No hushd.exe process found — daemon may have already exited\n"); + } + } + + if (stdout_read_ != nullptr) { + CloseHandle(stdout_read_); + stdout_read_ = nullptr; + } + // Final drain of debug.log + drainOutput(); + + if (monitor_thread_.joinable()) { + monitor_thread_.join(); + } + + setState(State::Stopped, "dragonxd stopped"); +} + +// Translate Windows NTSTATUS / exit codes to human-readable descriptions +static std::string translateWindowsExitCode(DWORD code) { + switch (code) { + case 0x80000003: return "STATUS_BREAKPOINT (0x80000003) — possible missing DLL or binary crash"; + case 0xC0000005: return "STATUS_ACCESS_VIOLATION (0xC0000005) — memory access violation"; + case 0xC0000135: return "STATUS_DLL_NOT_FOUND (0xC0000135) — required DLL not found"; + case 0xC000007B: return "STATUS_INVALID_IMAGE_FORMAT (0xC000007B) — wrong architecture or corrupt binary"; + case 0xC0000142: return "STATUS_DLL_INIT_FAILED (0xC0000142) — DLL initialization failed"; + case 0xC0000409: return "STATUS_STACK_BUFFER_OVERRUN (0xC0000409) — stack buffer overflow"; + case 0xC0000374: return "STATUS_HEAP_CORRUPTION (0xC0000374) — heap corruption detected"; + default: + if (code > 0x80000000) { + char buf[64]; + snprintf(buf, sizeof(buf), "exit code: 0x%08lX", code); + return std::string(buf); + } + return "exit code: " + std::to_string(code); + } +} + +void EmbeddedDaemon::monitorProcess() +{ + while (!should_stop_ && isRunning()) { + // Tail debug.log for new output + drainOutput(); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + } + + // Read any remaining output after process exits + drainOutput(); + + // Check if process exited unexpectedly + if (!should_stop_ && !isRunning()) { + // Get exit code for diagnostics + DWORD exit_code = 0; + if (process_handle_) { + GetExitCodeProcess(process_handle_, &exit_code); + } + + crash_count_++; + + // Build informative error message with full diagnostic details + std::string error_msg = "dragonxd exited unexpectedly (" + translateWindowsExitCode(exit_code) + ")"; + + // Add launch diagnostics + error_msg += "\n\nLaunch details:"; + error_msg += "\n Binary: " + launch_binary_; + error_msg += "\n Working dir: " + launch_workdir_; + error_msg += "\n Command: " + launch_cmd_; + + // Check binary file size + { + std::error_code ec; + auto fsize = fs::file_size(launch_binary_, ec); + if (!ec) { + char sizeBuf[32]; + snprintf(sizeBuf, sizeof(sizeBuf), "%llu", (unsigned long long)fsize); + error_msg += "\n Binary size: " + std::string(sizeBuf) + " bytes"; + } else { + error_msg += "\n Binary size: could not read (" + ec.message() + ")"; + } + } + + // Check if debug.log has any content from this launch + if (!debug_log_path_.empty()) { + std::error_code ec; + auto logSize = fs::file_size(debug_log_path_, ec); + if (!ec) { + size_t newBytes = (static_cast(logSize) > debug_log_offset_) + ? static_cast(logSize) - debug_log_offset_ : 0; + char logBuf[64]; + snprintf(logBuf, sizeof(logBuf), "%zu", newBytes); + error_msg += "\n debug.log new bytes: " + std::string(logBuf); + } + } + + // Include daemon output from debug.log + { + std::lock_guard lk(output_mutex_); + if (!process_output_.empty()) { + // Get last ~500 chars of output for context + std::string last_output = process_output_; + if (last_output.size() > 500) { + last_output = "..." + last_output.substr(last_output.size() - 500); + } + error_msg += "\n\nDaemon output:\n" + last_output; + } + } + + setState(State::Error, error_msg); + } +} + +#else // Linux/macOS + +bool EmbeddedDaemon::startProcess(const std::string& binary_path, const std::vector& args) +{ + // Create pipe for stdout/stderr + int pipefd[2]; + if (pipe(pipefd) == -1) { + last_error_ = "Failed to create pipe: " + std::string(strerror(errno)); + return false; + } + + pid_t pid = fork(); + if (pid == -1) { + last_error_ = "Fork failed: " + std::string(strerror(errno)); + close(pipefd[0]); + close(pipefd[1]); + return false; + } + + if (pid == 0) { + // Child process + close(pipefd[0]); // Close read end + + // Put child in its own process group so we can kill the entire + // group later (including hushd spawned by a wrapper script). + // Without this, SIGTERM only kills the shell, leaving hushd orphaned. + setpgid(0, 0); + + // Change to the daemon binary's directory so hushd can find + // sapling params via its PWD search path (same as CreateProcessA + // lpCurrentDirectory on Windows). + { + std::string daemon_dir = fs::path(binary_path).parent_path().string(); + if (!daemon_dir.empty()) { + if (chdir(daemon_dir.c_str()) != 0) { + fprintf(stderr, "chdir(%s) failed: %s\n", daemon_dir.c_str(), strerror(errno)); + } + } + } + + // Redirect stdout and stderr to pipe + dup2(pipefd[1], STDOUT_FILENO); + dup2(pipefd[1], STDERR_FILENO); + close(pipefd[1]); + + // Disable output buffering + setenv("PYTHONUNBUFFERED", "1", 1); + + // Build argv + std::vector argv; + + // Check if this is a shell script + bool is_script = false; + if (binary_path.size() >= 3) { + std::string ext = binary_path.substr(binary_path.size() - 3); + if (ext == ".sh" || binary_path.find("hush-arrakis-chain") != std::string::npos || + binary_path.find("dragonxd") != std::string::npos) { + // Check if it's a script by looking at first bytes + FILE* f = fopen(binary_path.c_str(), "r"); + if (f) { + char buf[2] = {0}; + if (fread(buf, 1, 2, f) == 2 && buf[0] == '#' && buf[1] == '!') { + is_script = true; + } + fclose(f); + } + } + } + + if (is_script) { + // Run shell scripts through bash + argv.push_back(const_cast("/bin/bash")); + argv.push_back(const_cast(binary_path.c_str())); + } else { + argv.push_back(const_cast(binary_path.c_str())); + } + + for (const auto& arg : args) { + argv.push_back(const_cast(arg.c_str())); + } + argv.push_back(nullptr); + + // Execute using execvp for PATH resolution + if (is_script) { + execv("/bin/bash", argv.data()); + } else { + execv(binary_path.c_str(), argv.data()); + } + + // If we get here, exec failed + fprintf(stderr, "execv failed: %s\n", strerror(errno)); + _exit(127); + } + + // Parent process + close(pipefd[1]); // Close write end + stdout_fd_ = pipefd[0]; + + // Also set process group from parent side (race with child's setpgid) + setpgid(pid, pid); + + // Set non-blocking + int flags = fcntl(stdout_fd_, F_GETFL, 0); + fcntl(stdout_fd_, F_SETFL, flags | O_NONBLOCK); + + process_pid_ = pid; + return true; +} + +double EmbeddedDaemon::getMemoryUsageMB() const +{ + if (process_pid_ <= 0) return 0.0; + + // The tracked PID is often a bash wrapper script; the real daemon + // (hushd) is a child in the same process group. Sum VmRSS for every + // process whose PGID matches our tracked PID. + double total_rss_mb = 0.0; + + // Iterate /proc//stat for all numeric entries + for (const auto& entry : fs::directory_iterator("/proc")) { + if (!entry.is_directory()) continue; + const std::string name = entry.path().filename().string(); + if (name.empty() || !std::isdigit(name[0])) continue; + + // Read process group from /proc//stat (field 5 is pgrp) + std::string statPath = entry.path().string() + "/stat"; + FILE* sf = fopen(statPath.c_str(), "r"); + if (!sf) continue; + + char statLine[512]; + if (!fgets(statLine, sizeof(statLine), sf)) { fclose(sf); continue; } + fclose(sf); + + // Fields in /proc//stat are space-separated, but field 2 (comm) + // is wrapped in parens and may contain spaces. Skip past ')'. + const char* p = strrchr(statLine, ')'); + if (!p) continue; + p++; // skip ')' + + // After ')' the fields are: state(3), ppid(4), pgrp(5), ... + int pgrp = 0; + char state; + int ppid; + if (sscanf(p, " %c %d %d", &state, &ppid, &pgrp) != 3) continue; + if (pgrp != process_pid_) continue; + + // This process belongs to our group — read its VmRSS + std::string statusPath = entry.path().string() + "/status"; + FILE* f = fopen(statusPath.c_str(), "r"); + if (!f) continue; + char line[256]; + while (fgets(line, sizeof(line), f)) { + if (strncmp(line, "VmRSS:", 6) == 0) { + long rss_kb = 0; + if (sscanf(line + 6, "%ld", &rss_kb) == 1) + total_rss_mb += static_cast(rss_kb) / 1024.0; + break; + } + } + fclose(f); + } + + return total_rss_mb; +} + +bool EmbeddedDaemon::isRunning() const +{ + if (process_pid_ <= 0) return false; + + int status; + pid_t result = waitpid(process_pid_, &status, WNOHANG); + + if (result == 0) { + // Still running + return true; + } + + return false; +} + +void EmbeddedDaemon::drainOutput() +{ + if (stdout_fd_ < 0) return; + char buffer[4096]; + for (;;) { + ssize_t n = read(stdout_fd_, buffer, sizeof(buffer) - 1); + if (n <= 0) break; + buffer[n] = '\0'; + { + std::lock_guard lk(output_mutex_); + appendOutput(buffer, static_cast(n)); + } + DEBUG_LOGF("[dragonxd] %s", buffer); + } +} + +void EmbeddedDaemon::stop(int wait_ms) +{ + should_stop_ = true; + + if (process_pid_ > 0) { + setState(State::Stopping, "Stopping dragonxd..."); + + // Send SIGTERM to the entire process group (negative PID). + // This ensures that if dragonxd is a shell script wrapper, + // both bash AND the actual hushd child receive the signal. + // Without this, only bash is killed and hushd is orphaned. + DEBUG_LOGF("Sending SIGTERM to process group -%d\n", process_pid_); + kill(-process_pid_, SIGTERM); + + // Wait for process to exit, draining stdout each iteration + auto start = std::chrono::steady_clock::now(); + while (isRunning()) { + drainOutput(); + + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); + + if (elapsed >= wait_ms) { + // Force kill the entire process group + DEBUG_LOGF("Forcing dragonxd termination with SIGKILL (group -%d)...\n", process_pid_); + kill(-process_pid_, SIGKILL); + break; + } + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + + drainOutput(); // read any remaining output + + // Reap the child process + int status; + waitpid(process_pid_, &status, 0); + process_pid_ = 0; + } + + if (stdout_fd_ >= 0) { + close(stdout_fd_); + stdout_fd_ = -1; + } + + if (monitor_thread_.joinable()) { + monitor_thread_.join(); + } + + setState(State::Stopped, "dragonxd stopped"); +} + +void EmbeddedDaemon::monitorProcess() +{ + char buffer[4096]; + + while (!should_stop_) { + // Check if process exited (non-blocking waitpid captures exit status) + if (process_pid_ > 0) { + int status = 0; + pid_t result = waitpid(process_pid_, &status, WNOHANG); + if (result == process_pid_) { + // Process exited — drain remaining output + drainOutput(); + + crash_count_++; + std::string exitInfo; + if (WIFEXITED(status)) { + exitInfo = "exit code: " + std::to_string(WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + exitInfo = "killed by signal " + std::to_string(WTERMSIG(status)); + } else { + exitInfo = "unknown exit status"; + } + process_pid_ = 0; + setState(State::Error, "dragonxd exited unexpectedly (" + exitInfo + ")"); + return; + } + } + + // Read process output (non-blocking) + ssize_t bytes_read = read(stdout_fd_, buffer, sizeof(buffer) - 1); + if (bytes_read > 0) { + buffer[bytes_read] = '\0'; + { + std::lock_guard lk(output_mutex_); + appendOutput(buffer, static_cast(bytes_read)); + } + DEBUG_LOGF("[dragonxd] %s", buffer); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} + +#endif // _WIN32 + +bool EmbeddedDaemon::isRpcPortInUse() +{ + int port = std::atoi(DRAGONX_DEFAULT_RPC_PORT); + return isPortInUse(port); +} + +} // namespace daemon +} // namespace dragonx diff --git a/src/daemon/embedded_daemon.h b/src/daemon/embedded_daemon.h new file mode 100644 index 0000000..d76c365 --- /dev/null +++ b/src/daemon/embedded_daemon.h @@ -0,0 +1,195 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace dragonx { +namespace daemon { + +/** + * @brief Manages the embedded dragonxd process + * + * Handles starting, stopping, and monitoring the dragonxd daemon process. + * Ports functionality from Qt version's connection.cpp. + */ +class EmbeddedDaemon { +public: + enum class State { + Stopped, + Starting, + Running, + Stopping, + Error + }; + + using StateCallback = std::function; + + EmbeddedDaemon(); + ~EmbeddedDaemon(); + + // Non-copyable + EmbeddedDaemon(const EmbeddedDaemon&) = delete; + EmbeddedDaemon& operator=(const EmbeddedDaemon&) = delete; + + /** + * @brief Start the embedded dragonxd daemon + * @param binary_path Path to dragonxd binary (auto-detect if empty) + * @return true if process started successfully + */ + bool start(const std::string& binary_path = ""); + + /** + * @brief Stop the running daemon + * @param wait_ms Maximum milliseconds to wait for graceful shutdown + */ + void stop(int wait_ms = 5000); + + /** + * @brief Check if daemon process is running + */ + bool isRunning() const; + + /** + * @brief Get current daemon state + */ + State getState() const { return state_; } + + /** + * @brief Get daemon process memory usage (RSS) in MB + * @return Memory usage in MB, or 0 if unavailable + */ + double getMemoryUsageMB() const; + + /** + * @brief Get last error message + */ + const std::string& getLastError() const { return last_error_; } + + /** + * @brief Get dragonxd process output (thread-safe copy) + */ + std::string getOutput() const { + std::lock_guard lk(output_mutex_); + return process_output_; + } + + /** + * @brief Get new output since a given offset (thread-safe). + * Returns the new text and updates offset to the current size. + */ + std::string getOutputSince(size_t& offset) const { + std::lock_guard lk(output_mutex_); + if (offset >= process_output_.size()) { + offset = process_output_.size(); + return {}; + } + std::string result = process_output_.substr(offset); + offset = process_output_.size(); + return result; + } + + /** + * @brief Get current output size (thread-safe, no copy) + */ + size_t getOutputSize() const { + std::lock_guard lk(output_mutex_); + return process_output_.size(); + } + + /** + * @brief Get last N lines of daemon output (thread-safe snapshot) + */ + std::vector getRecentLines(int maxLines = 8) const; + + /** + * @brief Whether start() detected an existing daemon on the RPC port. + * When true the wallet should connect to it instead of showing an error. + */ + bool externalDaemonDetected() const { return external_daemon_detected_; } + + /** + * @brief Set callback for state changes + */ + void setStateCallback(StateCallback cb) { state_callback_ = cb; } + + /** + * @brief Find dragonxd binary in standard locations + * @return Path to binary, or empty if not found + */ + static std::string findDaemonBinary(); + + /** + * @brief Check whether anything is listening on the default RPC port. + * Useful for detecting an externally-started daemon. + */ + static bool isRpcPortInUse(); + + /** + * @brief Get the chain parameters for dragonxd + * @return Command line arguments for dragonx chain + */ + static std::vector getChainParams(); + + /** + * @brief Set debug logging categories (appended as -debug= flags on next start) + */ + void setDebugCategories(const std::set& cats) { debug_categories_ = cats; } + const std::set& getDebugCategories() const { return debug_categories_; } + + /** Get number of consecutive daemon crashes (resets on successful start or manual reset) */ + int getCrashCount() const { return crash_count_.load(); } + /** Reset crash counter (call on successful connection or manual restart) */ + void resetCrashCount() { crash_count_ = 0; } + +private: + void setState(State s, const std::string& message = ""); + void monitorProcess(); + void drainOutput(); // read any pending stdout into process_output_ + void appendOutput(const char* data, size_t len); // append + trim (caller holds output_mutex_) + bool startProcess(const std::string& binary_path, const std::vector& args); + + std::atomic state_{State::Stopped}; + std::atomic external_daemon_detected_{false}; + std::string last_error_; + mutable std::mutex output_mutex_; // protects process_output_ + std::string process_output_; + StateCallback state_callback_; + + // Process handle +#ifdef _WIN32 + HANDLE process_handle_ = nullptr; + HANDLE stdout_read_ = nullptr; // pipe handle (Linux-style pipe, unused when tailing debug.log) + std::string debug_log_path_; // path to daemon's debug.log for output tailing + size_t debug_log_offset_ = 0; // read offset into debug.log + std::string launch_cmd_; // full command line used to launch daemon (for diagnostics) + std::string launch_binary_; // binary path used (for diagnostics) + std::string launch_workdir_; // working directory used (for diagnostics) +#else + pid_t process_pid_ = 0; + int stdout_fd_ = -1; +#endif + + std::thread monitor_thread_; + std::atomic should_stop_{false}; + std::set debug_categories_; + std::atomic crash_count_{0}; // consecutive crash counter +}; + +} // namespace daemon +} // namespace dragonx diff --git a/src/daemon/xmrig_manager.cpp b/src/daemon/xmrig_manager.cpp new file mode 100644 index 0000000..4124f7a --- /dev/null +++ b/src/daemon/xmrig_manager.cpp @@ -0,0 +1,715 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "xmrig_manager.h" +#include "../resources/embedded_resources.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../util/logger.h" + +#ifdef _WIN32 +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace fs = std::filesystem; +using json = nlohmann::json; + +namespace dragonx { +namespace daemon { + +// ============================================================================ +// Helpers +// ============================================================================ + +static std::string randomHexToken(int bytes = 16) { + static const char hex[] = "0123456789abcdef"; + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution dist(0, 15); + std::string out; + out.reserve(bytes * 2); + for (int i = 0; i < bytes * 2; ++i) + out.push_back(hex[dist(gen)]); + return out; +} + +static int randomPort() { + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution dist(18000, 18999); + return dist(gen); +} + +static std::string getConfigDir() { +#ifdef _WIN32 + char path[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, path))) { + return std::string(path) + "\\ObsidianDragon"; + } + return "."; +#else + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw ? pw->pw_dir : "/tmp"; + } + return std::string(home) + "/.config/ObsidianDragon"; +#endif +} + +// libcurl write callback +static size_t curlWriteCb(void* ptr, size_t sz, size_t n, void* userdata) { + auto* s = static_cast(userdata); + s->append(static_cast(ptr), sz * n); + return sz * n; +} + +// ============================================================================ +// Lifecycle +// ============================================================================ + +XmrigManager::XmrigManager() = default; + +XmrigManager::~XmrigManager() { + if (isRunning()) { + stop(3000); + } +} + +// ============================================================================ +// Binary discovery +// ============================================================================ + +std::string XmrigManager::findXmrigBinary() { + // Use the embedded_resources system (same pattern as daemon) + std::string path = resources::getXmrigPath(); + if (!path.empty() && fs::exists(path)) { + return path; + } + + // Fallback: system PATH +#ifdef _WIN32 + FILE* f = _popen("where xmrig.exe 2>nul", "r"); +#else + FILE* f = popen("which xmrig 2>/dev/null", "r"); +#endif + if (f) { + char line[512]; + if (fgets(line, sizeof(line), f)) { + std::string s(line); + while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) + s.pop_back(); + if (!s.empty() && fs::exists(s)) { +#ifdef _WIN32 + _pclose(f); +#else + pclose(f); +#endif + return s; + } + } +#ifdef _WIN32 + _pclose(f); +#else + pclose(f); +#endif + } + + return {}; +} + +// ============================================================================ +// Config generation +// ============================================================================ + +bool XmrigManager::generateConfig(const Config& cfg, const std::string& outPath) { + api_port_ = randomPort(); + api_token_ = randomHexToken(16); + + int hw = (int)std::thread::hardware_concurrency(); + if (hw < 1) hw = 1; + // Use explicit thread count (not just a hint) + threads_ = (cfg.threads > 0) ? cfg.threads : std::max(1, hw / 2); + if (threads_ > hw) threads_ = hw; + + json j; + j["autosave"] = false; + j["background"] = false; + j["colors"] = false; + + j["http"] = { + {"enabled", true}, + {"host", "127.0.0.1"}, + {"port", api_port_}, + {"access-token", api_token_}, + {"restricted", true} + }; + + j["randomx"] = { + {"init", -1}, + {"mode", "auto"}, + {"1gb-pages", false}, + {"numa", true}, + {"scratchpad_prefetch_mode", 1} + }; + + j["cpu"] = { + {"enabled", true}, + {"huge-pages", cfg.hugepages}, + {"max-threads-hint", 100}, // Use 100% of allotted threads + {"priority", 0}, // Idle priority (lowest) - prevents UI lag + {"yield", true} // Yield to other processes + }; + + j["pools"] = json::array({ + { + {"algo", cfg.algo}, + {"url", cfg.pool_url}, + {"user", cfg.wallet_address}, + {"pass", cfg.worker_name}, + {"keepalive", true}, + {"tls", cfg.tls} + } + }); + + j["donate-level"] = 0; + j["print-time"] = 10; + j["retries"] = 5; + j["retry-pause"] = 5; + + try { + fs::create_directories(fs::path(outPath).parent_path()); + std::ofstream ofs(outPath); + if (!ofs.is_open()) { + last_error_ = "Cannot write xmrig config: " + outPath; + DEBUG_LOGF("[ERROR] XmrigManager: %s\n", last_error_.c_str()); + return false; + } + ofs << j.dump(4); + ofs.close(); + +#ifndef _WIN32 + // 0600 permissions — only owner can read/write + chmod(outPath.c_str(), 0600); +#endif + return true; + } catch (const std::exception& e) { + last_error_ = std::string("Config write error: ") + e.what(); + DEBUG_LOGF("[ERROR] XmrigManager: %s\n", last_error_.c_str()); + return false; + } +} + +// ============================================================================ +// start / stop +// ============================================================================ + +bool XmrigManager::start(const Config& cfg) { + if (state_ == State::Running || state_ == State::Starting) { + last_error_ = "Already running"; + DEBUG_LOGF("[WARN] XmrigManager: %s\n", last_error_.c_str()); + return false; + } + + state_ = State::Starting; + should_stop_ = false; + last_error_.clear(); + { + std::lock_guard lk(output_mutex_); + process_output_.clear(); + } + stats_ = PoolStats{}; + + // Find binary + std::string binary = findXmrigBinary(); + if (binary.empty()) { + last_error_ = "xmrig binary not found"; + state_ = State::Error; + DEBUG_LOGF("[ERROR] XmrigManager: xmrig binary not found\n"); + return false; + } + DEBUG_LOGF("[INFO] XmrigManager: found binary at %s\n", binary.c_str()); + + // Generate config + std::string cfgDir = getConfigDir(); +#ifdef _WIN32 + std::string cfgPath = cfgDir + "\\xmrig-pool.json"; +#else + std::string cfgPath = cfgDir + "/xmrig-pool.json"; +#endif + if (!generateConfig(cfg, cfgPath)) { + state_ = State::Error; + DEBUG_LOGF("[ERROR] XmrigManager: failed to generate config\n"); + return false; + } + DEBUG_LOGF("[INFO] XmrigManager: config written to %s (API port %d, threads %d)\n", + cfgPath.c_str(), api_port_, threads_); + + // Spawn process + if (!startProcess(binary, cfgPath, threads_)) { + state_ = State::Error; + return false; + } + + // Start monitor thread + monitor_thread_ = std::thread(&XmrigManager::monitorProcess, this); + state_ = State::Running; + DEBUG_LOGF("[INFO] XmrigManager: started\n"); + return true; +} + +void XmrigManager::stop(int wait_ms) { + if (state_ == State::Stopped || state_ == State::Stopping) + return; + + state_ = State::Stopping; + should_stop_ = true; + +#ifdef _WIN32 + if (process_handle_) { + // Try graceful termination first + TerminateProcess(process_handle_, 0); + WaitForSingleObject(process_handle_, wait_ms); + CloseHandle(process_handle_); + process_handle_ = nullptr; + } + if (stdout_read_) { + CloseHandle(stdout_read_); + stdout_read_ = nullptr; + } +#else + if (process_pid_ > 0) { + // Send SIGTERM to process group + kill(-process_pid_, SIGTERM); + + // Poll-wait with drain + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(wait_ms); + while (std::chrono::steady_clock::now() < deadline) { + drainOutput(); + int status = 0; + pid_t ret = waitpid(process_pid_, &status, WNOHANG); + if (ret == process_pid_ || ret < 0) break; + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + // If still alive, SIGKILL + if (kill(process_pid_, 0) == 0) { + kill(-process_pid_, SIGKILL); + waitpid(process_pid_, nullptr, 0); + } + process_pid_ = 0; + } + if (stdout_fd_ >= 0) { + close(stdout_fd_); + stdout_fd_ = -1; + } +#endif + + if (monitor_thread_.joinable()) + monitor_thread_.join(); + + state_ = State::Stopped; + DEBUG_LOGF("[INFO] XmrigManager: stopped\n"); +} + +// ============================================================================ +// Process spawning — platform-specific +// ============================================================================ + +#ifdef _WIN32 + +bool XmrigManager::startProcess(const std::string& xmrigPath, const std::string& cfgPath, int threads) { + SECURITY_ATTRIBUTES sa{}; + sa.nLength = sizeof(sa); + sa.bInheritHandle = TRUE; + + HANDLE hRead = nullptr, hWrite = nullptr; + if (!CreatePipe(&hRead, &hWrite, &sa, 0)) { + last_error_ = "CreatePipe failed"; + DEBUG_LOGF("[ERROR] XmrigManager: %s\n", last_error_.c_str()); + return false; + } + SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0); + + // Use explicit --threads to enforce exact thread count (not just a hint) + std::string cmdLine = "\"" + xmrigPath + "\" --config=\"" + cfgPath + "\" --threads=" + std::to_string(threads); + + STARTUPINFOA si{}; + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + si.hStdOutput = hWrite; + si.hStdError = hWrite; + si.wShowWindow = SW_HIDE; + + PROCESS_INFORMATION pi{}; + BOOL ok = CreateProcessA( + nullptr, const_cast(cmdLine.c_str()), + nullptr, nullptr, TRUE, + CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | IDLE_PRIORITY_CLASS, + nullptr, nullptr, &si, &pi + ); + + CloseHandle(hWrite); + + if (!ok) { + CloseHandle(hRead); + DWORD err = GetLastError(); + char errBuf[256]; + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, err, 0, errBuf, sizeof(errBuf), NULL); + last_error_ = "CreateProcess failed for xmrig (error " + std::to_string(err) + "): " + errBuf; + DEBUG_LOGF("[ERROR] XmrigManager: %s\nCommand: %s\n", last_error_.c_str(), cmdLine.c_str()); + return false; + } + + process_handle_ = pi.hProcess; + stdout_read_ = hRead; + CloseHandle(pi.hThread); + + return true; +} + +bool XmrigManager::isRunning() const { + if (!process_handle_) return false; + DWORD exit_code; + GetExitCodeProcess(process_handle_, &exit_code); + return exit_code == STILL_ACTIVE; +} + +double XmrigManager::getMemoryUsageMB() const { + if (!process_handle_) return 0.0; + PROCESS_MEMORY_COUNTERS pmc; + ZeroMemory(&pmc, sizeof(pmc)); + pmc.cb = sizeof(pmc); + if (GetProcessMemoryInfo(process_handle_, &pmc, sizeof(pmc))) { + return static_cast(pmc.WorkingSetSize) / (1024.0 * 1024.0); + } + return 0.0; +} + +void XmrigManager::drainOutput() { + if (!stdout_read_) return; + char buf[4096]; + DWORD avail = 0; + while (PeekNamedPipe(stdout_read_, nullptr, 0, nullptr, &avail, nullptr) && avail > 0) { + DWORD nread = 0; + DWORD toRead = std::min(avail, (DWORD)sizeof(buf)); + if (ReadFile(stdout_read_, buf, toRead, &nread, nullptr) && nread > 0) { + std::lock_guard lk(output_mutex_); + appendOutput(buf, nread); + } else { + break; + } + } +} + +#else // ---- POSIX ---- + +bool XmrigManager::startProcess(const std::string& xmrigPath, const std::string& cfgPath, int threads) { + int pipefd[2]; + if (pipe(pipefd) != 0) { + last_error_ = "pipe() failed"; + DEBUG_LOGF("[ERROR] XmrigManager: %s\n", last_error_.c_str()); + return false; + } + + pid_t pid = fork(); + if (pid < 0) { + last_error_ = "fork() failed"; + DEBUG_LOGF("[ERROR] XmrigManager: %s\n", last_error_.c_str()); + close(pipefd[0]); + close(pipefd[1]); + return false; + } + + if (pid == 0) { + // Child + close(pipefd[0]); + dup2(pipefd[1], STDOUT_FILENO); + dup2(pipefd[1], STDERR_FILENO); + close(pipefd[1]); + + // New process group so we can kill the whole group + setpgid(0, 0); + + // Lowest priority to reduce UI lag (nice value 19 = minimum priority) + if (nice(19) == -1 && errno != 0) { /* ignore failure */ } + + std::string cfgArg = "--config=" + cfgPath; + std::string threadsArg = "--threads=" + std::to_string(threads); + const char* argv[] = { xmrigPath.c_str(), cfgArg.c_str(), threadsArg.c_str(), nullptr }; + execv(xmrigPath.c_str(), const_cast(argv)); + _exit(127); + } + + // Parent + close(pipefd[1]); + process_pid_ = pid; + stdout_fd_ = pipefd[0]; + + // Non-blocking reads + int flags = fcntl(stdout_fd_, F_GETFL, 0); + fcntl(stdout_fd_, F_SETFL, flags | O_NONBLOCK); + + return true; +} + +bool XmrigManager::isRunning() const { + // Use state_ instead of waitpid() to avoid races with moitorProcess + // which also calls waitpid. state_ is atomic and always correct. + State s = state_.load(std::memory_order_relaxed); + return (s == State::Running || s == State::Starting); +} + +double XmrigManager::getMemoryUsageMB() const { + if (process_pid_ <= 0) return 0.0; + char path[64]; + snprintf(path, sizeof(path), "/proc/%d/statm", process_pid_); + FILE* fp = fopen(path, "r"); + if (!fp) return 0.0; + long dummy = 0, pages = 0; + // statm: size resident shared text lib data dt + // We want resident (2nd field) + if (fscanf(fp, "%ld %ld", &dummy, &pages) != 2) pages = 0; + fclose(fp); + long pageSize = sysconf(_SC_PAGESIZE); + return static_cast(pages * pageSize) / (1024.0 * 1024.0); +} + +void XmrigManager::drainOutput() { + if (stdout_fd_ < 0) return; + char buf[4096]; + while (true) { + ssize_t n = read(stdout_fd_, buf, sizeof(buf)); + if (n > 0) { + std::lock_guard lk(output_mutex_); + appendOutput(buf, (size_t)n); + } else { + break; + } + } +} + +#endif // platform + +// ============================================================================ +// Output management +// ============================================================================ + +void XmrigManager::appendOutput(const char* data, size_t len) { + // Caller must hold output_mutex_ + static constexpr size_t MAX_OUTPUT = 1024 * 1024; // 1 MB cap + process_output_.append(data, len); + if (process_output_.size() > MAX_OUTPUT) { + // Trim from the front at a newline boundary + size_t cut = process_output_.size() - MAX_OUTPUT; + auto pos = process_output_.find('\n', cut); + if (pos != std::string::npos) + process_output_.erase(0, pos + 1); + else + process_output_.erase(0, cut); + } +} + +std::vector XmrigManager::getRecentLines(int maxLines) const { + std::lock_guard lk(output_mutex_); + std::vector lines; + if (process_output_.empty()) return lines; + + // Walk backwards collecting lines + size_t end = process_output_.size(); + while ((int)lines.size() < maxLines && end > 0) { + size_t nl = process_output_.rfind('\n', end - 1); + if (nl == std::string::npos) { + lines.push_back(process_output_.substr(0, end)); + break; + } + if (nl + 1 < end) + lines.push_back(process_output_.substr(nl + 1, end - nl - 1)); + end = nl; + } + std::reverse(lines.begin(), lines.end()); + // Remove empty trailing line + while (!lines.empty() && lines.back().empty()) + lines.pop_back(); + return lines; +} + +// ============================================================================ +// Monitor thread +// ============================================================================ + +void XmrigManager::monitorProcess() { + // Wait a few seconds for xmrig HTTP API to start up before first poll + for (int i = 0; i < 30 && !should_stop_; i++) { + drainOutput(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + + int poll_counter = 0; + while (!should_stop_) { + drainOutput(); + + // Check if the child process is still alive (monitor thread only) +#ifdef _WIN32 + if (process_handle_) { + DWORD exitCode = 0; + if (GetExitCodeProcess(process_handle_, &exitCode) && exitCode != STILL_ACTIVE) { + DEBUG_LOGF("[ERROR] XmrigManager: process exited (code %lu)\n", exitCode); + state_ = State::Error; + last_error_ = "xmrig process exited unexpectedly"; + break; + } + } +#else + if (process_pid_ > 0) { + int status = 0; + pid_t ret = waitpid(process_pid_, &status, WNOHANG); + if (ret == process_pid_ || ret < 0) { + DEBUG_LOGF("[ERROR] XmrigManager: process exited (waitpid=%d)\n", ret); + state_ = State::Error; + last_error_ = "xmrig process exited unexpectedly"; + break; + } + } +#endif + + // Poll HTTP stats every ~2 seconds (20 * 100ms) + if (++poll_counter >= 20) { + poll_counter = 0; + fetchStatsHttp(); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + drainOutput(); // Final drain +} + +// ============================================================================ +// Stats polling via HTTP API +// ============================================================================ + +void XmrigManager::pollStats() { + // No-op on UI thread — stats are fetched by the monitor thread. + // Just drain stdout so log lines stay fresh. + drainOutput(); +} + +void XmrigManager::fetchStatsHttp() { + if (state_ != State::Running) return; + + // Drain stdout while we're at it + drainOutput(); + + // Build URL + char url[256]; + snprintf(url, sizeof(url), "http://127.0.0.1:%d/2/summary", api_port_); + + std::string responseData; + CURL* curl = curl_easy_init(); + if (!curl) { + DEBUG_LOGF("[WARN] XmrigManager::pollStats: curl_easy_init failed\n"); + return; + } + + // Set up auth header + std::string authHeader = "Authorization: Bearer " + api_token_; + struct curl_slist* headers = nullptr; + headers = curl_slist_append(headers, authHeader.c_str()); + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteCb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseData); + curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 2000L); // 2s timeout — generous for loaded system + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 1000L); // 1s connect timeout + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); // Avoid signal issues in threads + + CURLcode res = curl_easy_perform(curl); + curl_slist_free_all(headers); + curl_easy_cleanup(curl); + + if (res != CURLE_OK) { + static int s_fail_count = 0; + if (++s_fail_count <= 5 || s_fail_count % 30 == 0) { + DEBUG_LOGF("[WARN] XmrigManager::pollStats: curl failed (%d): %s url=%s\n", + s_fail_count, curl_easy_strerror(res), url); + } + return; + } + + try { + json resp = json::parse(responseData); + + std::lock_guard lk(stats_mutex_); + + if (resp.contains("hashrate") && resp["hashrate"].contains("total")) { + auto& total = resp["hashrate"]["total"]; + if (total.is_array() && total.size() >= 3) { + stats_.hashrate_10s = total[0].is_null() ? 0.0 : total[0].get(); + stats_.hashrate_60s = total[1].is_null() ? 0.0 : total[1].get(); + stats_.hashrate_15m = total[2].is_null() ? 0.0 : total[2].get(); + } + } + + if (resp.contains("connection")) { + auto& conn = resp["connection"]; + stats_.accepted = conn.value("accepted", (int64_t)0); + stats_.rejected = conn.value("rejected", (int64_t)0); + stats_.uptime_sec = conn.value("uptime", (int64_t)0); + stats_.pool_diff = conn.value("diff", 0.0); + stats_.pool_url = conn.value("pool", std::string{}); + stats_.algo = conn.value("algo", std::string{}); + stats_.connected = (stats_.uptime_sec > 0); + } + + // Parse memory usage from "resources" section + if (resp.contains("resources") && resp["resources"].contains("memory")) { + auto& mem = resp["resources"]["memory"]; + stats_.memory_free = mem.value("free", (int64_t)0); + stats_.memory_total = mem.value("total", (int64_t)0); + stats_.memory_used = mem.value("resident_set_memory", (int64_t)0); + } + + // Parse active thread count from hashrate.threads array + if (resp.contains("hashrate") && resp["hashrate"].contains("threads")) { + auto& threads = resp["hashrate"]["threads"]; + if (threads.is_array()) { + stats_.threads_active = static_cast(threads.size()); + } + } else if (resp.contains("cpu") && resp["cpu"].contains("threads")) { + // Fallback: get from cpu section + stats_.threads_active = resp["cpu"].value("threads", 0); + } + } catch (...) { + // Malformed JSON — ignore, retry next poll + } +} + +} // namespace daemon +} // namespace dragonx diff --git a/src/daemon/xmrig_manager.h b/src/daemon/xmrig_manager.h new file mode 100644 index 0000000..25bf4e4 --- /dev/null +++ b/src/daemon/xmrig_manager.h @@ -0,0 +1,169 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#endif + +namespace dragonx { +namespace daemon { + +/** + * @brief Manages the xmrig pool mining process + * + * Handles starting/stopping xmrig for pool mining, polling stats via its + * HTTP API, and capturing stdout for the log panel. Modelled on + * EmbeddedDaemon (same fork/pipe/monitor pattern, same #ifdef split). + */ +class XmrigManager { +public: + enum class State { Stopped, Starting, Running, Stopping, Error }; + + /// Live stats polled from xmrig HTTP API (/2/summary) + struct PoolStats { + double hashrate_10s = 0; + double hashrate_60s = 0; + double hashrate_15m = 0; + int64_t accepted = 0; + int64_t rejected = 0; + int64_t uptime_sec = 0; + double pool_diff = 0; + std::string pool_url; + std::string algo; + bool connected = false; + // Memory usage + int64_t memory_free = 0; // bytes + int64_t memory_total = 0; // bytes + int64_t memory_used = 0; // bytes (resident set size) + int threads_active = 0; // actual mining threads + }; + + /// User-facing config (maps 1:1 to UI fields / Settings) + struct Config { + std::string pool_url = "pool.dragonx.is"; + std::string wallet_address; + std::string worker_name = "x"; + std::string algo = "rx/hush"; + int threads = 0; // 0 = xmrig auto + bool tls = false; + bool hugepages = true; + }; + + XmrigManager(); + ~XmrigManager(); + + // Non-copyable + XmrigManager(const XmrigManager&) = delete; + XmrigManager& operator=(const XmrigManager&) = delete; + + /** + * @brief Start xmrig with the given config. + * Generates a JSON config file, finds the binary, and spawns the process. + */ + bool start(const Config& cfg); + + /** + * @brief Stop xmrig gracefully (SIGTERM → wait → SIGKILL). + */ + void stop(int wait_ms = 5000); + + bool isRunning() const; + State getState() const { return state_.load(std::memory_order_relaxed); } + + const PoolStats& getStats() const { return stats_; } + const std::string& getLastError() const { return last_error_; } + + /** + * @brief Get last N lines of xmrig stdout (thread-safe snapshot). + */ + std::vector getRecentLines(int maxLines = 30) const; + + /** + * @brief Get new output since a given offset (thread-safe). + * Returns the new text and updates offset to the current size. + */ + std::string getOutputSince(size_t& offset) const { + std::lock_guard lk(output_mutex_); + if (offset >= process_output_.size()) { + offset = process_output_.size(); + return {}; + } + std::string result = process_output_.substr(offset); + offset = process_output_.size(); + return result; + } + + /** + * @brief Get current output size (thread-safe, no copy) + */ + size_t getOutputSize() const { + std::lock_guard lk(output_mutex_); + return process_output_.size(); + } + + /** + * @brief Poll the xmrig HTTP API for live stats. + * Lightweight — reads cached stats updated by the monitor thread. + * Called from App::update() every ~2 s while running. + */ + void pollStats(); + + /** + * @brief Get xmrig process memory usage in MB (from OS, not API). + */ + double getMemoryUsageMB() const; + + /** + * @brief Find xmrig binary in standard locations. + */ + static std::string findXmrigBinary(); + +private: + bool generateConfig(const Config& cfg, const std::string& outPath); + bool startProcess(const std::string& xmrigPath, const std::string& cfgPath, int threads); + void monitorProcess(); + void drainOutput(); + void appendOutput(const char* data, size_t len); + void fetchStatsHttp(); // Blocking HTTP call — runs on monitor thread only + + std::atomic state_{State::Stopped}; + std::string last_error_; + + mutable std::mutex output_mutex_; + std::string process_output_; + + // xmrig HTTP API credentials (random per session) + int api_port_ = 0; + std::string api_token_; + int threads_ = 0; // Thread count for mining + PoolStats stats_; + mutable std::mutex stats_mutex_; + + // Process handles +#ifdef _WIN32 + HANDLE process_handle_ = nullptr; + HANDLE stdout_read_ = nullptr; +#else + pid_t process_pid_ = 0; + int stdout_fd_ = -1; +#endif + + std::thread monitor_thread_; + std::atomic should_stop_{false}; +}; + +} // namespace daemon +} // namespace dragonx diff --git a/src/data/address_book.cpp b/src/data/address_book.cpp new file mode 100644 index 0000000..05ff428 --- /dev/null +++ b/src/data/address_book.cpp @@ -0,0 +1,184 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "address_book.h" + +#include +#include +#include + +#include "../util/logger.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +namespace fs = std::filesystem; +using json = nlohmann::json; + +namespace dragonx { +namespace data { + +AddressBook::AddressBook() = default; +AddressBook::~AddressBook() = default; + +std::string AddressBook::getDefaultPath() +{ +#ifdef _WIN32 + char path[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, path))) { + std::string dir = std::string(path) + "\\ObsidianDragon"; + fs::create_directories(dir); + return dir + "\\addressbook.json"; + } + return "addressbook.json"; +#elif defined(__APPLE__) + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + std::string dir = std::string(home) + "/Library/Application Support/ObsidianDragon"; + fs::create_directories(dir); + return dir + "/addressbook.json"; +#else + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + std::string dir = std::string(home) + "/.config/ObsidianDragon"; + fs::create_directories(dir); + return dir + "/addressbook.json"; +#endif +} + +bool AddressBook::load() +{ + file_path_ = getDefaultPath(); + + std::ifstream file(file_path_); + if (!file.is_open()) { + // No file yet - that's OK + return true; + } + + try { + json j; + file >> j; + + entries_.clear(); + + if (j.contains("entries") && j["entries"].is_array()) { + for (const auto& entry : j["entries"]) { + AddressBookEntry e; + e.label = entry.value("label", ""); + e.address = entry.value("address", ""); + e.notes = entry.value("notes", ""); + + if (!e.address.empty()) { + entries_.push_back(e); + } + } + } + + DEBUG_LOGF("Address book loaded: %zu entries\n", entries_.size()); + return true; + + } catch (const std::exception& e) { + DEBUG_LOGF("Error loading address book: %s\n", e.what()); + return false; + } +} + +bool AddressBook::save() +{ + if (file_path_.empty()) { + file_path_ = getDefaultPath(); + } + + try { + json j; + j["entries"] = json::array(); + + for (const auto& entry : entries_) { + json e; + e["label"] = entry.label; + e["address"] = entry.address; + e["notes"] = entry.notes; + j["entries"].push_back(e); + } + + // Ensure directory exists + fs::path p(file_path_); + fs::create_directories(p.parent_path()); + + std::ofstream file(file_path_); + if (!file.is_open()) { + DEBUG_LOGF("Could not open address book for writing: %s\n", file_path_.c_str()); + return false; + } + + file << j.dump(2); + DEBUG_LOGF("Address book saved: %zu entries\n", entries_.size()); + return true; + + } catch (const std::exception& e) { + DEBUG_LOGF("Error saving address book: %s\n", e.what()); + return false; + } +} + +bool AddressBook::addEntry(const AddressBookEntry& entry) +{ + // Check for duplicate address + if (findByAddress(entry.address) >= 0) { + return false; + } + + entries_.push_back(entry); + return save(); +} + +bool AddressBook::updateEntry(size_t index, const AddressBookEntry& entry) +{ + if (index >= entries_.size()) { + return false; + } + + // Check for duplicate address (excluding current entry) + int existing = findByAddress(entry.address); + if (existing >= 0 && static_cast(existing) != index) { + return false; + } + + entries_[index] = entry; + return save(); +} + +bool AddressBook::removeEntry(size_t index) +{ + if (index >= entries_.size()) { + return false; + } + + entries_.erase(entries_.begin() + index); + return save(); +} + +int AddressBook::findByAddress(const std::string& address) const +{ + for (size_t i = 0; i < entries_.size(); i++) { + if (entries_[i].address == address) { + return static_cast(i); + } + } + return -1; +} + +} // namespace data +} // namespace dragonx diff --git a/src/data/address_book.h b/src/data/address_book.h new file mode 100644 index 0000000..6ac7d19 --- /dev/null +++ b/src/data/address_book.h @@ -0,0 +1,103 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include + +namespace dragonx { +namespace data { + +/** + * @brief A single address book entry + */ +struct AddressBookEntry { + std::string label; + std::string address; + std::string notes; + + AddressBookEntry() = default; + AddressBookEntry(const std::string& l, const std::string& a, const std::string& n = "") + : label(l), address(a), notes(n) {} +}; + +/** + * @brief Address book manager + * + * Stores labeled addresses for easy access when sending. + */ +class AddressBook { +public: + AddressBook(); + ~AddressBook(); + + /** + * @brief Load address book from disk + * @return true if loaded successfully + */ + bool load(); + + /** + * @brief Save address book to disk + * @return true if saved successfully + */ + bool save(); + + /** + * @brief Get default address book file path + */ + static std::string getDefaultPath(); + + /** + * @brief Add a new entry + * @param entry The entry to add + * @return true if added (false if duplicate address) + */ + bool addEntry(const AddressBookEntry& entry); + + /** + * @brief Update an existing entry + * @param index Index of entry to update + * @param entry New entry data + * @return true if updated + */ + bool updateEntry(size_t index, const AddressBookEntry& entry); + + /** + * @brief Remove an entry + * @param index Index of entry to remove + * @return true if removed + */ + bool removeEntry(size_t index); + + /** + * @brief Find entry by address + * @param address Address to search for + * @return Index or -1 if not found + */ + int findByAddress(const std::string& address) const; + + /** + * @brief Get all entries + */ + const std::vector& entries() const { return entries_; } + + /** + * @brief Get entry count + */ + size_t size() const { return entries_.size(); } + + /** + * @brief Check if empty + */ + bool empty() const { return entries_.empty(); } + +private: + std::vector entries_; + std::string file_path_; +}; + +} // namespace data +} // namespace dragonx diff --git a/src/data/exchange_info.cpp b/src/data/exchange_info.cpp new file mode 100644 index 0000000..1b2af8c --- /dev/null +++ b/src/data/exchange_info.cpp @@ -0,0 +1,34 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "exchange_info.h" + +namespace dragonx { +namespace data { + +const std::vector& getExchangeRegistry() +{ + static const std::vector registry = { + { + "TradeOgre", + "https://tradeogre.com", + { + {"DRGX", "BTC", "DRGX/BTC", "https://tradeogre.com/exchange/DRGX-BTC"}, + {"DRGX", "LTC", "DRGX/LTC", "https://tradeogre.com/exchange/DRGX-LTC"}, + {"DRGX", "USDT", "DRGX/USDT", "https://tradeogre.com/exchange/DRGX-USDT"}, + } + }, + { + "Exbitron", + "https://www.exbitron.com", + { + {"DRGX", "USDT", "DRGX/USDT", "https://www.exbitron.com/trading/drgxusdt"}, + } + }, + }; + return registry; +} + +} // namespace data +} // namespace dragonx diff --git a/src/data/exchange_info.h b/src/data/exchange_info.h new file mode 100644 index 0000000..add5c81 --- /dev/null +++ b/src/data/exchange_info.h @@ -0,0 +1,38 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include + +namespace dragonx { +namespace data { + +/** + * @brief A single trading pair on an exchange (e.g. DRGX/BTC) + */ +struct ExchangePair { + std::string base; ///< e.g. "DRGX" + std::string quote; ///< e.g. "BTC" + std::string displayName; ///< e.g. "DRGX/BTC" + std::string tradeUrl; ///< Link to the exchange pair page +}; + +/** + * @brief Metadata for a supported exchange + */ +struct ExchangeInfo { + std::string name; ///< e.g. "TradeOgre" + std::string baseUrl; ///< e.g. "https://tradeogre.com" + std::vector pairs; +}; + +/** + * @brief Returns the static registry of supported exchanges + pairs + */ +const std::vector& getExchangeRegistry(); + +} // namespace data +} // namespace dragonx diff --git a/src/data/wallet_state.cpp b/src/data/wallet_state.cpp new file mode 100644 index 0000000..c0245c6 --- /dev/null +++ b/src/data/wallet_state.cpp @@ -0,0 +1,57 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "wallet_state.h" +#include +#include +#include + +namespace dragonx { + +std::string TransactionInfo::getTimeString() const +{ + if (timestamp == 0) return "Unknown"; + + std::time_t t = static_cast(timestamp); + std::tm* tm = std::localtime(&t); + + std::stringstream ss; + ss << std::put_time(tm, "%Y-%m-%d %H:%M"); + return ss.str(); +} + +std::string TransactionInfo::getTypeDisplay() const +{ + if (type == "send") return "Sent"; + if (type == "receive") return "Received"; + if (type == "mined" || type == "generate" || type == "immature") return "Mined"; + return type; +} + +std::string PeerInfo::getConnectionTime() const +{ + if (conntime == 0) return "Unknown"; + + int64_t now = std::time(nullptr); + int64_t diff = now - conntime; + + if (diff < 60) return std::to_string(diff) + "s"; + if (diff < 3600) return std::to_string(diff / 60) + "m"; + if (diff < 86400) return std::to_string(diff / 3600) + "h"; + return std::to_string(diff / 86400) + "d"; +} + +std::string BannedPeer::getBannedUntilString() const +{ + if (banned_until == 0) return "Never"; + + std::time_t t = static_cast(banned_until); + std::tm* tm = std::localtime(&t); + + std::stringstream ss; + ss << std::put_time(tm, "%Y-%m-%d %H:%M"); + return ss.str(); +} + +} // namespace dragonx diff --git a/src/data/wallet_state.h b/src/data/wallet_state.h new file mode 100644 index 0000000..01769b3 --- /dev/null +++ b/src/data/wallet_state.h @@ -0,0 +1,267 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include + +namespace dragonx { + +/** + * @brief Represents an address with its balance + */ +struct AddressInfo { + std::string address; + double balance = 0.0; + std::string type; // "shielded" or "transparent" + + // For display + std::string label; + + // Derived + bool isZAddr() const { return !address.empty() && address[0] == 'z'; } + bool isShielded() const { return type == "shielded"; } +}; + +/** + * @brief Represents a wallet transaction + */ +struct TransactionInfo { + std::string txid; + std::string type; // "send", "receive", "mined" + double amount = 0.0; + int64_t timestamp = 0; // Unix timestamp + int confirmations = 0; + std::string address; // destination (send) or source (receive) + std::string from_address; // source address for sends + std::string memo; + + // Computed fields + std::string getTimeString() const; + std::string getTypeDisplay() const; + bool isConfirmed() const { return confirmations >= 1; } + bool isMature() const { return confirmations >= 100; } +}; + +/** + * @brief Represents a connected peer + */ +struct PeerInfo { + int id = 0; + std::string addr; + std::string subver; + std::string services; + int version = 0; + int64_t conntime = 0; + int banscore = 0; + double pingtime = 0.0; + int64_t bytessent = 0; + int64_t bytesrecv = 0; + int startingheight = 0; + int synced_headers = 0; + int synced_blocks = 0; + bool inbound = false; + + // TLS info + std::string tls_cipher; + bool tls_verified = false; + + std::string getConnectionTime() const; +}; + +/** + * @brief Represents a banned peer + */ +struct BannedPeer { + std::string address; + std::string subnet; + int64_t banned_until = 0; + + std::string getBannedUntilString() const; +}; + +/** + * @brief Mining statistics + */ +struct MiningInfo { + bool generate = false; + int genproclimit = 0; // -1 means max CPUs + double localHashrate = 0.0; // Local hashrate (H/s) from getlocalsolps RPC (RandomX) + double networkHashrate = 0.0; // Network hashrate (H/s) + int blocks = 0; + double difficulty = 0.0; + std::string chain; + + double daemon_memory_mb = 0.0; // Daemon process RSS in MB + + // History for chart + std::vector hashrate_history; // Last N samples + static constexpr int MAX_HISTORY = 300; // 5 minutes at 1s intervals +}; + +/** + * @brief Blockchain synchronization info + */ +struct SyncInfo { + int blocks = 0; + int headers = 0; + double verification_progress = 0.0; + bool syncing = false; + std::string best_blockhash; + + bool isSynced() const { return !syncing && blocks > 0 && blocks >= headers - 2; } +}; + +/** + * @brief Market/price information + */ +struct MarketInfo { + double price_usd = 0.0; + double price_btc = 0.0; + double volume_24h = 0.0; + double change_24h = 0.0; + double market_cap = 0.0; + std::string last_updated; + + // Price history for chart + std::vector price_history; + static constexpr int MAX_HISTORY = 24; // 24 hours +}; + +/** + * @brief Pool mining state (from xmrig HTTP API) + */ +struct PoolMiningState { + bool pool_mode = false; // UI toggle: solo vs pool + bool xmrig_running = false; + std::string pool_url; + std::string algo; + + double hashrate_10s = 0; + double hashrate_60s = 0; + double hashrate_15m = 0; + int64_t accepted = 0; + int64_t rejected = 0; + int64_t uptime_sec = 0; + double pool_diff = 0; + bool connected = false; + + // Memory/thread usage (bytes for memory) + int64_t memory_used = 0; + int threads_active = 0; + + // Hashrate history for chart (mirrors MiningInfo::hashrate_history) + std::vector hashrate_history; + static constexpr int MAX_HISTORY = 60; // 5 minutes at ~5s intervals + + // Recent log lines for the log panel + std::vector log_lines; +}; + +/** + * @brief Complete wallet state - all data fetched from daemon + */ +struct WalletState { + // Connection + bool connected = false; + int daemon_version = 0; + std::string daemon_subversion; + int protocol_version = 0; + int p2p_port = 0; + int longestchain = 0; + int notarized = 0; + + // Sync status + SyncInfo sync; + + // Balances (named to match UI usage) + double privateBalance = 0.0; // shielded balance + double transparentBalance = 0.0; + double totalBalance = 0.0; + double unconfirmedBalance = 0.0; + + // Aliases for backward compatibility + double& shielded_balance = privateBalance; + double& transparent_balance = transparentBalance; + double& total_balance = totalBalance; + double& unconfirmed_balance = unconfirmedBalance; + + // Addresses - combined list for UI convenience + std::vector addresses; + + // Also keep separate lists for legacy code + std::vector z_addresses; + std::vector t_addresses; + + // Transactions + std::vector transactions; + + // Peers + std::vector peers; + std::vector bannedPeers; + + // Aliases for banned_peers + std::vector& banned_peers = bannedPeers; + + // Mining + MiningInfo mining; + + // Pool mining (xmrig) + PoolMiningState pool_mining; + + // Market + MarketInfo market; + + // Wallet encryption state (populated from getwalletinfo) + bool encrypted = false; // true if wallet has ever been encrypted + bool locked = false; // true if encrypted && unlocked_until <= now + int64_t unlocked_until = 0; // 0 = locked, >0 = unix timestamp when auto-lock fires + bool encryption_state_known = false; // true once first getwalletinfo response processed + + bool isEncrypted() const { return encrypted; } + bool isLocked() const { return encrypted && locked; } + bool isUnlocked() const { return encrypted && !locked; } + + // Timestamps for refresh logic + int64_t last_balance_update = 0; + int64_t last_tx_update = 0; + int64_t last_peer_update = 0; + int64_t last_mining_update = 0; + + // Helper methods + int getAddressCount() const { return addresses.size(); } + double getBalanceUSD() const { return totalBalance * market.price_usd; } + + void clear() { + connected = false; + privateBalance = transparentBalance = totalBalance = 0.0; + encrypted = false; + locked = false; + unlocked_until = 0; + encryption_state_known = false; + addresses.clear(); + z_addresses.clear(); + t_addresses.clear(); + transactions.clear(); + peers.clear(); + bannedPeers.clear(); + } + + // Rebuild combined addresses list from z/t lists + void rebuildAddressList() { + addresses.clear(); + addresses.reserve(z_addresses.size() + t_addresses.size()); + for (const auto& addr : z_addresses) { + addresses.push_back(addr); + } + for (const auto& addr : t_addresses) { + addresses.push_back(addr); + } + } +}; + +} // namespace dragonx diff --git a/src/embedded/IconsMaterialDesign.h b/src/embedded/IconsMaterialDesign.h new file mode 100644 index 0000000..31cf86d --- /dev/null +++ b/src/embedded/IconsMaterialDesign.h @@ -0,0 +1,2247 @@ +// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py +// for C and C++ +// from codepoints https://github.com/google/material-design-icons/raw/master/font/MaterialIcons-Regular.codepoints +// for use with font https://github.com/google/material-design-icons/blob/master/font/MaterialIcons-Regular.ttf + +#pragma once + +#define FONT_ICON_FILE_NAME_MD "MaterialIcons-Regular.ttf" + +#define ICON_MIN_MD 0xe000 +#define ICON_MAX_16_MD 0xf8ff +#define ICON_MAX_MD 0x10fffd + +#define ICON_MD_10K "\xee\xa5\x91" // U+e951 +#define ICON_MD_10MP "\xee\xa5\x92" // U+e952 +#define ICON_MD_11MP "\xee\xa5\x93" // U+e953 +#define ICON_MD_123 "\xee\xae\x8d" // U+eb8d +#define ICON_MD_12MP "\xee\xa5\x94" // U+e954 +#define ICON_MD_13MP "\xee\xa5\x95" // U+e955 +#define ICON_MD_14MP "\xee\xa5\x96" // U+e956 +#define ICON_MD_15MP "\xee\xa5\x97" // U+e957 +#define ICON_MD_16MP "\xee\xa5\x98" // U+e958 +#define ICON_MD_17MP "\xee\xa5\x99" // U+e959 +#define ICON_MD_18_UP_RATING "\xef\xa3\xbd" // U+f8fd +#define ICON_MD_18MP "\xee\xa5\x9a" // U+e95a +#define ICON_MD_19MP "\xee\xa5\x9b" // U+e95b +#define ICON_MD_1K "\xee\xa5\x9c" // U+e95c +#define ICON_MD_1K_PLUS "\xee\xa5\x9d" // U+e95d +#define ICON_MD_1X_MOBILEDATA "\xee\xbf\x8d" // U+efcd +#define ICON_MD_20MP "\xee\xa5\x9e" // U+e95e +#define ICON_MD_21MP "\xee\xa5\x9f" // U+e95f +#define ICON_MD_22MP "\xee\xa5\xa0" // U+e960 +#define ICON_MD_23MP "\xee\xa5\xa1" // U+e961 +#define ICON_MD_24MP "\xee\xa5\xa2" // U+e962 +#define ICON_MD_2K "\xee\xa5\xa3" // U+e963 +#define ICON_MD_2K_PLUS "\xee\xa5\xa4" // U+e964 +#define ICON_MD_2MP "\xee\xa5\xa5" // U+e965 +#define ICON_MD_30FPS "\xee\xbf\x8e" // U+efce +#define ICON_MD_30FPS_SELECT "\xee\xbf\x8f" // U+efcf +#define ICON_MD_360 "\xee\x95\xb7" // U+e577 +#define ICON_MD_3D_ROTATION "\xee\xa1\x8d" // U+e84d +#define ICON_MD_3G_MOBILEDATA "\xee\xbf\x90" // U+efd0 +#define ICON_MD_3K "\xee\xa5\xa6" // U+e966 +#define ICON_MD_3K_PLUS "\xee\xa5\xa7" // U+e967 +#define ICON_MD_3MP "\xee\xa5\xa8" // U+e968 +#define ICON_MD_3P "\xee\xbf\x91" // U+efd1 +#define ICON_MD_4G_MOBILEDATA "\xee\xbf\x92" // U+efd2 +#define ICON_MD_4G_PLUS_MOBILEDATA "\xee\xbf\x93" // U+efd3 +#define ICON_MD_4K "\xee\x81\xb2" // U+e072 +#define ICON_MD_4K_PLUS "\xee\xa5\xa9" // U+e969 +#define ICON_MD_4MP "\xee\xa5\xaa" // U+e96a +#define ICON_MD_5G "\xee\xbc\xb8" // U+ef38 +#define ICON_MD_5K "\xee\xa5\xab" // U+e96b +#define ICON_MD_5K_PLUS "\xee\xa5\xac" // U+e96c +#define ICON_MD_5MP "\xee\xa5\xad" // U+e96d +#define ICON_MD_60FPS "\xee\xbf\x94" // U+efd4 +#define ICON_MD_60FPS_SELECT "\xee\xbf\x95" // U+efd5 +#define ICON_MD_6_FT_APART "\xef\x88\x9e" // U+f21e +#define ICON_MD_6K "\xee\xa5\xae" // U+e96e +#define ICON_MD_6K_PLUS "\xee\xa5\xaf" // U+e96f +#define ICON_MD_6MP "\xee\xa5\xb0" // U+e970 +#define ICON_MD_7K "\xee\xa5\xb1" // U+e971 +#define ICON_MD_7K_PLUS "\xee\xa5\xb2" // U+e972 +#define ICON_MD_7MP "\xee\xa5\xb3" // U+e973 +#define ICON_MD_8K "\xee\xa5\xb4" // U+e974 +#define ICON_MD_8K_PLUS "\xee\xa5\xb5" // U+e975 +#define ICON_MD_8MP "\xee\xa5\xb6" // U+e976 +#define ICON_MD_9K "\xee\xa5\xb7" // U+e977 +#define ICON_MD_9K_PLUS "\xee\xa5\xb8" // U+e978 +#define ICON_MD_9MP "\xee\xa5\xb9" // U+e979 +#define ICON_MD_ABC "\xee\xae\x94" // U+eb94 +#define ICON_MD_AC_UNIT "\xee\xac\xbb" // U+eb3b +#define ICON_MD_ACCESS_ALARM "\xee\x86\x90" // U+e190 +#define ICON_MD_ACCESS_ALARMS "\xee\x86\x91" // U+e191 +#define ICON_MD_ACCESS_TIME "\xee\x86\x92" // U+e192 +#define ICON_MD_ACCESS_TIME_FILLED "\xee\xbf\x96" // U+efd6 +#define ICON_MD_ACCESSIBILITY "\xee\xa1\x8e" // U+e84e +#define ICON_MD_ACCESSIBILITY_NEW "\xee\xa4\xac" // U+e92c +#define ICON_MD_ACCESSIBLE "\xee\xa4\x94" // U+e914 +#define ICON_MD_ACCESSIBLE_FORWARD "\xee\xa4\xb4" // U+e934 +#define ICON_MD_ACCOUNT_BALANCE "\xee\xa1\x8f" // U+e84f +#define ICON_MD_ACCOUNT_BALANCE_WALLET "\xee\xa1\x90" // U+e850 +#define ICON_MD_ACCOUNT_BOX "\xee\xa1\x91" // U+e851 +#define ICON_MD_ACCOUNT_CIRCLE "\xee\xa1\x93" // U+e853 +#define ICON_MD_ACCOUNT_TREE "\xee\xa5\xba" // U+e97a +#define ICON_MD_AD_UNITS "\xee\xbc\xb9" // U+ef39 +#define ICON_MD_ADB "\xee\x98\x8e" // U+e60e +#define ICON_MD_ADD "\xee\x85\x85" // U+e145 +#define ICON_MD_ADD_A_PHOTO "\xee\x90\xb9" // U+e439 +#define ICON_MD_ADD_ALARM "\xee\x86\x93" // U+e193 +#define ICON_MD_ADD_ALERT "\xee\x80\x83" // U+e003 +#define ICON_MD_ADD_BOX "\xee\x85\x86" // U+e146 +#define ICON_MD_ADD_BUSINESS "\xee\x9c\xa9" // U+e729 +#define ICON_MD_ADD_CALL "\xee\x83\xa8" // U+e0e8 +#define ICON_MD_ADD_CARD "\xee\xae\x86" // U+eb86 +#define ICON_MD_ADD_CHART "\xee\xa5\xbb" // U+e97b +#define ICON_MD_ADD_CIRCLE "\xee\x85\x87" // U+e147 +#define ICON_MD_ADD_CIRCLE_OUTLINE "\xee\x85\x88" // U+e148 +#define ICON_MD_ADD_COMMENT "\xee\x89\xa6" // U+e266 +#define ICON_MD_ADD_HOME "\xef\xa3\xab" // U+f8eb +#define ICON_MD_ADD_HOME_WORK "\xef\xa3\xad" // U+f8ed +#define ICON_MD_ADD_IC_CALL "\xee\xa5\xbc" // U+e97c +#define ICON_MD_ADD_LINK "\xee\x85\xb8" // U+e178 +#define ICON_MD_ADD_LOCATION "\xee\x95\xa7" // U+e567 +#define ICON_MD_ADD_LOCATION_ALT "\xee\xbc\xba" // U+ef3a +#define ICON_MD_ADD_MODERATOR "\xee\xa5\xbd" // U+e97d +#define ICON_MD_ADD_PHOTO_ALTERNATE "\xee\x90\xbe" // U+e43e +#define ICON_MD_ADD_REACTION "\xee\x87\x93" // U+e1d3 +#define ICON_MD_ADD_ROAD "\xee\xbc\xbb" // U+ef3b +#define ICON_MD_ADD_SHOPPING_CART "\xee\xa1\x94" // U+e854 +#define ICON_MD_ADD_TASK "\xef\x88\xba" // U+f23a +#define ICON_MD_ADD_TO_DRIVE "\xee\x99\x9c" // U+e65c +#define ICON_MD_ADD_TO_HOME_SCREEN "\xee\x87\xbe" // U+e1fe +#define ICON_MD_ADD_TO_PHOTOS "\xee\x8e\x9d" // U+e39d +#define ICON_MD_ADD_TO_QUEUE "\xee\x81\x9c" // U+e05c +#define ICON_MD_ADDCHART "\xee\xbc\xbc" // U+ef3c +#define ICON_MD_ADF_SCANNER "\xee\xab\x9a" // U+eada +#define ICON_MD_ADJUST "\xee\x8e\x9e" // U+e39e +#define ICON_MD_ADMIN_PANEL_SETTINGS "\xee\xbc\xbd" // U+ef3d +#define ICON_MD_ADOBE "\xee\xaa\x96" // U+ea96 +#define ICON_MD_ADS_CLICK "\xee\x9d\xa2" // U+e762 +#define ICON_MD_AGRICULTURE "\xee\xa9\xb9" // U+ea79 +#define ICON_MD_AIR "\xee\xbf\x98" // U+efd8 +#define ICON_MD_AIRLINE_SEAT_FLAT "\xee\x98\xb0" // U+e630 +#define ICON_MD_AIRLINE_SEAT_FLAT_ANGLED "\xee\x98\xb1" // U+e631 +#define ICON_MD_AIRLINE_SEAT_INDIVIDUAL_SUITE "\xee\x98\xb2" // U+e632 +#define ICON_MD_AIRLINE_SEAT_LEGROOM_EXTRA "\xee\x98\xb3" // U+e633 +#define ICON_MD_AIRLINE_SEAT_LEGROOM_NORMAL "\xee\x98\xb4" // U+e634 +#define ICON_MD_AIRLINE_SEAT_LEGROOM_REDUCED "\xee\x98\xb5" // U+e635 +#define ICON_MD_AIRLINE_SEAT_RECLINE_EXTRA "\xee\x98\xb6" // U+e636 +#define ICON_MD_AIRLINE_SEAT_RECLINE_NORMAL "\xee\x98\xb7" // U+e637 +#define ICON_MD_AIRLINE_STOPS "\xee\x9f\x90" // U+e7d0 +#define ICON_MD_AIRLINES "\xee\x9f\x8a" // U+e7ca +#define ICON_MD_AIRPLANE_TICKET "\xee\xbf\x99" // U+efd9 +#define ICON_MD_AIRPLANEMODE_ACTIVE "\xee\x86\x95" // U+e195 +#define ICON_MD_AIRPLANEMODE_INACTIVE "\xee\x86\x94" // U+e194 +#define ICON_MD_AIRPLANEMODE_OFF "\xee\x86\x94" // U+e194 +#define ICON_MD_AIRPLANEMODE_ON "\xee\x86\x95" // U+e195 +#define ICON_MD_AIRPLAY "\xee\x81\x95" // U+e055 +#define ICON_MD_AIRPORT_SHUTTLE "\xee\xac\xbc" // U+eb3c +#define ICON_MD_ALARM "\xee\xa1\x95" // U+e855 +#define ICON_MD_ALARM_ADD "\xee\xa1\x96" // U+e856 +#define ICON_MD_ALARM_OFF "\xee\xa1\x97" // U+e857 +#define ICON_MD_ALARM_ON "\xee\xa1\x98" // U+e858 +#define ICON_MD_ALBUM "\xee\x80\x99" // U+e019 +#define ICON_MD_ALIGN_HORIZONTAL_CENTER "\xee\x80\x8f" // U+e00f +#define ICON_MD_ALIGN_HORIZONTAL_LEFT "\xee\x80\x8d" // U+e00d +#define ICON_MD_ALIGN_HORIZONTAL_RIGHT "\xee\x80\x90" // U+e010 +#define ICON_MD_ALIGN_VERTICAL_BOTTOM "\xee\x80\x95" // U+e015 +#define ICON_MD_ALIGN_VERTICAL_CENTER "\xee\x80\x91" // U+e011 +#define ICON_MD_ALIGN_VERTICAL_TOP "\xee\x80\x8c" // U+e00c +#define ICON_MD_ALL_INBOX "\xee\xa5\xbf" // U+e97f +#define ICON_MD_ALL_INCLUSIVE "\xee\xac\xbd" // U+eb3d +#define ICON_MD_ALL_OUT "\xee\xa4\x8b" // U+e90b +#define ICON_MD_ALT_ROUTE "\xef\x86\x84" // U+f184 +#define ICON_MD_ALTERNATE_EMAIL "\xee\x83\xa6" // U+e0e6 +#define ICON_MD_AMP_STORIES "\xee\xa8\x93" // U+ea13 +#define ICON_MD_ANALYTICS "\xee\xbc\xbe" // U+ef3e +#define ICON_MD_ANCHOR "\xef\x87\x8d" // U+f1cd +#define ICON_MD_ANDROID "\xee\xa1\x99" // U+e859 +#define ICON_MD_ANIMATION "\xee\x9c\x9c" // U+e71c +#define ICON_MD_ANNOUNCEMENT "\xee\xa1\x9a" // U+e85a +#define ICON_MD_AOD "\xee\xbf\x9a" // U+efda +#define ICON_MD_APARTMENT "\xee\xa9\x80" // U+ea40 +#define ICON_MD_API "\xef\x86\xb7" // U+f1b7 +#define ICON_MD_APP_BLOCKING "\xee\xbc\xbf" // U+ef3f +#define ICON_MD_APP_REGISTRATION "\xee\xbd\x80" // U+ef40 +#define ICON_MD_APP_SETTINGS_ALT "\xee\xbd\x81" // U+ef41 +#define ICON_MD_APP_SHORTCUT "\xee\xab\xa4" // U+eae4 +#define ICON_MD_APPLE "\xee\xaa\x80" // U+ea80 +#define ICON_MD_APPROVAL "\xee\xa6\x82" // U+e982 +#define ICON_MD_APPS "\xee\x97\x83" // U+e5c3 +#define ICON_MD_APPS_OUTAGE "\xee\x9f\x8c" // U+e7cc +#define ICON_MD_ARCHITECTURE "\xee\xa8\xbb" // U+ea3b +#define ICON_MD_ARCHIVE "\xee\x85\x89" // U+e149 +#define ICON_MD_AREA_CHART "\xee\x9d\xb0" // U+e770 +#define ICON_MD_ARROW_BACK "\xee\x97\x84" // U+e5c4 +#define ICON_MD_ARROW_BACK_IOS "\xee\x97\xa0" // U+e5e0 +#define ICON_MD_ARROW_BACK_IOS_NEW "\xee\x8b\xaa" // U+e2ea +#define ICON_MD_ARROW_CIRCLE_DOWN "\xef\x86\x81" // U+f181 +#define ICON_MD_ARROW_CIRCLE_LEFT "\xee\xaa\xa7" // U+eaa7 +#define ICON_MD_ARROW_CIRCLE_RIGHT "\xee\xaa\xaa" // U+eaaa +#define ICON_MD_ARROW_CIRCLE_UP "\xef\x86\x82" // U+f182 +#define ICON_MD_ARROW_DOWNWARD "\xee\x97\x9b" // U+e5db +#define ICON_MD_ARROW_DROP_DOWN "\xee\x97\x85" // U+e5c5 +#define ICON_MD_ARROW_DROP_DOWN_CIRCLE "\xee\x97\x86" // U+e5c6 +#define ICON_MD_ARROW_DROP_UP "\xee\x97\x87" // U+e5c7 +#define ICON_MD_ARROW_FORWARD "\xee\x97\x88" // U+e5c8 +#define ICON_MD_ARROW_FORWARD_IOS "\xee\x97\xa1" // U+e5e1 +#define ICON_MD_ARROW_LEFT "\xee\x97\x9e" // U+e5de +#define ICON_MD_ARROW_OUTWARD "\xef\xa3\x8e" // U+f8ce +#define ICON_MD_ARROW_RIGHT "\xee\x97\x9f" // U+e5df +#define ICON_MD_ARROW_RIGHT_ALT "\xee\xa5\x81" // U+e941 +#define ICON_MD_ARROW_UPWARD "\xee\x97\x98" // U+e5d8 +#define ICON_MD_ART_TRACK "\xee\x81\xa0" // U+e060 +#define ICON_MD_ARTICLE "\xee\xbd\x82" // U+ef42 +#define ICON_MD_ASPECT_RATIO "\xee\xa1\x9b" // U+e85b +#define ICON_MD_ASSESSMENT "\xee\xa1\x9c" // U+e85c +#define ICON_MD_ASSIGNMENT "\xee\xa1\x9d" // U+e85d +#define ICON_MD_ASSIGNMENT_ADD "\xef\xa1\x88" // U+f848 +#define ICON_MD_ASSIGNMENT_IND "\xee\xa1\x9e" // U+e85e +#define ICON_MD_ASSIGNMENT_LATE "\xee\xa1\x9f" // U+e85f +#define ICON_MD_ASSIGNMENT_RETURN "\xee\xa1\xa0" // U+e860 +#define ICON_MD_ASSIGNMENT_RETURNED "\xee\xa1\xa1" // U+e861 +#define ICON_MD_ASSIGNMENT_TURNED_IN "\xee\xa1\xa2" // U+e862 +#define ICON_MD_ASSIST_WALKER "\xef\xa3\x95" // U+f8d5 +#define ICON_MD_ASSISTANT "\xee\x8e\x9f" // U+e39f +#define ICON_MD_ASSISTANT_DIRECTION "\xee\xa6\x88" // U+e988 +#define ICON_MD_ASSISTANT_NAVIGATION "\xee\xa6\x89" // U+e989 +#define ICON_MD_ASSISTANT_PHOTO "\xee\x8e\xa0" // U+e3a0 +#define ICON_MD_ASSURED_WORKLOAD "\xee\xad\xaf" // U+eb6f +#define ICON_MD_ATM "\xee\x95\xb3" // U+e573 +#define ICON_MD_ATTACH_EMAIL "\xee\xa9\x9e" // U+ea5e +#define ICON_MD_ATTACH_FILE "\xee\x88\xa6" // U+e226 +#define ICON_MD_ATTACH_MONEY "\xee\x88\xa7" // U+e227 +#define ICON_MD_ATTACHMENT "\xee\x8a\xbc" // U+e2bc +#define ICON_MD_ATTRACTIONS "\xee\xa9\x92" // U+ea52 +#define ICON_MD_ATTRIBUTION "\xee\xbf\x9b" // U+efdb +#define ICON_MD_AUDIO_FILE "\xee\xae\x82" // U+eb82 +#define ICON_MD_AUDIOTRACK "\xee\x8e\xa1" // U+e3a1 +#define ICON_MD_AUTO_AWESOME "\xee\x99\x9f" // U+e65f +#define ICON_MD_AUTO_AWESOME_MOSAIC "\xee\x99\xa0" // U+e660 +#define ICON_MD_AUTO_AWESOME_MOTION "\xee\x99\xa1" // U+e661 +#define ICON_MD_AUTO_DELETE "\xee\xa9\x8c" // U+ea4c +#define ICON_MD_AUTO_FIX_HIGH "\xee\x99\xa3" // U+e663 +#define ICON_MD_AUTO_FIX_NORMAL "\xee\x99\xa4" // U+e664 +#define ICON_MD_AUTO_FIX_OFF "\xee\x99\xa5" // U+e665 +#define ICON_MD_AUTO_GRAPH "\xee\x93\xbb" // U+e4fb +#define ICON_MD_AUTO_MODE "\xee\xb0\xa0" // U+ec20 +#define ICON_MD_AUTO_STORIES "\xee\x99\xa6" // U+e666 +#define ICON_MD_AUTOFPS_SELECT "\xee\xbf\x9c" // U+efdc +#define ICON_MD_AUTORENEW "\xee\xa1\xa3" // U+e863 +#define ICON_MD_AV_TIMER "\xee\x80\x9b" // U+e01b +#define ICON_MD_BABY_CHANGING_STATION "\xef\x86\x9b" // U+f19b +#define ICON_MD_BACK_HAND "\xee\x9d\xa4" // U+e764 +#define ICON_MD_BACKPACK "\xef\x86\x9c" // U+f19c +#define ICON_MD_BACKSPACE "\xee\x85\x8a" // U+e14a +#define ICON_MD_BACKUP "\xee\xa1\xa4" // U+e864 +#define ICON_MD_BACKUP_TABLE "\xee\xbd\x83" // U+ef43 +#define ICON_MD_BADGE "\xee\xa9\xa7" // U+ea67 +#define ICON_MD_BAKERY_DINING "\xee\xa9\x93" // U+ea53 +#define ICON_MD_BALANCE "\xee\xab\xb6" // U+eaf6 +#define ICON_MD_BALCONY "\xee\x96\x8f" // U+e58f +#define ICON_MD_BALLOT "\xee\x85\xb2" // U+e172 +#define ICON_MD_BAR_CHART "\xee\x89\xab" // U+e26b +#define ICON_MD_BARCODE_READER "\xef\xa1\x9c" // U+f85c +#define ICON_MD_BATCH_PREDICTION "\xef\x83\xb5" // U+f0f5 +#define ICON_MD_BATHROOM "\xee\xbf\x9d" // U+efdd +#define ICON_MD_BATHTUB "\xee\xa9\x81" // U+ea41 +#define ICON_MD_BATTERY_0_BAR "\xee\xaf\x9c" // U+ebdc +#define ICON_MD_BATTERY_1_BAR "\xee\xaf\x99" // U+ebd9 +#define ICON_MD_BATTERY_2_BAR "\xee\xaf\xa0" // U+ebe0 +#define ICON_MD_BATTERY_3_BAR "\xee\xaf\x9d" // U+ebdd +#define ICON_MD_BATTERY_4_BAR "\xee\xaf\xa2" // U+ebe2 +#define ICON_MD_BATTERY_5_BAR "\xee\xaf\x94" // U+ebd4 +#define ICON_MD_BATTERY_6_BAR "\xee\xaf\x92" // U+ebd2 +#define ICON_MD_BATTERY_ALERT "\xee\x86\x9c" // U+e19c +#define ICON_MD_BATTERY_CHARGING_FULL "\xee\x86\xa3" // U+e1a3 +#define ICON_MD_BATTERY_FULL "\xee\x86\xa4" // U+e1a4 +#define ICON_MD_BATTERY_SAVER "\xee\xbf\x9e" // U+efde +#define ICON_MD_BATTERY_STD "\xee\x86\xa5" // U+e1a5 +#define ICON_MD_BATTERY_UNKNOWN "\xee\x86\xa6" // U+e1a6 +#define ICON_MD_BEACH_ACCESS "\xee\xac\xbe" // U+eb3e +#define ICON_MD_BED "\xee\xbf\x9f" // U+efdf +#define ICON_MD_BEDROOM_BABY "\xee\xbf\xa0" // U+efe0 +#define ICON_MD_BEDROOM_CHILD "\xee\xbf\xa1" // U+efe1 +#define ICON_MD_BEDROOM_PARENT "\xee\xbf\xa2" // U+efe2 +#define ICON_MD_BEDTIME "\xee\xbd\x84" // U+ef44 +#define ICON_MD_BEDTIME_OFF "\xee\xad\xb6" // U+eb76 +#define ICON_MD_BEENHERE "\xee\x94\xad" // U+e52d +#define ICON_MD_BENTO "\xef\x87\xb4" // U+f1f4 +#define ICON_MD_BIKE_SCOOTER "\xee\xbd\x85" // U+ef45 +#define ICON_MD_BIOTECH "\xee\xa8\xba" // U+ea3a +#define ICON_MD_BLENDER "\xee\xbf\xa3" // U+efe3 +#define ICON_MD_BLIND "\xef\xa3\x96" // U+f8d6 +#define ICON_MD_BLINDS "\xee\x8a\x86" // U+e286 +#define ICON_MD_BLINDS_CLOSED "\xee\xb0\x9f" // U+ec1f +#define ICON_MD_BLOCK "\xee\x85\x8b" // U+e14b +#define ICON_MD_BLOCK_FLIPPED "\xee\xbd\x86" // U+ef46 +#define ICON_MD_BLOODTYPE "\xee\xbf\xa4" // U+efe4 +#define ICON_MD_BLUETOOTH "\xee\x86\xa7" // U+e1a7 +#define ICON_MD_BLUETOOTH_AUDIO "\xee\x98\x8f" // U+e60f +#define ICON_MD_BLUETOOTH_CONNECTED "\xee\x86\xa8" // U+e1a8 +#define ICON_MD_BLUETOOTH_DISABLED "\xee\x86\xa9" // U+e1a9 +#define ICON_MD_BLUETOOTH_DRIVE "\xee\xbf\xa5" // U+efe5 +#define ICON_MD_BLUETOOTH_SEARCHING "\xee\x86\xaa" // U+e1aa +#define ICON_MD_BLUR_CIRCULAR "\xee\x8e\xa2" // U+e3a2 +#define ICON_MD_BLUR_LINEAR "\xee\x8e\xa3" // U+e3a3 +#define ICON_MD_BLUR_OFF "\xee\x8e\xa4" // U+e3a4 +#define ICON_MD_BLUR_ON "\xee\x8e\xa5" // U+e3a5 +#define ICON_MD_BOLT "\xee\xa8\x8b" // U+ea0b +#define ICON_MD_BOOK "\xee\xa1\xa5" // U+e865 +#define ICON_MD_BOOK_ONLINE "\xef\x88\x97" // U+f217 +#define ICON_MD_BOOKMARK "\xee\xa1\xa6" // U+e866 +#define ICON_MD_BOOKMARK_ADD "\xee\x96\x98" // U+e598 +#define ICON_MD_BOOKMARK_ADDED "\xee\x96\x99" // U+e599 +#define ICON_MD_BOOKMARK_BORDER "\xee\xa1\xa7" // U+e867 +#define ICON_MD_BOOKMARK_OUTLINE "\xee\xa1\xa7" // U+e867 +#define ICON_MD_BOOKMARK_REMOVE "\xee\x96\x9a" // U+e59a +#define ICON_MD_BOOKMARKS "\xee\xa6\x8b" // U+e98b +#define ICON_MD_BORDER_ALL "\xee\x88\xa8" // U+e228 +#define ICON_MD_BORDER_BOTTOM "\xee\x88\xa9" // U+e229 +#define ICON_MD_BORDER_CLEAR "\xee\x88\xaa" // U+e22a +#define ICON_MD_BORDER_COLOR "\xee\x88\xab" // U+e22b +#define ICON_MD_BORDER_HORIZONTAL "\xee\x88\xac" // U+e22c +#define ICON_MD_BORDER_INNER "\xee\x88\xad" // U+e22d +#define ICON_MD_BORDER_LEFT "\xee\x88\xae" // U+e22e +#define ICON_MD_BORDER_OUTER "\xee\x88\xaf" // U+e22f +#define ICON_MD_BORDER_RIGHT "\xee\x88\xb0" // U+e230 +#define ICON_MD_BORDER_STYLE "\xee\x88\xb1" // U+e231 +#define ICON_MD_BORDER_TOP "\xee\x88\xb2" // U+e232 +#define ICON_MD_BORDER_VERTICAL "\xee\x88\xb3" // U+e233 +#define ICON_MD_BOY "\xee\xad\xa7" // U+eb67 +#define ICON_MD_BRANDING_WATERMARK "\xee\x81\xab" // U+e06b +#define ICON_MD_BREAKFAST_DINING "\xee\xa9\x94" // U+ea54 +#define ICON_MD_BRIGHTNESS_1 "\xee\x8e\xa6" // U+e3a6 +#define ICON_MD_BRIGHTNESS_2 "\xee\x8e\xa7" // U+e3a7 +#define ICON_MD_BRIGHTNESS_3 "\xee\x8e\xa8" // U+e3a8 +#define ICON_MD_BRIGHTNESS_4 "\xee\x8e\xa9" // U+e3a9 +#define ICON_MD_BRIGHTNESS_5 "\xee\x8e\xaa" // U+e3aa +#define ICON_MD_BRIGHTNESS_6 "\xee\x8e\xab" // U+e3ab +#define ICON_MD_BRIGHTNESS_7 "\xee\x8e\xac" // U+e3ac +#define ICON_MD_BRIGHTNESS_AUTO "\xee\x86\xab" // U+e1ab +#define ICON_MD_BRIGHTNESS_HIGH "\xee\x86\xac" // U+e1ac +#define ICON_MD_BRIGHTNESS_LOW "\xee\x86\xad" // U+e1ad +#define ICON_MD_BRIGHTNESS_MEDIUM "\xee\x86\xae" // U+e1ae +#define ICON_MD_BROADCAST_ON_HOME "\xef\xa3\xb8" // U+f8f8 +#define ICON_MD_BROADCAST_ON_PERSONAL "\xef\xa3\xb9" // U+f8f9 +#define ICON_MD_BROKEN_IMAGE "\xee\x8e\xad" // U+e3ad +#define ICON_MD_BROWSE_GALLERY "\xee\xaf\x91" // U+ebd1 +#define ICON_MD_BROWSER_NOT_SUPPORTED "\xee\xbd\x87" // U+ef47 +#define ICON_MD_BROWSER_UPDATED "\xee\x9f\x8f" // U+e7cf +#define ICON_MD_BRUNCH_DINING "\xee\xa9\xb3" // U+ea73 +#define ICON_MD_BRUSH "\xee\x8e\xae" // U+e3ae +#define ICON_MD_BUBBLE_CHART "\xee\x9b\x9d" // U+e6dd +#define ICON_MD_BUG_REPORT "\xee\xa1\xa8" // U+e868 +#define ICON_MD_BUILD "\xee\xa1\xa9" // U+e869 +#define ICON_MD_BUILD_CIRCLE "\xee\xbd\x88" // U+ef48 +#define ICON_MD_BUNGALOW "\xee\x96\x91" // U+e591 +#define ICON_MD_BURST_MODE "\xee\x90\xbc" // U+e43c +#define ICON_MD_BUS_ALERT "\xee\xa6\x8f" // U+e98f +#define ICON_MD_BUSINESS "\xee\x82\xaf" // U+e0af +#define ICON_MD_BUSINESS_CENTER "\xee\xac\xbf" // U+eb3f +#define ICON_MD_CABIN "\xee\x96\x89" // U+e589 +#define ICON_MD_CABLE "\xee\xbf\xa6" // U+efe6 +#define ICON_MD_CACHED "\xee\xa1\xaa" // U+e86a +#define ICON_MD_CAKE "\xee\x9f\xa9" // U+e7e9 +#define ICON_MD_CALCULATE "\xee\xa9\x9f" // U+ea5f +#define ICON_MD_CALENDAR_MONTH "\xee\xaf\x8c" // U+ebcc +#define ICON_MD_CALENDAR_TODAY "\xee\xa4\xb5" // U+e935 +#define ICON_MD_CALENDAR_VIEW_DAY "\xee\xa4\xb6" // U+e936 +#define ICON_MD_CALENDAR_VIEW_MONTH "\xee\xbf\xa7" // U+efe7 +#define ICON_MD_CALENDAR_VIEW_WEEK "\xee\xbf\xa8" // U+efe8 +#define ICON_MD_CALL "\xee\x82\xb0" // U+e0b0 +#define ICON_MD_CALL_END "\xee\x82\xb1" // U+e0b1 +#define ICON_MD_CALL_MADE "\xee\x82\xb2" // U+e0b2 +#define ICON_MD_CALL_MERGE "\xee\x82\xb3" // U+e0b3 +#define ICON_MD_CALL_MISSED "\xee\x82\xb4" // U+e0b4 +#define ICON_MD_CALL_MISSED_OUTGOING "\xee\x83\xa4" // U+e0e4 +#define ICON_MD_CALL_RECEIVED "\xee\x82\xb5" // U+e0b5 +#define ICON_MD_CALL_SPLIT "\xee\x82\xb6" // U+e0b6 +#define ICON_MD_CALL_TO_ACTION "\xee\x81\xac" // U+e06c +#define ICON_MD_CAMERA "\xee\x8e\xaf" // U+e3af +#define ICON_MD_CAMERA_ALT "\xee\x8e\xb0" // U+e3b0 +#define ICON_MD_CAMERA_ENHANCE "\xee\xa3\xbc" // U+e8fc +#define ICON_MD_CAMERA_FRONT "\xee\x8e\xb1" // U+e3b1 +#define ICON_MD_CAMERA_INDOOR "\xee\xbf\xa9" // U+efe9 +#define ICON_MD_CAMERA_OUTDOOR "\xee\xbf\xaa" // U+efea +#define ICON_MD_CAMERA_REAR "\xee\x8e\xb2" // U+e3b2 +#define ICON_MD_CAMERA_ROLL "\xee\x8e\xb3" // U+e3b3 +#define ICON_MD_CAMERASWITCH "\xee\xbf\xab" // U+efeb +#define ICON_MD_CAMPAIGN "\xee\xbd\x89" // U+ef49 +#define ICON_MD_CANCEL "\xee\x97\x89" // U+e5c9 +#define ICON_MD_CANCEL_PRESENTATION "\xee\x83\xa9" // U+e0e9 +#define ICON_MD_CANCEL_SCHEDULE_SEND "\xee\xa8\xb9" // U+ea39 +#define ICON_MD_CANDLESTICK_CHART "\xee\xab\x94" // U+ead4 +#define ICON_MD_CAR_CRASH "\xee\xaf\xb2" // U+ebf2 +#define ICON_MD_CAR_RENTAL "\xee\xa9\x95" // U+ea55 +#define ICON_MD_CAR_REPAIR "\xee\xa9\x96" // U+ea56 +#define ICON_MD_CARD_GIFTCARD "\xee\xa3\xb6" // U+e8f6 +#define ICON_MD_CARD_MEMBERSHIP "\xee\xa3\xb7" // U+e8f7 +#define ICON_MD_CARD_TRAVEL "\xee\xa3\xb8" // U+e8f8 +#define ICON_MD_CARPENTER "\xef\x87\xb8" // U+f1f8 +#define ICON_MD_CASES "\xee\xa6\x92" // U+e992 +#define ICON_MD_CASINO "\xee\xad\x80" // U+eb40 +#define ICON_MD_CAST "\xee\x8c\x87" // U+e307 +#define ICON_MD_CAST_CONNECTED "\xee\x8c\x88" // U+e308 +#define ICON_MD_CAST_FOR_EDUCATION "\xee\xbf\xac" // U+efec +#define ICON_MD_CASTLE "\xee\xaa\xb1" // U+eab1 +#define ICON_MD_CATCHING_POKEMON "\xee\x94\x88" // U+e508 +#define ICON_MD_CATEGORY "\xee\x95\xb4" // U+e574 +#define ICON_MD_CELEBRATION "\xee\xa9\xa5" // U+ea65 +#define ICON_MD_CELL_TOWER "\xee\xae\xba" // U+ebba +#define ICON_MD_CELL_WIFI "\xee\x83\xac" // U+e0ec +#define ICON_MD_CENTER_FOCUS_STRONG "\xee\x8e\xb4" // U+e3b4 +#define ICON_MD_CENTER_FOCUS_WEAK "\xee\x8e\xb5" // U+e3b5 +#define ICON_MD_CHAIR "\xee\xbf\xad" // U+efed +#define ICON_MD_CHAIR_ALT "\xee\xbf\xae" // U+efee +#define ICON_MD_CHALET "\xee\x96\x85" // U+e585 +#define ICON_MD_CHANGE_CIRCLE "\xee\x8b\xa7" // U+e2e7 +#define ICON_MD_CHANGE_HISTORY "\xee\xa1\xab" // U+e86b +#define ICON_MD_CHARGING_STATION "\xef\x86\x9d" // U+f19d +#define ICON_MD_CHAT "\xee\x82\xb7" // U+e0b7 +#define ICON_MD_CHAT_BUBBLE "\xee\x83\x8a" // U+e0ca +#define ICON_MD_CHAT_BUBBLE_OUTLINE "\xee\x83\x8b" // U+e0cb +#define ICON_MD_CHECK "\xee\x97\x8a" // U+e5ca +#define ICON_MD_CHECK_BOX "\xee\xa0\xb4" // U+e834 +#define ICON_MD_CHECK_BOX_OUTLINE_BLANK "\xee\xa0\xb5" // U+e835 +#define ICON_MD_CHECK_CIRCLE "\xee\xa1\xac" // U+e86c +#define ICON_MD_CHECK_CIRCLE_OUTLINE "\xee\xa4\xad" // U+e92d +#define ICON_MD_CHECKLIST "\xee\x9a\xb1" // U+e6b1 +#define ICON_MD_CHECKLIST_RTL "\xee\x9a\xb3" // U+e6b3 +#define ICON_MD_CHECKROOM "\xef\x86\x9e" // U+f19e +#define ICON_MD_CHEVRON_LEFT "\xee\x97\x8b" // U+e5cb +#define ICON_MD_CHEVRON_RIGHT "\xee\x97\x8c" // U+e5cc +#define ICON_MD_CHILD_CARE "\xee\xad\x81" // U+eb41 +#define ICON_MD_CHILD_FRIENDLY "\xee\xad\x82" // U+eb42 +#define ICON_MD_CHROME_READER_MODE "\xee\xa1\xad" // U+e86d +#define ICON_MD_CHURCH "\xee\xaa\xae" // U+eaae +#define ICON_MD_CIRCLE "\xee\xbd\x8a" // U+ef4a +#define ICON_MD_CIRCLE_NOTIFICATIONS "\xee\xa6\x94" // U+e994 +#define ICON_MD_CLASS "\xee\xa1\xae" // U+e86e +#define ICON_MD_CLEAN_HANDS "\xef\x88\x9f" // U+f21f +#define ICON_MD_CLEANING_SERVICES "\xef\x83\xbf" // U+f0ff +#define ICON_MD_CLEAR "\xee\x85\x8c" // U+e14c +#define ICON_MD_CLEAR_ALL "\xee\x82\xb8" // U+e0b8 +#define ICON_MD_CLOSE "\xee\x97\x8d" // U+e5cd +#define ICON_MD_CLOSE_FULLSCREEN "\xef\x87\x8f" // U+f1cf +#define ICON_MD_CLOSED_CAPTION "\xee\x80\x9c" // U+e01c +#define ICON_MD_CLOSED_CAPTION_DISABLED "\xef\x87\x9c" // U+f1dc +#define ICON_MD_CLOSED_CAPTION_OFF "\xee\xa6\x96" // U+e996 +#define ICON_MD_CLOUD "\xee\x8a\xbd" // U+e2bd +#define ICON_MD_CLOUD_CIRCLE "\xee\x8a\xbe" // U+e2be +#define ICON_MD_CLOUD_DONE "\xee\x8a\xbf" // U+e2bf +#define ICON_MD_CLOUD_DOWNLOAD "\xee\x8b\x80" // U+e2c0 +#define ICON_MD_CLOUD_OFF "\xee\x8b\x81" // U+e2c1 +#define ICON_MD_CLOUD_QUEUE "\xee\x8b\x82" // U+e2c2 +#define ICON_MD_CLOUD_SYNC "\xee\xad\x9a" // U+eb5a +#define ICON_MD_CLOUD_UPLOAD "\xee\x8b\x83" // U+e2c3 +#define ICON_MD_CLOUDY_SNOWING "\xee\xa0\x90" // U+e810 +#define ICON_MD_CO2 "\xee\x9e\xb0" // U+e7b0 +#define ICON_MD_CO_PRESENT "\xee\xab\xb0" // U+eaf0 +#define ICON_MD_CODE "\xee\xa1\xaf" // U+e86f +#define ICON_MD_CODE_OFF "\xee\x93\xb3" // U+e4f3 +#define ICON_MD_COFFEE "\xee\xbf\xaf" // U+efef +#define ICON_MD_COFFEE_MAKER "\xee\xbf\xb0" // U+eff0 +#define ICON_MD_COLLECTIONS "\xee\x8e\xb6" // U+e3b6 +#define ICON_MD_COLLECTIONS_BOOKMARK "\xee\x90\xb1" // U+e431 +#define ICON_MD_COLOR_LENS "\xee\x8e\xb7" // U+e3b7 +#define ICON_MD_COLORIZE "\xee\x8e\xb8" // U+e3b8 +#define ICON_MD_COMMENT "\xee\x82\xb9" // U+e0b9 +#define ICON_MD_COMMENT_BANK "\xee\xa9\x8e" // U+ea4e +#define ICON_MD_COMMENTS_DISABLED "\xee\x9e\xa2" // U+e7a2 +#define ICON_MD_COMMIT "\xee\xab\xb5" // U+eaf5 +#define ICON_MD_COMMUTE "\xee\xa5\x80" // U+e940 +#define ICON_MD_COMPARE "\xee\x8e\xb9" // U+e3b9 +#define ICON_MD_COMPARE_ARROWS "\xee\xa4\x95" // U+e915 +#define ICON_MD_COMPASS_CALIBRATION "\xee\x95\xbc" // U+e57c +#define ICON_MD_COMPOST "\xee\x9d\xa1" // U+e761 +#define ICON_MD_COMPRESS "\xee\xa5\x8d" // U+e94d +#define ICON_MD_COMPUTER "\xee\x8c\x8a" // U+e30a +#define ICON_MD_CONFIRMATION_NUM "\xee\x98\xb8" // U+e638 +#define ICON_MD_CONFIRMATION_NUMBER "\xee\x98\xb8" // U+e638 +#define ICON_MD_CONNECT_WITHOUT_CONTACT "\xef\x88\xa3" // U+f223 +#define ICON_MD_CONNECTED_TV "\xee\xa6\x98" // U+e998 +#define ICON_MD_CONNECTING_AIRPORTS "\xee\x9f\x89" // U+e7c9 +#define ICON_MD_CONSTRUCTION "\xee\xa8\xbc" // U+ea3c +#define ICON_MD_CONTACT_EMERGENCY "\xef\xa3\x91" // U+f8d1 +#define ICON_MD_CONTACT_MAIL "\xee\x83\x90" // U+e0d0 +#define ICON_MD_CONTACT_PAGE "\xef\x88\xae" // U+f22e +#define ICON_MD_CONTACT_PHONE "\xee\x83\x8f" // U+e0cf +#define ICON_MD_CONTACT_SUPPORT "\xee\xa5\x8c" // U+e94c +#define ICON_MD_CONTACTLESS "\xee\xa9\xb1" // U+ea71 +#define ICON_MD_CONTACTS "\xee\x82\xba" // U+e0ba +#define ICON_MD_CONTENT_COPY "\xee\x85\x8d" // U+e14d +#define ICON_MD_CONTENT_CUT "\xee\x85\x8e" // U+e14e +#define ICON_MD_CONTENT_PASTE "\xee\x85\x8f" // U+e14f +#define ICON_MD_CONTENT_PASTE_GO "\xee\xaa\x8e" // U+ea8e +#define ICON_MD_CONTENT_PASTE_OFF "\xee\x93\xb8" // U+e4f8 +#define ICON_MD_CONTENT_PASTE_SEARCH "\xee\xaa\x9b" // U+ea9b +#define ICON_MD_CONTRAST "\xee\xac\xb7" // U+eb37 +#define ICON_MD_CONTROL_CAMERA "\xee\x81\xb4" // U+e074 +#define ICON_MD_CONTROL_POINT "\xee\x8e\xba" // U+e3ba +#define ICON_MD_CONTROL_POINT_DUPLICATE "\xee\x8e\xbb" // U+e3bb +#define ICON_MD_CONVEYOR_BELT "\xef\xa1\xa7" // U+f867 +#define ICON_MD_COOKIE "\xee\xaa\xac" // U+eaac +#define ICON_MD_COPY_ALL "\xee\x8b\xac" // U+e2ec +#define ICON_MD_COPYRIGHT "\xee\xa4\x8c" // U+e90c +#define ICON_MD_CORONAVIRUS "\xef\x88\xa1" // U+f221 +#define ICON_MD_CORPORATE_FARE "\xef\x87\x90" // U+f1d0 +#define ICON_MD_COTTAGE "\xee\x96\x87" // U+e587 +#define ICON_MD_COUNTERTOPS "\xef\x87\xb7" // U+f1f7 +#define ICON_MD_CREATE "\xee\x85\x90" // U+e150 +#define ICON_MD_CREATE_NEW_FOLDER "\xee\x8b\x8c" // U+e2cc +#define ICON_MD_CREDIT_CARD "\xee\xa1\xb0" // U+e870 +#define ICON_MD_CREDIT_CARD_OFF "\xee\x93\xb4" // U+e4f4 +#define ICON_MD_CREDIT_SCORE "\xee\xbf\xb1" // U+eff1 +#define ICON_MD_CRIB "\xee\x96\x88" // U+e588 +#define ICON_MD_CRISIS_ALERT "\xee\xaf\xa9" // U+ebe9 +#define ICON_MD_CROP "\xee\x8e\xbe" // U+e3be +#define ICON_MD_CROP_16_9 "\xee\x8e\xbc" // U+e3bc +#define ICON_MD_CROP_3_2 "\xee\x8e\xbd" // U+e3bd +#define ICON_MD_CROP_5_4 "\xee\x8e\xbf" // U+e3bf +#define ICON_MD_CROP_7_5 "\xee\x8f\x80" // U+e3c0 +#define ICON_MD_CROP_DIN "\xee\x8f\x81" // U+e3c1 +#define ICON_MD_CROP_FREE "\xee\x8f\x82" // U+e3c2 +#define ICON_MD_CROP_LANDSCAPE "\xee\x8f\x83" // U+e3c3 +#define ICON_MD_CROP_ORIGINAL "\xee\x8f\x84" // U+e3c4 +#define ICON_MD_CROP_PORTRAIT "\xee\x8f\x85" // U+e3c5 +#define ICON_MD_CROP_ROTATE "\xee\x90\xb7" // U+e437 +#define ICON_MD_CROP_SQUARE "\xee\x8f\x86" // U+e3c6 +#define ICON_MD_CRUELTY_FREE "\xee\x9e\x99" // U+e799 +#define ICON_MD_CSS "\xee\xae\x93" // U+eb93 +#define ICON_MD_CURRENCY_BITCOIN "\xee\xaf\x85" // U+ebc5 +#define ICON_MD_CURRENCY_EXCHANGE "\xee\xad\xb0" // U+eb70 +#define ICON_MD_CURRENCY_FRANC "\xee\xab\xba" // U+eafa +#define ICON_MD_CURRENCY_LIRA "\xee\xab\xaf" // U+eaef +#define ICON_MD_CURRENCY_POUND "\xee\xab\xb1" // U+eaf1 +#define ICON_MD_CURRENCY_RUBLE "\xee\xab\xac" // U+eaec +#define ICON_MD_CURRENCY_RUPEE "\xee\xab\xb7" // U+eaf7 +#define ICON_MD_CURRENCY_YEN "\xee\xab\xbb" // U+eafb +#define ICON_MD_CURRENCY_YUAN "\xee\xab\xb9" // U+eaf9 +#define ICON_MD_CURTAINS "\xee\xb0\x9e" // U+ec1e +#define ICON_MD_CURTAINS_CLOSED "\xee\xb0\x9d" // U+ec1d +#define ICON_MD_CYCLONE "\xee\xaf\x95" // U+ebd5 +#define ICON_MD_DANGEROUS "\xee\xa6\x9a" // U+e99a +#define ICON_MD_DARK_MODE "\xee\x94\x9c" // U+e51c +#define ICON_MD_DASHBOARD "\xee\xa1\xb1" // U+e871 +#define ICON_MD_DASHBOARD_CUSTOMIZE "\xee\xa6\x9b" // U+e99b +#define ICON_MD_DATA_ARRAY "\xee\xab\x91" // U+ead1 +#define ICON_MD_DATA_EXPLORATION "\xee\x9d\xaf" // U+e76f +#define ICON_MD_DATA_OBJECT "\xee\xab\x93" // U+ead3 +#define ICON_MD_DATA_SAVER_OFF "\xee\xbf\xb2" // U+eff2 +#define ICON_MD_DATA_SAVER_ON "\xee\xbf\xb3" // U+eff3 +#define ICON_MD_DATA_THRESHOLDING "\xee\xae\x9f" // U+eb9f +#define ICON_MD_DATA_USAGE "\xee\x86\xaf" // U+e1af +#define ICON_MD_DATASET "\xef\xa3\xae" // U+f8ee +#define ICON_MD_DATASET_LINKED "\xef\xa3\xaf" // U+f8ef +#define ICON_MD_DATE_RANGE "\xee\xa4\x96" // U+e916 +#define ICON_MD_DEBLUR "\xee\xad\xb7" // U+eb77 +#define ICON_MD_DECK "\xee\xa9\x82" // U+ea42 +#define ICON_MD_DEHAZE "\xee\x8f\x87" // U+e3c7 +#define ICON_MD_DELETE "\xee\xa1\xb2" // U+e872 +#define ICON_MD_DELETE_FOREVER "\xee\xa4\xab" // U+e92b +#define ICON_MD_DELETE_OUTLINE "\xee\xa4\xae" // U+e92e +#define ICON_MD_DELETE_SWEEP "\xee\x85\xac" // U+e16c +#define ICON_MD_DELIVERY_DINING "\xee\xa9\xb2" // U+ea72 +#define ICON_MD_DENSITY_LARGE "\xee\xae\xa9" // U+eba9 +#define ICON_MD_DENSITY_MEDIUM "\xee\xae\x9e" // U+eb9e +#define ICON_MD_DENSITY_SMALL "\xee\xae\xa8" // U+eba8 +#define ICON_MD_DEPARTURE_BOARD "\xee\x95\xb6" // U+e576 +#define ICON_MD_DESCRIPTION "\xee\xa1\xb3" // U+e873 +#define ICON_MD_DESELECT "\xee\xae\xb6" // U+ebb6 +#define ICON_MD_DESIGN_SERVICES "\xef\x84\x8a" // U+f10a +#define ICON_MD_DESK "\xef\xa3\xb4" // U+f8f4 +#define ICON_MD_DESKTOP_ACCESS_DISABLED "\xee\xa6\x9d" // U+e99d +#define ICON_MD_DESKTOP_MAC "\xee\x8c\x8b" // U+e30b +#define ICON_MD_DESKTOP_WINDOWS "\xee\x8c\x8c" // U+e30c +#define ICON_MD_DETAILS "\xee\x8f\x88" // U+e3c8 +#define ICON_MD_DEVELOPER_BOARD "\xee\x8c\x8d" // U+e30d +#define ICON_MD_DEVELOPER_BOARD_OFF "\xee\x93\xbf" // U+e4ff +#define ICON_MD_DEVELOPER_MODE "\xee\x86\xb0" // U+e1b0 +#define ICON_MD_DEVICE_HUB "\xee\x8c\xb5" // U+e335 +#define ICON_MD_DEVICE_THERMOSTAT "\xee\x87\xbf" // U+e1ff +#define ICON_MD_DEVICE_UNKNOWN "\xee\x8c\xb9" // U+e339 +#define ICON_MD_DEVICES "\xee\x86\xb1" // U+e1b1 +#define ICON_MD_DEVICES_FOLD "\xee\xaf\x9e" // U+ebde +#define ICON_MD_DEVICES_OTHER "\xee\x8c\xb7" // U+e337 +#define ICON_MD_DEW_POINT "\xef\xa1\xb9" // U+f879 +#define ICON_MD_DIALER_SIP "\xee\x82\xbb" // U+e0bb +#define ICON_MD_DIALPAD "\xee\x82\xbc" // U+e0bc +#define ICON_MD_DIAMOND "\xee\xab\x95" // U+ead5 +#define ICON_MD_DIFFERENCE "\xee\xad\xbd" // U+eb7d +#define ICON_MD_DINING "\xee\xbf\xb4" // U+eff4 +#define ICON_MD_DINNER_DINING "\xee\xa9\x97" // U+ea57 +#define ICON_MD_DIRECTIONS "\xee\x94\xae" // U+e52e +#define ICON_MD_DIRECTIONS_BIKE "\xee\x94\xaf" // U+e52f +#define ICON_MD_DIRECTIONS_BOAT "\xee\x94\xb2" // U+e532 +#define ICON_MD_DIRECTIONS_BOAT_FILLED "\xee\xbf\xb5" // U+eff5 +#define ICON_MD_DIRECTIONS_BUS "\xee\x94\xb0" // U+e530 +#define ICON_MD_DIRECTIONS_BUS_FILLED "\xee\xbf\xb6" // U+eff6 +#define ICON_MD_DIRECTIONS_CAR "\xee\x94\xb1" // U+e531 +#define ICON_MD_DIRECTIONS_CAR_FILLED "\xee\xbf\xb7" // U+eff7 +#define ICON_MD_DIRECTIONS_FERRY "\xee\x94\xb2" // U+e532 +#define ICON_MD_DIRECTIONS_OFF "\xef\x84\x8f" // U+f10f +#define ICON_MD_DIRECTIONS_RAILWAY "\xee\x94\xb4" // U+e534 +#define ICON_MD_DIRECTIONS_RAILWAY_FILLED "\xee\xbf\xb8" // U+eff8 +#define ICON_MD_DIRECTIONS_RUN "\xee\x95\xa6" // U+e566 +#define ICON_MD_DIRECTIONS_SUBWAY "\xee\x94\xb3" // U+e533 +#define ICON_MD_DIRECTIONS_SUBWAY_FILLED "\xee\xbf\xb9" // U+eff9 +#define ICON_MD_DIRECTIONS_TRAIN "\xee\x94\xb4" // U+e534 +#define ICON_MD_DIRECTIONS_TRANSIT "\xee\x94\xb5" // U+e535 +#define ICON_MD_DIRECTIONS_TRANSIT_FILLED "\xee\xbf\xba" // U+effa +#define ICON_MD_DIRECTIONS_WALK "\xee\x94\xb6" // U+e536 +#define ICON_MD_DIRTY_LENS "\xee\xbd\x8b" // U+ef4b +#define ICON_MD_DISABLED_BY_DEFAULT "\xef\x88\xb0" // U+f230 +#define ICON_MD_DISABLED_VISIBLE "\xee\x9d\xae" // U+e76e +#define ICON_MD_DISC_FULL "\xee\x98\x90" // U+e610 +#define ICON_MD_DISCORD "\xee\xa9\xac" // U+ea6c +#define ICON_MD_DISCOUNT "\xee\xaf\x89" // U+ebc9 +#define ICON_MD_DISPLAY_SETTINGS "\xee\xae\x97" // U+eb97 +#define ICON_MD_DIVERSITY_1 "\xef\xa3\x97" // U+f8d7 +#define ICON_MD_DIVERSITY_2 "\xef\xa3\x98" // U+f8d8 +#define ICON_MD_DIVERSITY_3 "\xef\xa3\x99" // U+f8d9 +#define ICON_MD_DND_FORWARDSLASH "\xee\x98\x91" // U+e611 +#define ICON_MD_DNS "\xee\xa1\xb5" // U+e875 +#define ICON_MD_DO_DISTURB "\xef\x82\x8c" // U+f08c +#define ICON_MD_DO_DISTURB_ALT "\xef\x82\x8d" // U+f08d +#define ICON_MD_DO_DISTURB_OFF "\xef\x82\x8e" // U+f08e +#define ICON_MD_DO_DISTURB_ON "\xef\x82\x8f" // U+f08f +#define ICON_MD_DO_NOT_DISTURB "\xee\x98\x92" // U+e612 +#define ICON_MD_DO_NOT_DISTURB_ALT "\xee\x98\x91" // U+e611 +#define ICON_MD_DO_NOT_DISTURB_OFF "\xee\x99\x83" // U+e643 +#define ICON_MD_DO_NOT_DISTURB_ON "\xee\x99\x84" // U+e644 +#define ICON_MD_DO_NOT_DISTURB_ON_TOTAL_SILENCE "\xee\xbf\xbb" // U+effb +#define ICON_MD_DO_NOT_STEP "\xef\x86\x9f" // U+f19f +#define ICON_MD_DO_NOT_TOUCH "\xef\x86\xb0" // U+f1b0 +#define ICON_MD_DOCK "\xee\x8c\x8e" // U+e30e +#define ICON_MD_DOCUMENT_SCANNER "\xee\x97\xba" // U+e5fa +#define ICON_MD_DOMAIN "\xee\x9f\xae" // U+e7ee +#define ICON_MD_DOMAIN_ADD "\xee\xad\xa2" // U+eb62 +#define ICON_MD_DOMAIN_DISABLED "\xee\x83\xaf" // U+e0ef +#define ICON_MD_DOMAIN_VERIFICATION "\xee\xbd\x8c" // U+ef4c +#define ICON_MD_DONE "\xee\xa1\xb6" // U+e876 +#define ICON_MD_DONE_ALL "\xee\xa1\xb7" // U+e877 +#define ICON_MD_DONE_OUTLINE "\xee\xa4\xaf" // U+e92f +#define ICON_MD_DONUT_LARGE "\xee\xa4\x97" // U+e917 +#define ICON_MD_DONUT_SMALL "\xee\xa4\x98" // U+e918 +#define ICON_MD_DOOR_BACK "\xee\xbf\xbc" // U+effc +#define ICON_MD_DOOR_FRONT "\xee\xbf\xbd" // U+effd +#define ICON_MD_DOOR_SLIDING "\xee\xbf\xbe" // U+effe +#define ICON_MD_DOORBELL "\xee\xbf\xbf" // U+efff +#define ICON_MD_DOUBLE_ARROW "\xee\xa9\x90" // U+ea50 +#define ICON_MD_DOWNHILL_SKIING "\xee\x94\x89" // U+e509 +#define ICON_MD_DOWNLOAD "\xef\x82\x90" // U+f090 +#define ICON_MD_DOWNLOAD_DONE "\xef\x82\x91" // U+f091 +#define ICON_MD_DOWNLOAD_FOR_OFFLINE "\xef\x80\x80" // U+f000 +#define ICON_MD_DOWNLOADING "\xef\x80\x81" // U+f001 +#define ICON_MD_DRAFTS "\xee\x85\x91" // U+e151 +#define ICON_MD_DRAG_HANDLE "\xee\x89\x9d" // U+e25d +#define ICON_MD_DRAG_INDICATOR "\xee\xa5\x85" // U+e945 +#define ICON_MD_DRAW "\xee\x9d\x86" // U+e746 +#define ICON_MD_DRIVE_ETA "\xee\x98\x93" // U+e613 +#define ICON_MD_DRIVE_FILE_MOVE "\xee\x99\xb5" // U+e675 +#define ICON_MD_DRIVE_FILE_MOVE_OUTLINE "\xee\xa6\xa1" // U+e9a1 +#define ICON_MD_DRIVE_FILE_MOVE_RTL "\xee\x9d\xad" // U+e76d +#define ICON_MD_DRIVE_FILE_RENAME_OUTLINE "\xee\xa6\xa2" // U+e9a2 +#define ICON_MD_DRIVE_FOLDER_UPLOAD "\xee\xa6\xa3" // U+e9a3 +#define ICON_MD_DRY "\xef\x86\xb3" // U+f1b3 +#define ICON_MD_DRY_CLEANING "\xee\xa9\x98" // U+ea58 +#define ICON_MD_DUO "\xee\xa6\xa5" // U+e9a5 +#define ICON_MD_DVR "\xee\x86\xb2" // U+e1b2 +#define ICON_MD_DYNAMIC_FEED "\xee\xa8\x94" // U+ea14 +#define ICON_MD_DYNAMIC_FORM "\xef\x86\xbf" // U+f1bf +#define ICON_MD_E_MOBILEDATA "\xef\x80\x82" // U+f002 +#define ICON_MD_EARBUDS "\xef\x80\x83" // U+f003 +#define ICON_MD_EARBUDS_BATTERY "\xef\x80\x84" // U+f004 +#define ICON_MD_EAST "\xef\x87\x9f" // U+f1df +#define ICON_MD_ECO "\xee\xa8\xb5" // U+ea35 +#define ICON_MD_EDGESENSOR_HIGH "\xef\x80\x85" // U+f005 +#define ICON_MD_EDGESENSOR_LOW "\xef\x80\x86" // U+f006 +#define ICON_MD_EDIT "\xee\x8f\x89" // U+e3c9 +#define ICON_MD_EDIT_ATTRIBUTES "\xee\x95\xb8" // U+e578 +#define ICON_MD_EDIT_CALENDAR "\xee\x9d\x82" // U+e742 +#define ICON_MD_EDIT_DOCUMENT "\xef\xa2\x8c" // U+f88c +#define ICON_MD_EDIT_LOCATION "\xee\x95\xa8" // U+e568 +#define ICON_MD_EDIT_LOCATION_ALT "\xee\x87\x85" // U+e1c5 +#define ICON_MD_EDIT_NOTE "\xee\x9d\x85" // U+e745 +#define ICON_MD_EDIT_NOTIFICATIONS "\xee\x94\xa5" // U+e525 +#define ICON_MD_EDIT_OFF "\xee\xa5\x90" // U+e950 +#define ICON_MD_EDIT_ROAD "\xee\xbd\x8d" // U+ef4d +#define ICON_MD_EDIT_SQUARE "\xef\xa2\x8d" // U+f88d +#define ICON_MD_EGG "\xee\xab\x8c" // U+eacc +#define ICON_MD_EGG_ALT "\xee\xab\x88" // U+eac8 +#define ICON_MD_EJECT "\xee\xa3\xbb" // U+e8fb +#define ICON_MD_ELDERLY "\xef\x88\x9a" // U+f21a +#define ICON_MD_ELDERLY_WOMAN "\xee\xad\xa9" // U+eb69 +#define ICON_MD_ELECTRIC_BIKE "\xee\xac\x9b" // U+eb1b +#define ICON_MD_ELECTRIC_BOLT "\xee\xb0\x9c" // U+ec1c +#define ICON_MD_ELECTRIC_CAR "\xee\xac\x9c" // U+eb1c +#define ICON_MD_ELECTRIC_METER "\xee\xb0\x9b" // U+ec1b +#define ICON_MD_ELECTRIC_MOPED "\xee\xac\x9d" // U+eb1d +#define ICON_MD_ELECTRIC_RICKSHAW "\xee\xac\x9e" // U+eb1e +#define ICON_MD_ELECTRIC_SCOOTER "\xee\xac\x9f" // U+eb1f +#define ICON_MD_ELECTRICAL_SERVICES "\xef\x84\x82" // U+f102 +#define ICON_MD_ELEVATOR "\xef\x86\xa0" // U+f1a0 +#define ICON_MD_EMAIL "\xee\x82\xbe" // U+e0be +#define ICON_MD_EMERGENCY "\xee\x87\xab" // U+e1eb +#define ICON_MD_EMERGENCY_RECORDING "\xee\xaf\xb4" // U+ebf4 +#define ICON_MD_EMERGENCY_SHARE "\xee\xaf\xb6" // U+ebf6 +#define ICON_MD_EMOJI_EMOTIONS "\xee\xa8\xa2" // U+ea22 +#define ICON_MD_EMOJI_EVENTS "\xee\xa8\xa3" // U+ea23 +#define ICON_MD_EMOJI_FLAGS "\xee\xa8\x9a" // U+ea1a +#define ICON_MD_EMOJI_FOOD_BEVERAGE "\xee\xa8\x9b" // U+ea1b +#define ICON_MD_EMOJI_NATURE "\xee\xa8\x9c" // U+ea1c +#define ICON_MD_EMOJI_OBJECTS "\xee\xa8\xa4" // U+ea24 +#define ICON_MD_EMOJI_PEOPLE "\xee\xa8\x9d" // U+ea1d +#define ICON_MD_EMOJI_SYMBOLS "\xee\xa8\x9e" // U+ea1e +#define ICON_MD_EMOJI_TRANSPORTATION "\xee\xa8\x9f" // U+ea1f +#define ICON_MD_ENERGY_SAVINGS_LEAF "\xee\xb0\x9a" // U+ec1a +#define ICON_MD_ENGINEERING "\xee\xa8\xbd" // U+ea3d +#define ICON_MD_ENHANCE_PHOTO_TRANSLATE "\xee\xa3\xbc" // U+e8fc +#define ICON_MD_ENHANCED_ENCRYPTION "\xee\x98\xbf" // U+e63f +#define ICON_MD_EQUALIZER "\xee\x80\x9d" // U+e01d +#define ICON_MD_ERROR "\xee\x80\x80" // U+e000 +#define ICON_MD_ERROR_OUTLINE "\xee\x80\x81" // U+e001 +#define ICON_MD_ESCALATOR "\xef\x86\xa1" // U+f1a1 +#define ICON_MD_ESCALATOR_WARNING "\xef\x86\xac" // U+f1ac +#define ICON_MD_EURO "\xee\xa8\x95" // U+ea15 +#define ICON_MD_EURO_SYMBOL "\xee\xa4\xa6" // U+e926 +#define ICON_MD_EV_STATION "\xee\x95\xad" // U+e56d +#define ICON_MD_EVENT "\xee\xa1\xb8" // U+e878 +#define ICON_MD_EVENT_AVAILABLE "\xee\x98\x94" // U+e614 +#define ICON_MD_EVENT_BUSY "\xee\x98\x95" // U+e615 +#define ICON_MD_EVENT_NOTE "\xee\x98\x96" // U+e616 +#define ICON_MD_EVENT_REPEAT "\xee\xad\xbb" // U+eb7b +#define ICON_MD_EVENT_SEAT "\xee\xa4\x83" // U+e903 +#define ICON_MD_EXIT_TO_APP "\xee\xa1\xb9" // U+e879 +#define ICON_MD_EXPAND "\xee\xa5\x8f" // U+e94f +#define ICON_MD_EXPAND_CIRCLE_DOWN "\xee\x9f\x8d" // U+e7cd +#define ICON_MD_EXPAND_LESS "\xee\x97\x8e" // U+e5ce +#define ICON_MD_EXPAND_MORE "\xee\x97\x8f" // U+e5cf +#define ICON_MD_EXPLICIT "\xee\x80\x9e" // U+e01e +#define ICON_MD_EXPLORE "\xee\xa1\xba" // U+e87a +#define ICON_MD_EXPLORE_OFF "\xee\xa6\xa8" // U+e9a8 +#define ICON_MD_EXPOSURE "\xee\x8f\x8a" // U+e3ca +#define ICON_MD_EXPOSURE_MINUS_1 "\xee\x8f\x8b" // U+e3cb +#define ICON_MD_EXPOSURE_MINUS_2 "\xee\x8f\x8c" // U+e3cc +#define ICON_MD_EXPOSURE_NEG_1 "\xee\x8f\x8b" // U+e3cb +#define ICON_MD_EXPOSURE_NEG_2 "\xee\x8f\x8c" // U+e3cc +#define ICON_MD_EXPOSURE_PLUS_1 "\xee\x8f\x8d" // U+e3cd +#define ICON_MD_EXPOSURE_PLUS_2 "\xee\x8f\x8e" // U+e3ce +#define ICON_MD_EXPOSURE_ZERO "\xee\x8f\x8f" // U+e3cf +#define ICON_MD_EXTENSION "\xee\xa1\xbb" // U+e87b +#define ICON_MD_EXTENSION_OFF "\xee\x93\xb5" // U+e4f5 +#define ICON_MD_FACE "\xee\xa1\xbc" // U+e87c +#define ICON_MD_FACE_2 "\xef\xa3\x9a" // U+f8da +#define ICON_MD_FACE_3 "\xef\xa3\x9b" // U+f8db +#define ICON_MD_FACE_4 "\xef\xa3\x9c" // U+f8dc +#define ICON_MD_FACE_5 "\xef\xa3\x9d" // U+f8dd +#define ICON_MD_FACE_6 "\xef\xa3\x9e" // U+f8de +#define ICON_MD_FACE_RETOUCHING_NATURAL "\xee\xbd\x8e" // U+ef4e +#define ICON_MD_FACE_RETOUCHING_OFF "\xef\x80\x87" // U+f007 +#define ICON_MD_FACEBOOK "\xef\x88\xb4" // U+f234 +#define ICON_MD_FACT_CHECK "\xef\x83\x85" // U+f0c5 +#define ICON_MD_FACTORY "\xee\xae\xbc" // U+ebbc +#define ICON_MD_FAMILY_RESTROOM "\xef\x86\xa2" // U+f1a2 +#define ICON_MD_FAST_FORWARD "\xee\x80\x9f" // U+e01f +#define ICON_MD_FAST_REWIND "\xee\x80\xa0" // U+e020 +#define ICON_MD_FASTFOOD "\xee\x95\xba" // U+e57a +#define ICON_MD_FAVORITE "\xee\xa1\xbd" // U+e87d +#define ICON_MD_FAVORITE_BORDER "\xee\xa1\xbe" // U+e87e +#define ICON_MD_FAVORITE_OUTLINE "\xee\xa1\xbe" // U+e87e +#define ICON_MD_FAX "\xee\xab\x98" // U+ead8 +#define ICON_MD_FEATURED_PLAY_LIST "\xee\x81\xad" // U+e06d +#define ICON_MD_FEATURED_VIDEO "\xee\x81\xae" // U+e06e +#define ICON_MD_FEED "\xef\x80\x89" // U+f009 +#define ICON_MD_FEEDBACK "\xee\xa1\xbf" // U+e87f +#define ICON_MD_FEMALE "\xee\x96\x90" // U+e590 +#define ICON_MD_FENCE "\xef\x87\xb6" // U+f1f6 +#define ICON_MD_FESTIVAL "\xee\xa9\xa8" // U+ea68 +#define ICON_MD_FIBER_DVR "\xee\x81\x9d" // U+e05d +#define ICON_MD_FIBER_MANUAL_RECORD "\xee\x81\xa1" // U+e061 +#define ICON_MD_FIBER_NEW "\xee\x81\x9e" // U+e05e +#define ICON_MD_FIBER_PIN "\xee\x81\xaa" // U+e06a +#define ICON_MD_FIBER_SMART_RECORD "\xee\x81\xa2" // U+e062 +#define ICON_MD_FILE_COPY "\xee\x85\xb3" // U+e173 +#define ICON_MD_FILE_DOWNLOAD "\xee\x8b\x84" // U+e2c4 +#define ICON_MD_FILE_DOWNLOAD_DONE "\xee\xa6\xaa" // U+e9aa +#define ICON_MD_FILE_DOWNLOAD_OFF "\xee\x93\xbe" // U+e4fe +#define ICON_MD_FILE_OPEN "\xee\xab\xb3" // U+eaf3 +#define ICON_MD_FILE_PRESENT "\xee\xa8\x8e" // U+ea0e +#define ICON_MD_FILE_UPLOAD "\xee\x8b\x86" // U+e2c6 +#define ICON_MD_FILE_UPLOAD_OFF "\xef\xa2\x86" // U+f886 +#define ICON_MD_FILTER "\xee\x8f\x93" // U+e3d3 +#define ICON_MD_FILTER_1 "\xee\x8f\x90" // U+e3d0 +#define ICON_MD_FILTER_2 "\xee\x8f\x91" // U+e3d1 +#define ICON_MD_FILTER_3 "\xee\x8f\x92" // U+e3d2 +#define ICON_MD_FILTER_4 "\xee\x8f\x94" // U+e3d4 +#define ICON_MD_FILTER_5 "\xee\x8f\x95" // U+e3d5 +#define ICON_MD_FILTER_6 "\xee\x8f\x96" // U+e3d6 +#define ICON_MD_FILTER_7 "\xee\x8f\x97" // U+e3d7 +#define ICON_MD_FILTER_8 "\xee\x8f\x98" // U+e3d8 +#define ICON_MD_FILTER_9 "\xee\x8f\x99" // U+e3d9 +#define ICON_MD_FILTER_9_PLUS "\xee\x8f\x9a" // U+e3da +#define ICON_MD_FILTER_ALT "\xee\xbd\x8f" // U+ef4f +#define ICON_MD_FILTER_ALT_OFF "\xee\xac\xb2" // U+eb32 +#define ICON_MD_FILTER_B_AND_W "\xee\x8f\x9b" // U+e3db +#define ICON_MD_FILTER_CENTER_FOCUS "\xee\x8f\x9c" // U+e3dc +#define ICON_MD_FILTER_DRAMA "\xee\x8f\x9d" // U+e3dd +#define ICON_MD_FILTER_FRAMES "\xee\x8f\x9e" // U+e3de +#define ICON_MD_FILTER_HDR "\xee\x8f\x9f" // U+e3df +#define ICON_MD_FILTER_LIST "\xee\x85\x92" // U+e152 +#define ICON_MD_FILTER_LIST_ALT "\xee\xa5\x8e" // U+e94e +#define ICON_MD_FILTER_LIST_OFF "\xee\xad\x97" // U+eb57 +#define ICON_MD_FILTER_NONE "\xee\x8f\xa0" // U+e3e0 +#define ICON_MD_FILTER_TILT_SHIFT "\xee\x8f\xa2" // U+e3e2 +#define ICON_MD_FILTER_VINTAGE "\xee\x8f\xa3" // U+e3e3 +#define ICON_MD_FIND_IN_PAGE "\xee\xa2\x80" // U+e880 +#define ICON_MD_FIND_REPLACE "\xee\xa2\x81" // U+e881 +#define ICON_MD_FINGERPRINT "\xee\xa4\x8d" // U+e90d +#define ICON_MD_FIRE_EXTINGUISHER "\xef\x87\x98" // U+f1d8 +#define ICON_MD_FIRE_HYDRANT "\xef\x86\xa3" // U+f1a3 +#define ICON_MD_FIRE_HYDRANT_ALT "\xef\xa3\xb1" // U+f8f1 +#define ICON_MD_FIRE_TRUCK "\xef\xa3\xb2" // U+f8f2 +#define ICON_MD_FIREPLACE "\xee\xa9\x83" // U+ea43 +#define ICON_MD_FIRST_PAGE "\xee\x97\x9c" // U+e5dc +#define ICON_MD_FIT_SCREEN "\xee\xa8\x90" // U+ea10 +#define ICON_MD_FITBIT "\xee\xa0\xab" // U+e82b +#define ICON_MD_FITNESS_CENTER "\xee\xad\x83" // U+eb43 +#define ICON_MD_FLAG "\xee\x85\x93" // U+e153 +#define ICON_MD_FLAG_CIRCLE "\xee\xab\xb8" // U+eaf8 +#define ICON_MD_FLAKY "\xee\xbd\x90" // U+ef50 +#define ICON_MD_FLARE "\xee\x8f\xa4" // U+e3e4 +#define ICON_MD_FLASH_AUTO "\xee\x8f\xa5" // U+e3e5 +#define ICON_MD_FLASH_OFF "\xee\x8f\xa6" // U+e3e6 +#define ICON_MD_FLASH_ON "\xee\x8f\xa7" // U+e3e7 +#define ICON_MD_FLASHLIGHT_OFF "\xef\x80\x8a" // U+f00a +#define ICON_MD_FLASHLIGHT_ON "\xef\x80\x8b" // U+f00b +#define ICON_MD_FLATWARE "\xef\x80\x8c" // U+f00c +#define ICON_MD_FLIGHT "\xee\x94\xb9" // U+e539 +#define ICON_MD_FLIGHT_CLASS "\xee\x9f\x8b" // U+e7cb +#define ICON_MD_FLIGHT_LAND "\xee\xa4\x84" // U+e904 +#define ICON_MD_FLIGHT_TAKEOFF "\xee\xa4\x85" // U+e905 +#define ICON_MD_FLIP "\xee\x8f\xa8" // U+e3e8 +#define ICON_MD_FLIP_CAMERA_ANDROID "\xee\xa8\xb7" // U+ea37 +#define ICON_MD_FLIP_CAMERA_IOS "\xee\xa8\xb8" // U+ea38 +#define ICON_MD_FLIP_TO_BACK "\xee\xa2\x82" // U+e882 +#define ICON_MD_FLIP_TO_FRONT "\xee\xa2\x83" // U+e883 +#define ICON_MD_FLOOD "\xee\xaf\xa6" // U+ebe6 +#define ICON_MD_FLOURESCENT "\xef\x80\x8d" // U+f00d +#define ICON_MD_FLUORESCENT "\xee\xb0\xb1" // U+ec31 +#define ICON_MD_FLUTTER_DASH "\xee\x80\x8b" // U+e00b +#define ICON_MD_FMD_BAD "\xef\x80\x8e" // U+f00e +#define ICON_MD_FMD_GOOD "\xef\x80\x8f" // U+f00f +#define ICON_MD_FOGGY "\xee\xa0\x98" // U+e818 +#define ICON_MD_FOLDER "\xee\x8b\x87" // U+e2c7 +#define ICON_MD_FOLDER_COPY "\xee\xae\xbd" // U+ebbd +#define ICON_MD_FOLDER_DELETE "\xee\xac\xb4" // U+eb34 +#define ICON_MD_FOLDER_OFF "\xee\xae\x83" // U+eb83 +#define ICON_MD_FOLDER_OPEN "\xee\x8b\x88" // U+e2c8 +#define ICON_MD_FOLDER_SHARED "\xee\x8b\x89" // U+e2c9 +#define ICON_MD_FOLDER_SPECIAL "\xee\x98\x97" // U+e617 +#define ICON_MD_FOLDER_ZIP "\xee\xac\xac" // U+eb2c +#define ICON_MD_FOLLOW_THE_SIGNS "\xef\x88\xa2" // U+f222 +#define ICON_MD_FONT_DOWNLOAD "\xee\x85\xa7" // U+e167 +#define ICON_MD_FONT_DOWNLOAD_OFF "\xee\x93\xb9" // U+e4f9 +#define ICON_MD_FOOD_BANK "\xef\x87\xb2" // U+f1f2 +#define ICON_MD_FOREST "\xee\xaa\x99" // U+ea99 +#define ICON_MD_FORK_LEFT "\xee\xae\xa0" // U+eba0 +#define ICON_MD_FORK_RIGHT "\xee\xae\xac" // U+ebac +#define ICON_MD_FORKLIFT "\xef\xa1\xa8" // U+f868 +#define ICON_MD_FORMAT_ALIGN_CENTER "\xee\x88\xb4" // U+e234 +#define ICON_MD_FORMAT_ALIGN_JUSTIFY "\xee\x88\xb5" // U+e235 +#define ICON_MD_FORMAT_ALIGN_LEFT "\xee\x88\xb6" // U+e236 +#define ICON_MD_FORMAT_ALIGN_RIGHT "\xee\x88\xb7" // U+e237 +#define ICON_MD_FORMAT_BOLD "\xee\x88\xb8" // U+e238 +#define ICON_MD_FORMAT_CLEAR "\xee\x88\xb9" // U+e239 +#define ICON_MD_FORMAT_COLOR_FILL "\xee\x88\xba" // U+e23a +#define ICON_MD_FORMAT_COLOR_RESET "\xee\x88\xbb" // U+e23b +#define ICON_MD_FORMAT_COLOR_TEXT "\xee\x88\xbc" // U+e23c +#define ICON_MD_FORMAT_INDENT_DECREASE "\xee\x88\xbd" // U+e23d +#define ICON_MD_FORMAT_INDENT_INCREASE "\xee\x88\xbe" // U+e23e +#define ICON_MD_FORMAT_ITALIC "\xee\x88\xbf" // U+e23f +#define ICON_MD_FORMAT_LINE_SPACING "\xee\x89\x80" // U+e240 +#define ICON_MD_FORMAT_LIST_BULLETED "\xee\x89\x81" // U+e241 +#define ICON_MD_FORMAT_LIST_BULLETED_ADD "\xef\xa1\x89" // U+f849 +#define ICON_MD_FORMAT_LIST_NUMBERED "\xee\x89\x82" // U+e242 +#define ICON_MD_FORMAT_LIST_NUMBERED_RTL "\xee\x89\xa7" // U+e267 +#define ICON_MD_FORMAT_OVERLINE "\xee\xad\xa5" // U+eb65 +#define ICON_MD_FORMAT_PAINT "\xee\x89\x83" // U+e243 +#define ICON_MD_FORMAT_QUOTE "\xee\x89\x84" // U+e244 +#define ICON_MD_FORMAT_SHAPES "\xee\x89\x9e" // U+e25e +#define ICON_MD_FORMAT_SIZE "\xee\x89\x85" // U+e245 +#define ICON_MD_FORMAT_STRIKETHROUGH "\xee\x89\x86" // U+e246 +#define ICON_MD_FORMAT_TEXTDIRECTION_L_TO_R "\xee\x89\x87" // U+e247 +#define ICON_MD_FORMAT_TEXTDIRECTION_R_TO_L "\xee\x89\x88" // U+e248 +#define ICON_MD_FORMAT_UNDERLINE "\xee\x89\x89" // U+e249 +#define ICON_MD_FORMAT_UNDERLINED "\xee\x89\x89" // U+e249 +#define ICON_MD_FORT "\xee\xaa\xad" // U+eaad +#define ICON_MD_FORUM "\xee\x82\xbf" // U+e0bf +#define ICON_MD_FORWARD "\xee\x85\x94" // U+e154 +#define ICON_MD_FORWARD_10 "\xee\x81\x96" // U+e056 +#define ICON_MD_FORWARD_30 "\xee\x81\x97" // U+e057 +#define ICON_MD_FORWARD_5 "\xee\x81\x98" // U+e058 +#define ICON_MD_FORWARD_TO_INBOX "\xef\x86\x87" // U+f187 +#define ICON_MD_FOUNDATION "\xef\x88\x80" // U+f200 +#define ICON_MD_FREE_BREAKFAST "\xee\xad\x84" // U+eb44 +#define ICON_MD_FREE_CANCELLATION "\xee\x9d\x88" // U+e748 +#define ICON_MD_FRONT_HAND "\xee\x9d\xa9" // U+e769 +#define ICON_MD_FRONT_LOADER "\xef\xa1\xa9" // U+f869 +#define ICON_MD_FULLSCREEN "\xee\x97\x90" // U+e5d0 +#define ICON_MD_FULLSCREEN_EXIT "\xee\x97\x91" // U+e5d1 +#define ICON_MD_FUNCTIONS "\xee\x89\x8a" // U+e24a +#define ICON_MD_G_MOBILEDATA "\xef\x80\x90" // U+f010 +#define ICON_MD_G_TRANSLATE "\xee\xa4\xa7" // U+e927 +#define ICON_MD_GAMEPAD "\xee\x8c\x8f" // U+e30f +#define ICON_MD_GAMES "\xee\x80\xa1" // U+e021 +#define ICON_MD_GARAGE "\xef\x80\x91" // U+f011 +#define ICON_MD_GAS_METER "\xee\xb0\x99" // U+ec19 +#define ICON_MD_GAVEL "\xee\xa4\x8e" // U+e90e +#define ICON_MD_GENERATING_TOKENS "\xee\x9d\x89" // U+e749 +#define ICON_MD_GESTURE "\xee\x85\x95" // U+e155 +#define ICON_MD_GET_APP "\xee\xa2\x84" // U+e884 +#define ICON_MD_GIF "\xee\xa4\x88" // U+e908 +#define ICON_MD_GIF_BOX "\xee\x9e\xa3" // U+e7a3 +#define ICON_MD_GIRL "\xee\xad\xa8" // U+eb68 +#define ICON_MD_GITE "\xee\x96\x8b" // U+e58b +#define ICON_MD_GOAT "\xf4\x8f\xbf\xbd" // U+10fffd +#define ICON_MD_GOLF_COURSE "\xee\xad\x85" // U+eb45 +#define ICON_MD_GPP_BAD "\xef\x80\x92" // U+f012 +#define ICON_MD_GPP_GOOD "\xef\x80\x93" // U+f013 +#define ICON_MD_GPP_MAYBE "\xef\x80\x94" // U+f014 +#define ICON_MD_GPS_FIXED "\xee\x86\xb3" // U+e1b3 +#define ICON_MD_GPS_NOT_FIXED "\xee\x86\xb4" // U+e1b4 +#define ICON_MD_GPS_OFF "\xee\x86\xb5" // U+e1b5 +#define ICON_MD_GRADE "\xee\xa2\x85" // U+e885 +#define ICON_MD_GRADIENT "\xee\x8f\xa9" // U+e3e9 +#define ICON_MD_GRADING "\xee\xa9\x8f" // U+ea4f +#define ICON_MD_GRAIN "\xee\x8f\xaa" // U+e3ea +#define ICON_MD_GRAPHIC_EQ "\xee\x86\xb8" // U+e1b8 +#define ICON_MD_GRASS "\xef\x88\x85" // U+f205 +#define ICON_MD_GRID_3X3 "\xef\x80\x95" // U+f015 +#define ICON_MD_GRID_4X4 "\xef\x80\x96" // U+f016 +#define ICON_MD_GRID_GOLDENRATIO "\xef\x80\x97" // U+f017 +#define ICON_MD_GRID_OFF "\xee\x8f\xab" // U+e3eb +#define ICON_MD_GRID_ON "\xee\x8f\xac" // U+e3ec +#define ICON_MD_GRID_VIEW "\xee\xa6\xb0" // U+e9b0 +#define ICON_MD_GROUP "\xee\x9f\xaf" // U+e7ef +#define ICON_MD_GROUP_ADD "\xee\x9f\xb0" // U+e7f0 +#define ICON_MD_GROUP_OFF "\xee\x9d\x87" // U+e747 +#define ICON_MD_GROUP_REMOVE "\xee\x9e\xad" // U+e7ad +#define ICON_MD_GROUP_WORK "\xee\xa2\x86" // U+e886 +#define ICON_MD_GROUPS "\xef\x88\xb3" // U+f233 +#define ICON_MD_GROUPS_2 "\xef\xa3\x9f" // U+f8df +#define ICON_MD_GROUPS_3 "\xef\xa3\xa0" // U+f8e0 +#define ICON_MD_H_MOBILEDATA "\xef\x80\x98" // U+f018 +#define ICON_MD_H_PLUS_MOBILEDATA "\xef\x80\x99" // U+f019 +#define ICON_MD_HAIL "\xee\xa6\xb1" // U+e9b1 +#define ICON_MD_HANDSHAKE "\xee\xaf\x8b" // U+ebcb +#define ICON_MD_HANDYMAN "\xef\x84\x8b" // U+f10b +#define ICON_MD_HARDWARE "\xee\xa9\x99" // U+ea59 +#define ICON_MD_HD "\xee\x81\x92" // U+e052 +#define ICON_MD_HDR_AUTO "\xef\x80\x9a" // U+f01a +#define ICON_MD_HDR_AUTO_SELECT "\xef\x80\x9b" // U+f01b +#define ICON_MD_HDR_ENHANCED_SELECT "\xee\xbd\x91" // U+ef51 +#define ICON_MD_HDR_OFF "\xee\x8f\xad" // U+e3ed +#define ICON_MD_HDR_OFF_SELECT "\xef\x80\x9c" // U+f01c +#define ICON_MD_HDR_ON "\xee\x8f\xae" // U+e3ee +#define ICON_MD_HDR_ON_SELECT "\xef\x80\x9d" // U+f01d +#define ICON_MD_HDR_PLUS "\xef\x80\x9e" // U+f01e +#define ICON_MD_HDR_STRONG "\xee\x8f\xb1" // U+e3f1 +#define ICON_MD_HDR_WEAK "\xee\x8f\xb2" // U+e3f2 +#define ICON_MD_HEADPHONES "\xef\x80\x9f" // U+f01f +#define ICON_MD_HEADPHONES_BATTERY "\xef\x80\xa0" // U+f020 +#define ICON_MD_HEADSET "\xee\x8c\x90" // U+e310 +#define ICON_MD_HEADSET_MIC "\xee\x8c\x91" // U+e311 +#define ICON_MD_HEADSET_OFF "\xee\x8c\xba" // U+e33a +#define ICON_MD_HEALING "\xee\x8f\xb3" // U+e3f3 +#define ICON_MD_HEALTH_AND_SAFETY "\xee\x87\x95" // U+e1d5 +#define ICON_MD_HEARING "\xee\x80\xa3" // U+e023 +#define ICON_MD_HEARING_DISABLED "\xef\x84\x84" // U+f104 +#define ICON_MD_HEART_BROKEN "\xee\xab\x82" // U+eac2 +#define ICON_MD_HEAT_PUMP "\xee\xb0\x98" // U+ec18 +#define ICON_MD_HEIGHT "\xee\xa8\x96" // U+ea16 +#define ICON_MD_HELP "\xee\xa2\x87" // U+e887 +#define ICON_MD_HELP_CENTER "\xef\x87\x80" // U+f1c0 +#define ICON_MD_HELP_OUTLINE "\xee\xa3\xbd" // U+e8fd +#define ICON_MD_HEVC "\xef\x80\xa1" // U+f021 +#define ICON_MD_HEXAGON "\xee\xac\xb9" // U+eb39 +#define ICON_MD_HIDE_IMAGE "\xef\x80\xa2" // U+f022 +#define ICON_MD_HIDE_SOURCE "\xef\x80\xa3" // U+f023 +#define ICON_MD_HIGH_QUALITY "\xee\x80\xa4" // U+e024 +#define ICON_MD_HIGHLIGHT "\xee\x89\x9f" // U+e25f +#define ICON_MD_HIGHLIGHT_ALT "\xee\xbd\x92" // U+ef52 +#define ICON_MD_HIGHLIGHT_OFF "\xee\xa2\x88" // U+e888 +#define ICON_MD_HIGHLIGHT_REMOVE "\xee\xa2\x88" // U+e888 +#define ICON_MD_HIKING "\xee\x94\x8a" // U+e50a +#define ICON_MD_HISTORY "\xee\xa2\x89" // U+e889 +#define ICON_MD_HISTORY_EDU "\xee\xa8\xbe" // U+ea3e +#define ICON_MD_HISTORY_TOGGLE_OFF "\xef\x85\xbd" // U+f17d +#define ICON_MD_HIVE "\xee\xaa\xa6" // U+eaa6 +#define ICON_MD_HLS "\xee\xae\x8a" // U+eb8a +#define ICON_MD_HLS_OFF "\xee\xae\x8c" // U+eb8c +#define ICON_MD_HOLIDAY_VILLAGE "\xee\x96\x8a" // U+e58a +#define ICON_MD_HOME "\xee\xa2\x8a" // U+e88a +#define ICON_MD_HOME_FILLED "\xee\xa6\xb2" // U+e9b2 +#define ICON_MD_HOME_MAX "\xef\x80\xa4" // U+f024 +#define ICON_MD_HOME_MINI "\xef\x80\xa5" // U+f025 +#define ICON_MD_HOME_REPAIR_SERVICE "\xef\x84\x80" // U+f100 +#define ICON_MD_HOME_WORK "\xee\xa8\x89" // U+ea09 +#define ICON_MD_HORIZONTAL_DISTRIBUTE "\xee\x80\x94" // U+e014 +#define ICON_MD_HORIZONTAL_RULE "\xef\x84\x88" // U+f108 +#define ICON_MD_HORIZONTAL_SPLIT "\xee\xa5\x87" // U+e947 +#define ICON_MD_HOT_TUB "\xee\xad\x86" // U+eb46 +#define ICON_MD_HOTEL "\xee\x94\xba" // U+e53a +#define ICON_MD_HOTEL_CLASS "\xee\x9d\x83" // U+e743 +#define ICON_MD_HOURGLASS_BOTTOM "\xee\xa9\x9c" // U+ea5c +#define ICON_MD_HOURGLASS_DISABLED "\xee\xbd\x93" // U+ef53 +#define ICON_MD_HOURGLASS_EMPTY "\xee\xa2\x8b" // U+e88b +#define ICON_MD_HOURGLASS_FULL "\xee\xa2\x8c" // U+e88c +#define ICON_MD_HOURGLASS_TOP "\xee\xa9\x9b" // U+ea5b +#define ICON_MD_HOUSE "\xee\xa9\x84" // U+ea44 +#define ICON_MD_HOUSE_SIDING "\xef\x88\x82" // U+f202 +#define ICON_MD_HOUSEBOAT "\xee\x96\x84" // U+e584 +#define ICON_MD_HOW_TO_REG "\xee\x85\xb4" // U+e174 +#define ICON_MD_HOW_TO_VOTE "\xee\x85\xb5" // U+e175 +#define ICON_MD_HTML "\xee\xad\xbe" // U+eb7e +#define ICON_MD_HTTP "\xee\xa4\x82" // U+e902 +#define ICON_MD_HTTPS "\xee\xa2\x8d" // U+e88d +#define ICON_MD_HUB "\xee\xa7\xb4" // U+e9f4 +#define ICON_MD_HVAC "\xef\x84\x8e" // U+f10e +#define ICON_MD_ICE_SKATING "\xee\x94\x8b" // U+e50b +#define ICON_MD_ICECREAM "\xee\xa9\xa9" // U+ea69 +#define ICON_MD_IMAGE "\xee\x8f\xb4" // U+e3f4 +#define ICON_MD_IMAGE_ASPECT_RATIO "\xee\x8f\xb5" // U+e3f5 +#define ICON_MD_IMAGE_NOT_SUPPORTED "\xef\x84\x96" // U+f116 +#define ICON_MD_IMAGE_SEARCH "\xee\x90\xbf" // U+e43f +#define ICON_MD_IMAGESEARCH_ROLLER "\xee\xa6\xb4" // U+e9b4 +#define ICON_MD_IMPORT_CONTACTS "\xee\x83\xa0" // U+e0e0 +#define ICON_MD_IMPORT_EXPORT "\xee\x83\x83" // U+e0c3 +#define ICON_MD_IMPORTANT_DEVICES "\xee\xa4\x92" // U+e912 +#define ICON_MD_INBOX "\xee\x85\x96" // U+e156 +#define ICON_MD_INCOMPLETE_CIRCLE "\xee\x9e\x9b" // U+e79b +#define ICON_MD_INDETERMINATE_CHECK_BOX "\xee\xa4\x89" // U+e909 +#define ICON_MD_INFO "\xee\xa2\x8e" // U+e88e +#define ICON_MD_INFO_OUTLINE "\xee\xa2\x8f" // U+e88f +#define ICON_MD_INPUT "\xee\xa2\x90" // U+e890 +#define ICON_MD_INSERT_CHART "\xee\x89\x8b" // U+e24b +#define ICON_MD_INSERT_CHART_OUTLINED "\xee\x89\xaa" // U+e26a +#define ICON_MD_INSERT_COMMENT "\xee\x89\x8c" // U+e24c +#define ICON_MD_INSERT_DRIVE_FILE "\xee\x89\x8d" // U+e24d +#define ICON_MD_INSERT_EMOTICON "\xee\x89\x8e" // U+e24e +#define ICON_MD_INSERT_INVITATION "\xee\x89\x8f" // U+e24f +#define ICON_MD_INSERT_LINK "\xee\x89\x90" // U+e250 +#define ICON_MD_INSERT_PAGE_BREAK "\xee\xab\x8a" // U+eaca +#define ICON_MD_INSERT_PHOTO "\xee\x89\x91" // U+e251 +#define ICON_MD_INSIGHTS "\xef\x82\x92" // U+f092 +#define ICON_MD_INSTALL_DESKTOP "\xee\xad\xb1" // U+eb71 +#define ICON_MD_INSTALL_MOBILE "\xee\xad\xb2" // U+eb72 +#define ICON_MD_INTEGRATION_INSTRUCTIONS "\xee\xbd\x94" // U+ef54 +#define ICON_MD_INTERESTS "\xee\x9f\x88" // U+e7c8 +#define ICON_MD_INTERPRETER_MODE "\xee\xa0\xbb" // U+e83b +#define ICON_MD_INVENTORY "\xee\x85\xb9" // U+e179 +#define ICON_MD_INVENTORY_2 "\xee\x86\xa1" // U+e1a1 +#define ICON_MD_INVERT_COLORS "\xee\xa2\x91" // U+e891 +#define ICON_MD_INVERT_COLORS_OFF "\xee\x83\x84" // U+e0c4 +#define ICON_MD_INVERT_COLORS_ON "\xee\xa2\x91" // U+e891 +#define ICON_MD_IOS_SHARE "\xee\x9a\xb8" // U+e6b8 +#define ICON_MD_IRON "\xee\x96\x83" // U+e583 +#define ICON_MD_ISO "\xee\x8f\xb6" // U+e3f6 +#define ICON_MD_JAVASCRIPT "\xee\xad\xbc" // U+eb7c +#define ICON_MD_JOIN_FULL "\xee\xab\xab" // U+eaeb +#define ICON_MD_JOIN_INNER "\xee\xab\xb4" // U+eaf4 +#define ICON_MD_JOIN_LEFT "\xee\xab\xb2" // U+eaf2 +#define ICON_MD_JOIN_RIGHT "\xee\xab\xaa" // U+eaea +#define ICON_MD_KAYAKING "\xee\x94\x8c" // U+e50c +#define ICON_MD_KEBAB_DINING "\xee\xa1\x82" // U+e842 +#define ICON_MD_KEY "\xee\x9c\xbc" // U+e73c +#define ICON_MD_KEY_OFF "\xee\xae\x84" // U+eb84 +#define ICON_MD_KEYBOARD "\xee\x8c\x92" // U+e312 +#define ICON_MD_KEYBOARD_ALT "\xef\x80\xa8" // U+f028 +#define ICON_MD_KEYBOARD_ARROW_DOWN "\xee\x8c\x93" // U+e313 +#define ICON_MD_KEYBOARD_ARROW_LEFT "\xee\x8c\x94" // U+e314 +#define ICON_MD_KEYBOARD_ARROW_RIGHT "\xee\x8c\x95" // U+e315 +#define ICON_MD_KEYBOARD_ARROW_UP "\xee\x8c\x96" // U+e316 +#define ICON_MD_KEYBOARD_BACKSPACE "\xee\x8c\x97" // U+e317 +#define ICON_MD_KEYBOARD_CAPSLOCK "\xee\x8c\x98" // U+e318 +#define ICON_MD_KEYBOARD_COMMAND "\xee\xab\xa0" // U+eae0 +#define ICON_MD_KEYBOARD_COMMAND_KEY "\xee\xab\xa7" // U+eae7 +#define ICON_MD_KEYBOARD_CONTROL "\xee\x97\x93" // U+e5d3 +#define ICON_MD_KEYBOARD_CONTROL_KEY "\xee\xab\xa6" // U+eae6 +#define ICON_MD_KEYBOARD_DOUBLE_ARROW_DOWN "\xee\xab\x90" // U+ead0 +#define ICON_MD_KEYBOARD_DOUBLE_ARROW_LEFT "\xee\xab\x83" // U+eac3 +#define ICON_MD_KEYBOARD_DOUBLE_ARROW_RIGHT "\xee\xab\x89" // U+eac9 +#define ICON_MD_KEYBOARD_DOUBLE_ARROW_UP "\xee\xab\x8f" // U+eacf +#define ICON_MD_KEYBOARD_HIDE "\xee\x8c\x9a" // U+e31a +#define ICON_MD_KEYBOARD_OPTION "\xee\xab\x9f" // U+eadf +#define ICON_MD_KEYBOARD_OPTION_KEY "\xee\xab\xa8" // U+eae8 +#define ICON_MD_KEYBOARD_RETURN "\xee\x8c\x9b" // U+e31b +#define ICON_MD_KEYBOARD_TAB "\xee\x8c\x9c" // U+e31c +#define ICON_MD_KEYBOARD_VOICE "\xee\x8c\x9d" // U+e31d +#define ICON_MD_KING_BED "\xee\xa9\x85" // U+ea45 +#define ICON_MD_KITCHEN "\xee\xad\x87" // U+eb47 +#define ICON_MD_KITESURFING "\xee\x94\x8d" // U+e50d +#define ICON_MD_LABEL "\xee\xa2\x92" // U+e892 +#define ICON_MD_LABEL_IMPORTANT "\xee\xa4\xb7" // U+e937 +#define ICON_MD_LABEL_IMPORTANT_OUTLINE "\xee\xa5\x88" // U+e948 +#define ICON_MD_LABEL_OFF "\xee\xa6\xb6" // U+e9b6 +#define ICON_MD_LABEL_OUTLINE "\xee\xa2\x93" // U+e893 +#define ICON_MD_LAN "\xee\xac\xaf" // U+eb2f +#define ICON_MD_LANDSCAPE "\xee\x8f\xb7" // U+e3f7 +#define ICON_MD_LANDSLIDE "\xee\xaf\x97" // U+ebd7 +#define ICON_MD_LANGUAGE "\xee\xa2\x94" // U+e894 +#define ICON_MD_LAPTOP "\xee\x8c\x9e" // U+e31e +#define ICON_MD_LAPTOP_CHROMEBOOK "\xee\x8c\x9f" // U+e31f +#define ICON_MD_LAPTOP_MAC "\xee\x8c\xa0" // U+e320 +#define ICON_MD_LAPTOP_WINDOWS "\xee\x8c\xa1" // U+e321 +#define ICON_MD_LAST_PAGE "\xee\x97\x9d" // U+e5dd +#define ICON_MD_LAUNCH "\xee\xa2\x95" // U+e895 +#define ICON_MD_LAYERS "\xee\x94\xbb" // U+e53b +#define ICON_MD_LAYERS_CLEAR "\xee\x94\xbc" // U+e53c +#define ICON_MD_LEADERBOARD "\xef\x88\x8c" // U+f20c +#define ICON_MD_LEAK_ADD "\xee\x8f\xb8" // U+e3f8 +#define ICON_MD_LEAK_REMOVE "\xee\x8f\xb9" // U+e3f9 +#define ICON_MD_LEAVE_BAGS_AT_HOME "\xef\x88\x9b" // U+f21b +#define ICON_MD_LEGEND_TOGGLE "\xef\x84\x9b" // U+f11b +#define ICON_MD_LENS "\xee\x8f\xba" // U+e3fa +#define ICON_MD_LENS_BLUR "\xef\x80\xa9" // U+f029 +#define ICON_MD_LIBRARY_ADD "\xee\x80\xae" // U+e02e +#define ICON_MD_LIBRARY_ADD_CHECK "\xee\xa6\xb7" // U+e9b7 +#define ICON_MD_LIBRARY_BOOKS "\xee\x80\xaf" // U+e02f +#define ICON_MD_LIBRARY_MUSIC "\xee\x80\xb0" // U+e030 +#define ICON_MD_LIGHT "\xef\x80\xaa" // U+f02a +#define ICON_MD_LIGHT_MODE "\xee\x94\x98" // U+e518 +#define ICON_MD_LIGHTBULB "\xee\x83\xb0" // U+e0f0 +#define ICON_MD_LIGHTBULB_CIRCLE "\xee\xaf\xbe" // U+ebfe +#define ICON_MD_LIGHTBULB_OUTLINE "\xee\xa4\x8f" // U+e90f +#define ICON_MD_LINE_AXIS "\xee\xaa\x9a" // U+ea9a +#define ICON_MD_LINE_STYLE "\xee\xa4\x99" // U+e919 +#define ICON_MD_LINE_WEIGHT "\xee\xa4\x9a" // U+e91a +#define ICON_MD_LINEAR_SCALE "\xee\x89\xa0" // U+e260 +#define ICON_MD_LINK "\xee\x85\x97" // U+e157 +#define ICON_MD_LINK_OFF "\xee\x85\xaf" // U+e16f +#define ICON_MD_LINKED_CAMERA "\xee\x90\xb8" // U+e438 +#define ICON_MD_LIQUOR "\xee\xa9\xa0" // U+ea60 +#define ICON_MD_LIST "\xee\xa2\x96" // U+e896 +#define ICON_MD_LIST_ALT "\xee\x83\xae" // U+e0ee +#define ICON_MD_LIVE_HELP "\xee\x83\x86" // U+e0c6 +#define ICON_MD_LIVE_TV "\xee\x98\xb9" // U+e639 +#define ICON_MD_LIVING "\xef\x80\xab" // U+f02b +#define ICON_MD_LOCAL_ACTIVITY "\xee\x94\xbf" // U+e53f +#define ICON_MD_LOCAL_AIRPORT "\xee\x94\xbd" // U+e53d +#define ICON_MD_LOCAL_ATM "\xee\x94\xbe" // U+e53e +#define ICON_MD_LOCAL_ATTRACTION "\xee\x94\xbf" // U+e53f +#define ICON_MD_LOCAL_BAR "\xee\x95\x80" // U+e540 +#define ICON_MD_LOCAL_CAFE "\xee\x95\x81" // U+e541 +#define ICON_MD_LOCAL_CAR_WASH "\xee\x95\x82" // U+e542 +#define ICON_MD_LOCAL_CONVENIENCE_STORE "\xee\x95\x83" // U+e543 +#define ICON_MD_LOCAL_DINING "\xee\x95\x96" // U+e556 +#define ICON_MD_LOCAL_DRINK "\xee\x95\x84" // U+e544 +#define ICON_MD_LOCAL_FIRE_DEPARTMENT "\xee\xbd\x95" // U+ef55 +#define ICON_MD_LOCAL_FLORIST "\xee\x95\x85" // U+e545 +#define ICON_MD_LOCAL_GAS_STATION "\xee\x95\x86" // U+e546 +#define ICON_MD_LOCAL_GROCERY_STORE "\xee\x95\x87" // U+e547 +#define ICON_MD_LOCAL_HOSPITAL "\xee\x95\x88" // U+e548 +#define ICON_MD_LOCAL_HOTEL "\xee\x95\x89" // U+e549 +#define ICON_MD_LOCAL_LAUNDRY_SERVICE "\xee\x95\x8a" // U+e54a +#define ICON_MD_LOCAL_LIBRARY "\xee\x95\x8b" // U+e54b +#define ICON_MD_LOCAL_MALL "\xee\x95\x8c" // U+e54c +#define ICON_MD_LOCAL_MOVIES "\xee\x95\x8d" // U+e54d +#define ICON_MD_LOCAL_OFFER "\xee\x95\x8e" // U+e54e +#define ICON_MD_LOCAL_PARKING "\xee\x95\x8f" // U+e54f +#define ICON_MD_LOCAL_PHARMACY "\xee\x95\x90" // U+e550 +#define ICON_MD_LOCAL_PHONE "\xee\x95\x91" // U+e551 +#define ICON_MD_LOCAL_PIZZA "\xee\x95\x92" // U+e552 +#define ICON_MD_LOCAL_PLAY "\xee\x95\x93" // U+e553 +#define ICON_MD_LOCAL_POLICE "\xee\xbd\x96" // U+ef56 +#define ICON_MD_LOCAL_POST_OFFICE "\xee\x95\x94" // U+e554 +#define ICON_MD_LOCAL_PRINT_SHOP "\xee\x95\x95" // U+e555 +#define ICON_MD_LOCAL_PRINTSHOP "\xee\x95\x95" // U+e555 +#define ICON_MD_LOCAL_RESTAURANT "\xee\x95\x96" // U+e556 +#define ICON_MD_LOCAL_SEE "\xee\x95\x97" // U+e557 +#define ICON_MD_LOCAL_SHIPPING "\xee\x95\x98" // U+e558 +#define ICON_MD_LOCAL_TAXI "\xee\x95\x99" // U+e559 +#define ICON_MD_LOCATION_CITY "\xee\x9f\xb1" // U+e7f1 +#define ICON_MD_LOCATION_DISABLED "\xee\x86\xb6" // U+e1b6 +#define ICON_MD_LOCATION_HISTORY "\xee\x95\x9a" // U+e55a +#define ICON_MD_LOCATION_OFF "\xee\x83\x87" // U+e0c7 +#define ICON_MD_LOCATION_ON "\xee\x83\x88" // U+e0c8 +#define ICON_MD_LOCATION_PIN "\xef\x87\x9b" // U+f1db +#define ICON_MD_LOCATION_SEARCHING "\xee\x86\xb7" // U+e1b7 +#define ICON_MD_LOCK "\xee\xa2\x97" // U+e897 +#define ICON_MD_LOCK_CLOCK "\xee\xbd\x97" // U+ef57 +#define ICON_MD_LOCK_OPEN "\xee\xa2\x98" // U+e898 +#define ICON_MD_LOCK_OUTLINE "\xee\xa2\x99" // U+e899 +#define ICON_MD_LOCK_PERSON "\xef\xa3\xb3" // U+f8f3 +#define ICON_MD_LOCK_RESET "\xee\xab\x9e" // U+eade +#define ICON_MD_LOGIN "\xee\xa9\xb7" // U+ea77 +#define ICON_MD_LOGO_DEV "\xee\xab\x96" // U+ead6 +#define ICON_MD_LOGOUT "\xee\xa6\xba" // U+e9ba +#define ICON_MD_LOOKS "\xee\x8f\xbc" // U+e3fc +#define ICON_MD_LOOKS_3 "\xee\x8f\xbb" // U+e3fb +#define ICON_MD_LOOKS_4 "\xee\x8f\xbd" // U+e3fd +#define ICON_MD_LOOKS_5 "\xee\x8f\xbe" // U+e3fe +#define ICON_MD_LOOKS_6 "\xee\x8f\xbf" // U+e3ff +#define ICON_MD_LOOKS_ONE "\xee\x90\x80" // U+e400 +#define ICON_MD_LOOKS_TWO "\xee\x90\x81" // U+e401 +#define ICON_MD_LOOP "\xee\x80\xa8" // U+e028 +#define ICON_MD_LOUPE "\xee\x90\x82" // U+e402 +#define ICON_MD_LOW_PRIORITY "\xee\x85\xad" // U+e16d +#define ICON_MD_LOYALTY "\xee\xa2\x9a" // U+e89a +#define ICON_MD_LTE_MOBILEDATA "\xef\x80\xac" // U+f02c +#define ICON_MD_LTE_PLUS_MOBILEDATA "\xef\x80\xad" // U+f02d +#define ICON_MD_LUGGAGE "\xef\x88\xb5" // U+f235 +#define ICON_MD_LUNCH_DINING "\xee\xa9\xa1" // U+ea61 +#define ICON_MD_LYRICS "\xee\xb0\x8b" // U+ec0b +#define ICON_MD_MACRO_OFF "\xef\xa3\x92" // U+f8d2 +#define ICON_MD_MAIL "\xee\x85\x98" // U+e158 +#define ICON_MD_MAIL_LOCK "\xee\xb0\x8a" // U+ec0a +#define ICON_MD_MAIL_OUTLINE "\xee\x83\xa1" // U+e0e1 +#define ICON_MD_MALE "\xee\x96\x8e" // U+e58e +#define ICON_MD_MAN "\xee\x93\xab" // U+e4eb +#define ICON_MD_MAN_2 "\xef\xa3\xa1" // U+f8e1 +#define ICON_MD_MAN_3 "\xef\xa3\xa2" // U+f8e2 +#define ICON_MD_MAN_4 "\xef\xa3\xa3" // U+f8e3 +#define ICON_MD_MANAGE_ACCOUNTS "\xef\x80\xae" // U+f02e +#define ICON_MD_MANAGE_HISTORY "\xee\xaf\xa7" // U+ebe7 +#define ICON_MD_MANAGE_SEARCH "\xef\x80\xaf" // U+f02f +#define ICON_MD_MAP "\xee\x95\x9b" // U+e55b +#define ICON_MD_MAPS_HOME_WORK "\xef\x80\xb0" // U+f030 +#define ICON_MD_MAPS_UGC "\xee\xbd\x98" // U+ef58 +#define ICON_MD_MARGIN "\xee\xa6\xbb" // U+e9bb +#define ICON_MD_MARK_AS_UNREAD "\xee\xa6\xbc" // U+e9bc +#define ICON_MD_MARK_CHAT_READ "\xef\x86\x8b" // U+f18b +#define ICON_MD_MARK_CHAT_UNREAD "\xef\x86\x89" // U+f189 +#define ICON_MD_MARK_EMAIL_READ "\xef\x86\x8c" // U+f18c +#define ICON_MD_MARK_EMAIL_UNREAD "\xef\x86\x8a" // U+f18a +#define ICON_MD_MARK_UNREAD_CHAT_ALT "\xee\xae\x9d" // U+eb9d +#define ICON_MD_MARKUNREAD "\xee\x85\x99" // U+e159 +#define ICON_MD_MARKUNREAD_MAILBOX "\xee\xa2\x9b" // U+e89b +#define ICON_MD_MASKS "\xef\x88\x98" // U+f218 +#define ICON_MD_MAXIMIZE "\xee\xa4\xb0" // U+e930 +#define ICON_MD_MEDIA_BLUETOOTH_OFF "\xef\x80\xb1" // U+f031 +#define ICON_MD_MEDIA_BLUETOOTH_ON "\xef\x80\xb2" // U+f032 +#define ICON_MD_MEDIATION "\xee\xbe\xa7" // U+efa7 +#define ICON_MD_MEDICAL_INFORMATION "\xee\xaf\xad" // U+ebed +#define ICON_MD_MEDICAL_SERVICES "\xef\x84\x89" // U+f109 +#define ICON_MD_MEDICATION "\xef\x80\xb3" // U+f033 +#define ICON_MD_MEDICATION_LIQUID "\xee\xaa\x87" // U+ea87 +#define ICON_MD_MEETING_ROOM "\xee\xad\x8f" // U+eb4f +#define ICON_MD_MEMORY "\xee\x8c\xa2" // U+e322 +#define ICON_MD_MENU "\xee\x97\x92" // U+e5d2 +#define ICON_MD_MENU_BOOK "\xee\xa8\x99" // U+ea19 +#define ICON_MD_MENU_OPEN "\xee\xa6\xbd" // U+e9bd +#define ICON_MD_MERGE "\xee\xae\x98" // U+eb98 +#define ICON_MD_MERGE_TYPE "\xee\x89\x92" // U+e252 +#define ICON_MD_MESSAGE "\xee\x83\x89" // U+e0c9 +#define ICON_MD_MESSENGER "\xee\x83\x8a" // U+e0ca +#define ICON_MD_MESSENGER_OUTLINE "\xee\x83\x8b" // U+e0cb +#define ICON_MD_MIC "\xee\x80\xa9" // U+e029 +#define ICON_MD_MIC_EXTERNAL_OFF "\xee\xbd\x99" // U+ef59 +#define ICON_MD_MIC_EXTERNAL_ON "\xee\xbd\x9a" // U+ef5a +#define ICON_MD_MIC_NONE "\xee\x80\xaa" // U+e02a +#define ICON_MD_MIC_OFF "\xee\x80\xab" // U+e02b +#define ICON_MD_MICROWAVE "\xef\x88\x84" // U+f204 +#define ICON_MD_MILITARY_TECH "\xee\xa8\xbf" // U+ea3f +#define ICON_MD_MINIMIZE "\xee\xa4\xb1" // U+e931 +#define ICON_MD_MINOR_CRASH "\xee\xaf\xb1" // U+ebf1 +#define ICON_MD_MISCELLANEOUS_SERVICES "\xef\x84\x8c" // U+f10c +#define ICON_MD_MISSED_VIDEO_CALL "\xee\x81\xb3" // U+e073 +#define ICON_MD_MMS "\xee\x98\x98" // U+e618 +#define ICON_MD_MOBILE_FRIENDLY "\xee\x88\x80" // U+e200 +#define ICON_MD_MOBILE_OFF "\xee\x88\x81" // U+e201 +#define ICON_MD_MOBILE_SCREEN_SHARE "\xee\x83\xa7" // U+e0e7 +#define ICON_MD_MOBILEDATA_OFF "\xef\x80\xb4" // U+f034 +#define ICON_MD_MODE "\xef\x82\x97" // U+f097 +#define ICON_MD_MODE_COMMENT "\xee\x89\x93" // U+e253 +#define ICON_MD_MODE_EDIT "\xee\x89\x94" // U+e254 +#define ICON_MD_MODE_EDIT_OUTLINE "\xef\x80\xb5" // U+f035 +#define ICON_MD_MODE_FAN_OFF "\xee\xb0\x97" // U+ec17 +#define ICON_MD_MODE_NIGHT "\xef\x80\xb6" // U+f036 +#define ICON_MD_MODE_OF_TRAVEL "\xee\x9f\x8e" // U+e7ce +#define ICON_MD_MODE_STANDBY "\xef\x80\xb7" // U+f037 +#define ICON_MD_MODEL_TRAINING "\xef\x83\x8f" // U+f0cf +#define ICON_MD_MONETIZATION_ON "\xee\x89\xa3" // U+e263 +#define ICON_MD_MONEY "\xee\x95\xbd" // U+e57d +#define ICON_MD_MONEY_OFF "\xee\x89\x9c" // U+e25c +#define ICON_MD_MONEY_OFF_CSRED "\xef\x80\xb8" // U+f038 +#define ICON_MD_MONITOR "\xee\xbd\x9b" // U+ef5b +#define ICON_MD_MONITOR_HEART "\xee\xaa\xa2" // U+eaa2 +#define ICON_MD_MONITOR_WEIGHT "\xef\x80\xb9" // U+f039 +#define ICON_MD_MONOCHROME_PHOTOS "\xee\x90\x83" // U+e403 +#define ICON_MD_MOOD "\xee\x9f\xb2" // U+e7f2 +#define ICON_MD_MOOD_BAD "\xee\x9f\xb3" // U+e7f3 +#define ICON_MD_MOPED "\xee\xac\xa8" // U+eb28 +#define ICON_MD_MORE "\xee\x98\x99" // U+e619 +#define ICON_MD_MORE_HORIZ "\xee\x97\x93" // U+e5d3 +#define ICON_MD_MORE_TIME "\xee\xa9\x9d" // U+ea5d +#define ICON_MD_MORE_VERT "\xee\x97\x94" // U+e5d4 +#define ICON_MD_MOSQUE "\xee\xaa\xb2" // U+eab2 +#define ICON_MD_MOTION_PHOTOS_AUTO "\xef\x80\xba" // U+f03a +#define ICON_MD_MOTION_PHOTOS_OFF "\xee\xa7\x80" // U+e9c0 +#define ICON_MD_MOTION_PHOTOS_ON "\xee\xa7\x81" // U+e9c1 +#define ICON_MD_MOTION_PHOTOS_PAUSE "\xef\x88\xa7" // U+f227 +#define ICON_MD_MOTION_PHOTOS_PAUSED "\xee\xa7\x82" // U+e9c2 +#define ICON_MD_MOTORCYCLE "\xee\xa4\x9b" // U+e91b +#define ICON_MD_MOUSE "\xee\x8c\xa3" // U+e323 +#define ICON_MD_MOVE_DOWN "\xee\xad\xa1" // U+eb61 +#define ICON_MD_MOVE_TO_INBOX "\xee\x85\xa8" // U+e168 +#define ICON_MD_MOVE_UP "\xee\xad\xa4" // U+eb64 +#define ICON_MD_MOVIE "\xee\x80\xac" // U+e02c +#define ICON_MD_MOVIE_CREATION "\xee\x90\x84" // U+e404 +#define ICON_MD_MOVIE_EDIT "\xef\xa1\x80" // U+f840 +#define ICON_MD_MOVIE_FILTER "\xee\x90\xba" // U+e43a +#define ICON_MD_MOVING "\xee\x94\x81" // U+e501 +#define ICON_MD_MP "\xee\xa7\x83" // U+e9c3 +#define ICON_MD_MULTILINE_CHART "\xee\x9b\x9f" // U+e6df +#define ICON_MD_MULTIPLE_STOP "\xef\x86\xb9" // U+f1b9 +#define ICON_MD_MULTITRACK_AUDIO "\xee\x86\xb8" // U+e1b8 +#define ICON_MD_MUSEUM "\xee\xa8\xb6" // U+ea36 +#define ICON_MD_MUSIC_NOTE "\xee\x90\x85" // U+e405 +#define ICON_MD_MUSIC_OFF "\xee\x91\x80" // U+e440 +#define ICON_MD_MUSIC_VIDEO "\xee\x81\xa3" // U+e063 +#define ICON_MD_MY_LIBRARY_ADD "\xee\x80\xae" // U+e02e +#define ICON_MD_MY_LIBRARY_BOOKS "\xee\x80\xaf" // U+e02f +#define ICON_MD_MY_LIBRARY_MUSIC "\xee\x80\xb0" // U+e030 +#define ICON_MD_MY_LOCATION "\xee\x95\x9c" // U+e55c +#define ICON_MD_NAT "\xee\xbd\x9c" // U+ef5c +#define ICON_MD_NATURE "\xee\x90\x86" // U+e406 +#define ICON_MD_NATURE_PEOPLE "\xee\x90\x87" // U+e407 +#define ICON_MD_NAVIGATE_BEFORE "\xee\x90\x88" // U+e408 +#define ICON_MD_NAVIGATE_NEXT "\xee\x90\x89" // U+e409 +#define ICON_MD_NAVIGATION "\xee\x95\x9d" // U+e55d +#define ICON_MD_NEAR_ME "\xee\x95\xa9" // U+e569 +#define ICON_MD_NEAR_ME_DISABLED "\xef\x87\xaf" // U+f1ef +#define ICON_MD_NEARBY_ERROR "\xef\x80\xbb" // U+f03b +#define ICON_MD_NEARBY_OFF "\xef\x80\xbc" // U+f03c +#define ICON_MD_NEST_CAM_WIRED_STAND "\xee\xb0\x96" // U+ec16 +#define ICON_MD_NETWORK_CELL "\xee\x86\xb9" // U+e1b9 +#define ICON_MD_NETWORK_CHECK "\xee\x99\x80" // U+e640 +#define ICON_MD_NETWORK_LOCKED "\xee\x98\x9a" // U+e61a +#define ICON_MD_NETWORK_PING "\xee\xaf\x8a" // U+ebca +#define ICON_MD_NETWORK_WIFI "\xee\x86\xba" // U+e1ba +#define ICON_MD_NETWORK_WIFI_1_BAR "\xee\xaf\xa4" // U+ebe4 +#define ICON_MD_NETWORK_WIFI_2_BAR "\xee\xaf\x96" // U+ebd6 +#define ICON_MD_NETWORK_WIFI_3_BAR "\xee\xaf\xa1" // U+ebe1 +#define ICON_MD_NEW_LABEL "\xee\x98\x89" // U+e609 +#define ICON_MD_NEW_RELEASES "\xee\x80\xb1" // U+e031 +#define ICON_MD_NEWSPAPER "\xee\xae\x81" // U+eb81 +#define ICON_MD_NEXT_PLAN "\xee\xbd\x9d" // U+ef5d +#define ICON_MD_NEXT_WEEK "\xee\x85\xaa" // U+e16a +#define ICON_MD_NFC "\xee\x86\xbb" // U+e1bb +#define ICON_MD_NIGHT_SHELTER "\xef\x87\xb1" // U+f1f1 +#define ICON_MD_NIGHTLIFE "\xee\xa9\xa2" // U+ea62 +#define ICON_MD_NIGHTLIGHT "\xef\x80\xbd" // U+f03d +#define ICON_MD_NIGHTLIGHT_ROUND "\xee\xbd\x9e" // U+ef5e +#define ICON_MD_NIGHTS_STAY "\xee\xa9\x86" // U+ea46 +#define ICON_MD_NO_ACCOUNTS "\xef\x80\xbe" // U+f03e +#define ICON_MD_NO_ADULT_CONTENT "\xef\xa3\xbe" // U+f8fe +#define ICON_MD_NO_BACKPACK "\xef\x88\xb7" // U+f237 +#define ICON_MD_NO_CELL "\xef\x86\xa4" // U+f1a4 +#define ICON_MD_NO_CRASH "\xee\xaf\xb0" // U+ebf0 +#define ICON_MD_NO_DRINKS "\xef\x86\xa5" // U+f1a5 +#define ICON_MD_NO_ENCRYPTION "\xee\x99\x81" // U+e641 +#define ICON_MD_NO_ENCRYPTION_GMAILERRORRED "\xef\x80\xbf" // U+f03f +#define ICON_MD_NO_FLASH "\xef\x86\xa6" // U+f1a6 +#define ICON_MD_NO_FOOD "\xef\x86\xa7" // U+f1a7 +#define ICON_MD_NO_LUGGAGE "\xef\x88\xbb" // U+f23b +#define ICON_MD_NO_MEALS "\xef\x87\x96" // U+f1d6 +#define ICON_MD_NO_MEALS_OULINE "\xef\x88\xa9" // U+f229 +#define ICON_MD_NO_MEETING_ROOM "\xee\xad\x8e" // U+eb4e +#define ICON_MD_NO_PHOTOGRAPHY "\xef\x86\xa8" // U+f1a8 +#define ICON_MD_NO_SIM "\xee\x83\x8c" // U+e0cc +#define ICON_MD_NO_STROLLER "\xef\x86\xaf" // U+f1af +#define ICON_MD_NO_TRANSFER "\xef\x87\x95" // U+f1d5 +#define ICON_MD_NOISE_AWARE "\xee\xaf\xac" // U+ebec +#define ICON_MD_NOISE_CONTROL_OFF "\xee\xaf\xb3" // U+ebf3 +#define ICON_MD_NORDIC_WALKING "\xee\x94\x8e" // U+e50e +#define ICON_MD_NORTH "\xef\x87\xa0" // U+f1e0 +#define ICON_MD_NORTH_EAST "\xef\x87\xa1" // U+f1e1 +#define ICON_MD_NORTH_WEST "\xef\x87\xa2" // U+f1e2 +#define ICON_MD_NOT_ACCESSIBLE "\xef\x83\xbe" // U+f0fe +#define ICON_MD_NOT_INTERESTED "\xee\x80\xb3" // U+e033 +#define ICON_MD_NOT_LISTED_LOCATION "\xee\x95\xb5" // U+e575 +#define ICON_MD_NOT_STARTED "\xef\x83\x91" // U+f0d1 +#define ICON_MD_NOTE "\xee\x81\xaf" // U+e06f +#define ICON_MD_NOTE_ADD "\xee\xa2\x9c" // U+e89c +#define ICON_MD_NOTE_ALT "\xef\x81\x80" // U+f040 +#define ICON_MD_NOTES "\xee\x89\xac" // U+e26c +#define ICON_MD_NOTIFICATION_ADD "\xee\x8e\x99" // U+e399 +#define ICON_MD_NOTIFICATION_IMPORTANT "\xee\x80\x84" // U+e004 +#define ICON_MD_NOTIFICATIONS "\xee\x9f\xb4" // U+e7f4 +#define ICON_MD_NOTIFICATIONS_ACTIVE "\xee\x9f\xb7" // U+e7f7 +#define ICON_MD_NOTIFICATIONS_NONE "\xee\x9f\xb5" // U+e7f5 +#define ICON_MD_NOTIFICATIONS_OFF "\xee\x9f\xb6" // U+e7f6 +#define ICON_MD_NOTIFICATIONS_ON "\xee\x9f\xb7" // U+e7f7 +#define ICON_MD_NOTIFICATIONS_PAUSED "\xee\x9f\xb8" // U+e7f8 +#define ICON_MD_NOW_WALLPAPER "\xee\x86\xbc" // U+e1bc +#define ICON_MD_NOW_WIDGETS "\xee\x86\xbd" // U+e1bd +#define ICON_MD_NUMBERS "\xee\xab\x87" // U+eac7 +#define ICON_MD_OFFLINE_BOLT "\xee\xa4\xb2" // U+e932 +#define ICON_MD_OFFLINE_PIN "\xee\xa4\x8a" // U+e90a +#define ICON_MD_OFFLINE_SHARE "\xee\xa7\x85" // U+e9c5 +#define ICON_MD_OIL_BARREL "\xee\xb0\x95" // U+ec15 +#define ICON_MD_ON_DEVICE_TRAINING "\xee\xaf\xbd" // U+ebfd +#define ICON_MD_ONDEMAND_VIDEO "\xee\x98\xba" // U+e63a +#define ICON_MD_ONLINE_PREDICTION "\xef\x83\xab" // U+f0eb +#define ICON_MD_OPACITY "\xee\xa4\x9c" // U+e91c +#define ICON_MD_OPEN_IN_BROWSER "\xee\xa2\x9d" // U+e89d +#define ICON_MD_OPEN_IN_FULL "\xef\x87\x8e" // U+f1ce +#define ICON_MD_OPEN_IN_NEW "\xee\xa2\x9e" // U+e89e +#define ICON_MD_OPEN_IN_NEW_OFF "\xee\x93\xb6" // U+e4f6 +#define ICON_MD_OPEN_WITH "\xee\xa2\x9f" // U+e89f +#define ICON_MD_OTHER_HOUSES "\xee\x96\x8c" // U+e58c +#define ICON_MD_OUTBOND "\xef\x88\xa8" // U+f228 +#define ICON_MD_OUTBOUND "\xee\x87\x8a" // U+e1ca +#define ICON_MD_OUTBOX "\xee\xbd\x9f" // U+ef5f +#define ICON_MD_OUTDOOR_GRILL "\xee\xa9\x87" // U+ea47 +#define ICON_MD_OUTGOING_MAIL "\xef\x83\x92" // U+f0d2 +#define ICON_MD_OUTLET "\xef\x87\x94" // U+f1d4 +#define ICON_MD_OUTLINED_FLAG "\xee\x85\xae" // U+e16e +#define ICON_MD_OUTPUT "\xee\xae\xbe" // U+ebbe +#define ICON_MD_PADDING "\xee\xa7\x88" // U+e9c8 +#define ICON_MD_PAGES "\xee\x9f\xb9" // U+e7f9 +#define ICON_MD_PAGEVIEW "\xee\xa2\xa0" // U+e8a0 +#define ICON_MD_PAID "\xef\x81\x81" // U+f041 +#define ICON_MD_PALETTE "\xee\x90\x8a" // U+e40a +#define ICON_MD_PALLET "\xef\xa1\xaa" // U+f86a +#define ICON_MD_PAN_TOOL "\xee\xa4\xa5" // U+e925 +#define ICON_MD_PAN_TOOL_ALT "\xee\xae\xb9" // U+ebb9 +#define ICON_MD_PANORAMA "\xee\x90\x8b" // U+e40b +#define ICON_MD_PANORAMA_FISH_EYE "\xee\x90\x8c" // U+e40c +#define ICON_MD_PANORAMA_FISHEYE "\xee\x90\x8c" // U+e40c +#define ICON_MD_PANORAMA_HORIZONTAL "\xee\x90\x8d" // U+e40d +#define ICON_MD_PANORAMA_HORIZONTAL_SELECT "\xee\xbd\xa0" // U+ef60 +#define ICON_MD_PANORAMA_PHOTOSPHERE "\xee\xa7\x89" // U+e9c9 +#define ICON_MD_PANORAMA_PHOTOSPHERE_SELECT "\xee\xa7\x8a" // U+e9ca +#define ICON_MD_PANORAMA_VERTICAL "\xee\x90\x8e" // U+e40e +#define ICON_MD_PANORAMA_VERTICAL_SELECT "\xee\xbd\xa1" // U+ef61 +#define ICON_MD_PANORAMA_WIDE_ANGLE "\xee\x90\x8f" // U+e40f +#define ICON_MD_PANORAMA_WIDE_ANGLE_SELECT "\xee\xbd\xa2" // U+ef62 +#define ICON_MD_PARAGLIDING "\xee\x94\x8f" // U+e50f +#define ICON_MD_PARK "\xee\xa9\xa3" // U+ea63 +#define ICON_MD_PARTY_MODE "\xee\x9f\xba" // U+e7fa +#define ICON_MD_PASSWORD "\xef\x81\x82" // U+f042 +#define ICON_MD_PATTERN "\xef\x81\x83" // U+f043 +#define ICON_MD_PAUSE "\xee\x80\xb4" // U+e034 +#define ICON_MD_PAUSE_CIRCLE "\xee\x86\xa2" // U+e1a2 +#define ICON_MD_PAUSE_CIRCLE_FILLED "\xee\x80\xb5" // U+e035 +#define ICON_MD_PAUSE_CIRCLE_OUTLINE "\xee\x80\xb6" // U+e036 +#define ICON_MD_PAUSE_PRESENTATION "\xee\x83\xaa" // U+e0ea +#define ICON_MD_PAYMENT "\xee\xa2\xa1" // U+e8a1 +#define ICON_MD_PAYMENTS "\xee\xbd\xa3" // U+ef63 +#define ICON_MD_PAYPAL "\xee\xaa\x8d" // U+ea8d +#define ICON_MD_PEDAL_BIKE "\xee\xac\xa9" // U+eb29 +#define ICON_MD_PENDING "\xee\xbd\xa4" // U+ef64 +#define ICON_MD_PENDING_ACTIONS "\xef\x86\xbb" // U+f1bb +#define ICON_MD_PENTAGON "\xee\xad\x90" // U+eb50 +#define ICON_MD_PEOPLE "\xee\x9f\xbb" // U+e7fb +#define ICON_MD_PEOPLE_ALT "\xee\xa8\xa1" // U+ea21 +#define ICON_MD_PEOPLE_OUTLINE "\xee\x9f\xbc" // U+e7fc +#define ICON_MD_PERCENT "\xee\xad\x98" // U+eb58 +#define ICON_MD_PERM_CAMERA_MIC "\xee\xa2\xa2" // U+e8a2 +#define ICON_MD_PERM_CONTACT_CAL "\xee\xa2\xa3" // U+e8a3 +#define ICON_MD_PERM_CONTACT_CALENDAR "\xee\xa2\xa3" // U+e8a3 +#define ICON_MD_PERM_DATA_SETTING "\xee\xa2\xa4" // U+e8a4 +#define ICON_MD_PERM_DEVICE_INFO "\xee\xa2\xa5" // U+e8a5 +#define ICON_MD_PERM_DEVICE_INFORMATION "\xee\xa2\xa5" // U+e8a5 +#define ICON_MD_PERM_IDENTITY "\xee\xa2\xa6" // U+e8a6 +#define ICON_MD_PERM_MEDIA "\xee\xa2\xa7" // U+e8a7 +#define ICON_MD_PERM_PHONE_MSG "\xee\xa2\xa8" // U+e8a8 +#define ICON_MD_PERM_SCAN_WIFI "\xee\xa2\xa9" // U+e8a9 +#define ICON_MD_PERSON "\xee\x9f\xbd" // U+e7fd +#define ICON_MD_PERSON_2 "\xef\xa3\xa4" // U+f8e4 +#define ICON_MD_PERSON_3 "\xef\xa3\xa5" // U+f8e5 +#define ICON_MD_PERSON_4 "\xef\xa3\xa6" // U+f8e6 +#define ICON_MD_PERSON_ADD "\xee\x9f\xbe" // U+e7fe +#define ICON_MD_PERSON_ADD_ALT "\xee\xa9\x8d" // U+ea4d +#define ICON_MD_PERSON_ADD_ALT_1 "\xee\xbd\xa5" // U+ef65 +#define ICON_MD_PERSON_ADD_DISABLED "\xee\xa7\x8b" // U+e9cb +#define ICON_MD_PERSON_OFF "\xee\x94\x90" // U+e510 +#define ICON_MD_PERSON_OUTLINE "\xee\x9f\xbf" // U+e7ff +#define ICON_MD_PERSON_PIN "\xee\x95\x9a" // U+e55a +#define ICON_MD_PERSON_PIN_CIRCLE "\xee\x95\xaa" // U+e56a +#define ICON_MD_PERSON_REMOVE "\xee\xbd\xa6" // U+ef66 +#define ICON_MD_PERSON_REMOVE_ALT_1 "\xee\xbd\xa7" // U+ef67 +#define ICON_MD_PERSON_SEARCH "\xef\x84\x86" // U+f106 +#define ICON_MD_PERSONAL_INJURY "\xee\x9b\x9a" // U+e6da +#define ICON_MD_PERSONAL_VIDEO "\xee\x98\xbb" // U+e63b +#define ICON_MD_PEST_CONTROL "\xef\x83\xba" // U+f0fa +#define ICON_MD_PEST_CONTROL_RODENT "\xef\x83\xbd" // U+f0fd +#define ICON_MD_PETS "\xee\xa4\x9d" // U+e91d +#define ICON_MD_PHISHING "\xee\xab\x97" // U+ead7 +#define ICON_MD_PHONE "\xee\x83\x8d" // U+e0cd +#define ICON_MD_PHONE_ANDROID "\xee\x8c\xa4" // U+e324 +#define ICON_MD_PHONE_BLUETOOTH_SPEAKER "\xee\x98\x9b" // U+e61b +#define ICON_MD_PHONE_CALLBACK "\xee\x99\x89" // U+e649 +#define ICON_MD_PHONE_DISABLED "\xee\xa7\x8c" // U+e9cc +#define ICON_MD_PHONE_ENABLED "\xee\xa7\x8d" // U+e9cd +#define ICON_MD_PHONE_FORWARDED "\xee\x98\x9c" // U+e61c +#define ICON_MD_PHONE_IN_TALK "\xee\x98\x9d" // U+e61d +#define ICON_MD_PHONE_IPHONE "\xee\x8c\xa5" // U+e325 +#define ICON_MD_PHONE_LOCKED "\xee\x98\x9e" // U+e61e +#define ICON_MD_PHONE_MISSED "\xee\x98\x9f" // U+e61f +#define ICON_MD_PHONE_PAUSED "\xee\x98\xa0" // U+e620 +#define ICON_MD_PHONELINK "\xee\x8c\xa6" // U+e326 +#define ICON_MD_PHONELINK_ERASE "\xee\x83\x9b" // U+e0db +#define ICON_MD_PHONELINK_LOCK "\xee\x83\x9c" // U+e0dc +#define ICON_MD_PHONELINK_OFF "\xee\x8c\xa7" // U+e327 +#define ICON_MD_PHONELINK_RING "\xee\x83\x9d" // U+e0dd +#define ICON_MD_PHONELINK_SETUP "\xee\x83\x9e" // U+e0de +#define ICON_MD_PHOTO "\xee\x90\x90" // U+e410 +#define ICON_MD_PHOTO_ALBUM "\xee\x90\x91" // U+e411 +#define ICON_MD_PHOTO_CAMERA "\xee\x90\x92" // U+e412 +#define ICON_MD_PHOTO_CAMERA_BACK "\xee\xbd\xa8" // U+ef68 +#define ICON_MD_PHOTO_CAMERA_FRONT "\xee\xbd\xa9" // U+ef69 +#define ICON_MD_PHOTO_FILTER "\xee\x90\xbb" // U+e43b +#define ICON_MD_PHOTO_LIBRARY "\xee\x90\x93" // U+e413 +#define ICON_MD_PHOTO_SIZE_SELECT_ACTUAL "\xee\x90\xb2" // U+e432 +#define ICON_MD_PHOTO_SIZE_SELECT_LARGE "\xee\x90\xb3" // U+e433 +#define ICON_MD_PHOTO_SIZE_SELECT_SMALL "\xee\x90\xb4" // U+e434 +#define ICON_MD_PHP "\xee\xae\x8f" // U+eb8f +#define ICON_MD_PIANO "\xee\x94\xa1" // U+e521 +#define ICON_MD_PIANO_OFF "\xee\x94\xa0" // U+e520 +#define ICON_MD_PICTURE_AS_PDF "\xee\x90\x95" // U+e415 +#define ICON_MD_PICTURE_IN_PICTURE "\xee\xa2\xaa" // U+e8aa +#define ICON_MD_PICTURE_IN_PICTURE_ALT "\xee\xa4\x91" // U+e911 +#define ICON_MD_PIE_CHART "\xee\x9b\x84" // U+e6c4 +#define ICON_MD_PIE_CHART_OUTLINE "\xef\x81\x84" // U+f044 +#define ICON_MD_PIE_CHART_OUTLINED "\xee\x9b\x85" // U+e6c5 +#define ICON_MD_PIN "\xef\x81\x85" // U+f045 +#define ICON_MD_PIN_DROP "\xee\x95\x9e" // U+e55e +#define ICON_MD_PIN_END "\xee\x9d\xa7" // U+e767 +#define ICON_MD_PIN_INVOKE "\xee\x9d\xa3" // U+e763 +#define ICON_MD_PINCH "\xee\xac\xb8" // U+eb38 +#define ICON_MD_PIVOT_TABLE_CHART "\xee\xa7\x8e" // U+e9ce +#define ICON_MD_PIX "\xee\xaa\xa3" // U+eaa3 +#define ICON_MD_PLACE "\xee\x95\x9f" // U+e55f +#define ICON_MD_PLAGIARISM "\xee\xa9\x9a" // U+ea5a +#define ICON_MD_PLAY_ARROW "\xee\x80\xb7" // U+e037 +#define ICON_MD_PLAY_CIRCLE "\xee\x87\x84" // U+e1c4 +#define ICON_MD_PLAY_CIRCLE_FILL "\xee\x80\xb8" // U+e038 +#define ICON_MD_PLAY_CIRCLE_FILLED "\xee\x80\xb8" // U+e038 +#define ICON_MD_PLAY_CIRCLE_OUTLINE "\xee\x80\xb9" // U+e039 +#define ICON_MD_PLAY_DISABLED "\xee\xbd\xaa" // U+ef6a +#define ICON_MD_PLAY_FOR_WORK "\xee\xa4\x86" // U+e906 +#define ICON_MD_PLAY_LESSON "\xef\x81\x87" // U+f047 +#define ICON_MD_PLAYLIST_ADD "\xee\x80\xbb" // U+e03b +#define ICON_MD_PLAYLIST_ADD_CHECK "\xee\x81\xa5" // U+e065 +#define ICON_MD_PLAYLIST_ADD_CHECK_CIRCLE "\xee\x9f\xa6" // U+e7e6 +#define ICON_MD_PLAYLIST_ADD_CIRCLE "\xee\x9f\xa5" // U+e7e5 +#define ICON_MD_PLAYLIST_PLAY "\xee\x81\x9f" // U+e05f +#define ICON_MD_PLAYLIST_REMOVE "\xee\xae\x80" // U+eb80 +#define ICON_MD_PLUMBING "\xef\x84\x87" // U+f107 +#define ICON_MD_PLUS_ONE "\xee\xa0\x80" // U+e800 +#define ICON_MD_PODCASTS "\xef\x81\x88" // U+f048 +#define ICON_MD_POINT_OF_SALE "\xef\x85\xbe" // U+f17e +#define ICON_MD_POLICY "\xee\xa8\x97" // U+ea17 +#define ICON_MD_POLL "\xee\xa0\x81" // U+e801 +#define ICON_MD_POLYLINE "\xee\xae\xbb" // U+ebbb +#define ICON_MD_POLYMER "\xee\xa2\xab" // U+e8ab +#define ICON_MD_POOL "\xee\xad\x88" // U+eb48 +#define ICON_MD_PORTABLE_WIFI_OFF "\xee\x83\x8e" // U+e0ce +#define ICON_MD_PORTRAIT "\xee\x90\x96" // U+e416 +#define ICON_MD_POST_ADD "\xee\xa8\xa0" // U+ea20 +#define ICON_MD_POWER "\xee\x98\xbc" // U+e63c +#define ICON_MD_POWER_INPUT "\xee\x8c\xb6" // U+e336 +#define ICON_MD_POWER_OFF "\xee\x99\x86" // U+e646 +#define ICON_MD_POWER_SETTINGS_NEW "\xee\xa2\xac" // U+e8ac +#define ICON_MD_PRECISION_MANUFACTURING "\xef\x81\x89" // U+f049 +#define ICON_MD_PREGNANT_WOMAN "\xee\xa4\x9e" // U+e91e +#define ICON_MD_PRESENT_TO_ALL "\xee\x83\x9f" // U+e0df +#define ICON_MD_PREVIEW "\xef\x87\x85" // U+f1c5 +#define ICON_MD_PRICE_CHANGE "\xef\x81\x8a" // U+f04a +#define ICON_MD_PRICE_CHECK "\xef\x81\x8b" // U+f04b +#define ICON_MD_PRINT "\xee\xa2\xad" // U+e8ad +#define ICON_MD_PRINT_DISABLED "\xee\xa7\x8f" // U+e9cf +#define ICON_MD_PRIORITY_HIGH "\xee\x99\x85" // U+e645 +#define ICON_MD_PRIVACY_TIP "\xef\x83\x9c" // U+f0dc +#define ICON_MD_PRIVATE_CONNECTIVITY "\xee\x9d\x84" // U+e744 +#define ICON_MD_PRODUCTION_QUANTITY_LIMITS "\xee\x87\x91" // U+e1d1 +#define ICON_MD_PROPANE "\xee\xb0\x94" // U+ec14 +#define ICON_MD_PROPANE_TANK "\xee\xb0\x93" // U+ec13 +#define ICON_MD_PSYCHOLOGY "\xee\xa9\x8a" // U+ea4a +#define ICON_MD_PSYCHOLOGY_ALT "\xef\xa3\xaa" // U+f8ea +#define ICON_MD_PUBLIC "\xee\xa0\x8b" // U+e80b +#define ICON_MD_PUBLIC_OFF "\xef\x87\x8a" // U+f1ca +#define ICON_MD_PUBLISH "\xee\x89\x95" // U+e255 +#define ICON_MD_PUBLISHED_WITH_CHANGES "\xef\x88\xb2" // U+f232 +#define ICON_MD_PUNCH_CLOCK "\xee\xaa\xa8" // U+eaa8 +#define ICON_MD_PUSH_PIN "\xef\x84\x8d" // U+f10d +#define ICON_MD_QR_CODE "\xee\xbd\xab" // U+ef6b +#define ICON_MD_QR_CODE_2 "\xee\x80\x8a" // U+e00a +#define ICON_MD_QR_CODE_SCANNER "\xef\x88\x86" // U+f206 +#define ICON_MD_QUERY_BUILDER "\xee\xa2\xae" // U+e8ae +#define ICON_MD_QUERY_STATS "\xee\x93\xbc" // U+e4fc +#define ICON_MD_QUESTION_ANSWER "\xee\xa2\xaf" // U+e8af +#define ICON_MD_QUESTION_MARK "\xee\xae\x8b" // U+eb8b +#define ICON_MD_QUEUE "\xee\x80\xbc" // U+e03c +#define ICON_MD_QUEUE_MUSIC "\xee\x80\xbd" // U+e03d +#define ICON_MD_QUEUE_PLAY_NEXT "\xee\x81\xa6" // U+e066 +#define ICON_MD_QUICK_CONTACTS_DIALER "\xee\x83\x8f" // U+e0cf +#define ICON_MD_QUICK_CONTACTS_MAIL "\xee\x83\x90" // U+e0d0 +#define ICON_MD_QUICKREPLY "\xee\xbd\xac" // U+ef6c +#define ICON_MD_QUIZ "\xef\x81\x8c" // U+f04c +#define ICON_MD_QUORA "\xee\xaa\x98" // U+ea98 +#define ICON_MD_R_MOBILEDATA "\xef\x81\x8d" // U+f04d +#define ICON_MD_RADAR "\xef\x81\x8e" // U+f04e +#define ICON_MD_RADIO "\xee\x80\xbe" // U+e03e +#define ICON_MD_RADIO_BUTTON_CHECKED "\xee\xa0\xb7" // U+e837 +#define ICON_MD_RADIO_BUTTON_OFF "\xee\xa0\xb6" // U+e836 +#define ICON_MD_RADIO_BUTTON_ON "\xee\xa0\xb7" // U+e837 +#define ICON_MD_RADIO_BUTTON_UNCHECKED "\xee\xa0\xb6" // U+e836 +#define ICON_MD_RAILWAY_ALERT "\xee\xa7\x91" // U+e9d1 +#define ICON_MD_RAMEN_DINING "\xee\xa9\xa4" // U+ea64 +#define ICON_MD_RAMP_LEFT "\xee\xae\x9c" // U+eb9c +#define ICON_MD_RAMP_RIGHT "\xee\xae\x96" // U+eb96 +#define ICON_MD_RATE_REVIEW "\xee\x95\xa0" // U+e560 +#define ICON_MD_RAW_OFF "\xef\x81\x8f" // U+f04f +#define ICON_MD_RAW_ON "\xef\x81\x90" // U+f050 +#define ICON_MD_READ_MORE "\xee\xbd\xad" // U+ef6d +#define ICON_MD_REAL_ESTATE_AGENT "\xee\x9c\xba" // U+e73a +#define ICON_MD_REBASE_EDIT "\xef\xa1\x86" // U+f846 +#define ICON_MD_RECEIPT "\xee\xa2\xb0" // U+e8b0 +#define ICON_MD_RECEIPT_LONG "\xee\xbd\xae" // U+ef6e +#define ICON_MD_RECENT_ACTORS "\xee\x80\xbf" // U+e03f +#define ICON_MD_RECOMMEND "\xee\xa7\x92" // U+e9d2 +#define ICON_MD_RECORD_VOICE_OVER "\xee\xa4\x9f" // U+e91f +#define ICON_MD_RECTANGLE "\xee\xad\x94" // U+eb54 +#define ICON_MD_RECYCLING "\xee\x9d\xa0" // U+e760 +#define ICON_MD_REDDIT "\xee\xaa\xa0" // U+eaa0 +#define ICON_MD_REDEEM "\xee\xa2\xb1" // U+e8b1 +#define ICON_MD_REDO "\xee\x85\x9a" // U+e15a +#define ICON_MD_REDUCE_CAPACITY "\xef\x88\x9c" // U+f21c +#define ICON_MD_REFRESH "\xee\x97\x95" // U+e5d5 +#define ICON_MD_REMEMBER_ME "\xef\x81\x91" // U+f051 +#define ICON_MD_REMOVE "\xee\x85\x9b" // U+e15b +#define ICON_MD_REMOVE_CIRCLE "\xee\x85\x9c" // U+e15c +#define ICON_MD_REMOVE_CIRCLE_OUTLINE "\xee\x85\x9d" // U+e15d +#define ICON_MD_REMOVE_DONE "\xee\xa7\x93" // U+e9d3 +#define ICON_MD_REMOVE_FROM_QUEUE "\xee\x81\xa7" // U+e067 +#define ICON_MD_REMOVE_MODERATOR "\xee\xa7\x94" // U+e9d4 +#define ICON_MD_REMOVE_RED_EYE "\xee\x90\x97" // U+e417 +#define ICON_MD_REMOVE_ROAD "\xee\xaf\xbc" // U+ebfc +#define ICON_MD_REMOVE_SHOPPING_CART "\xee\xa4\xa8" // U+e928 +#define ICON_MD_REORDER "\xee\xa3\xbe" // U+e8fe +#define ICON_MD_REPARTITION "\xef\xa3\xa8" // U+f8e8 +#define ICON_MD_REPEAT "\xee\x81\x80" // U+e040 +#define ICON_MD_REPEAT_ON "\xee\xa7\x96" // U+e9d6 +#define ICON_MD_REPEAT_ONE "\xee\x81\x81" // U+e041 +#define ICON_MD_REPEAT_ONE_ON "\xee\xa7\x97" // U+e9d7 +#define ICON_MD_REPLAY "\xee\x81\x82" // U+e042 +#define ICON_MD_REPLAY_10 "\xee\x81\x99" // U+e059 +#define ICON_MD_REPLAY_30 "\xee\x81\x9a" // U+e05a +#define ICON_MD_REPLAY_5 "\xee\x81\x9b" // U+e05b +#define ICON_MD_REPLAY_CIRCLE_FILLED "\xee\xa7\x98" // U+e9d8 +#define ICON_MD_REPLY "\xee\x85\x9e" // U+e15e +#define ICON_MD_REPLY_ALL "\xee\x85\x9f" // U+e15f +#define ICON_MD_REPORT "\xee\x85\xa0" // U+e160 +#define ICON_MD_REPORT_GMAILERRORRED "\xef\x81\x92" // U+f052 +#define ICON_MD_REPORT_OFF "\xee\x85\xb0" // U+e170 +#define ICON_MD_REPORT_PROBLEM "\xee\xa2\xb2" // U+e8b2 +#define ICON_MD_REQUEST_PAGE "\xef\x88\xac" // U+f22c +#define ICON_MD_REQUEST_QUOTE "\xef\x86\xb6" // U+f1b6 +#define ICON_MD_RESET_TV "\xee\xa7\x99" // U+e9d9 +#define ICON_MD_RESTART_ALT "\xef\x81\x93" // U+f053 +#define ICON_MD_RESTAURANT "\xee\x95\xac" // U+e56c +#define ICON_MD_RESTAURANT_MENU "\xee\x95\xa1" // U+e561 +#define ICON_MD_RESTORE "\xee\xa2\xb3" // U+e8b3 +#define ICON_MD_RESTORE_FROM_TRASH "\xee\xa4\xb8" // U+e938 +#define ICON_MD_RESTORE_PAGE "\xee\xa4\xa9" // U+e929 +#define ICON_MD_REVIEWS "\xef\x81\x94" // U+f054 +#define ICON_MD_RICE_BOWL "\xef\x87\xb5" // U+f1f5 +#define ICON_MD_RING_VOLUME "\xee\x83\x91" // U+e0d1 +#define ICON_MD_ROCKET "\xee\xae\xa5" // U+eba5 +#define ICON_MD_ROCKET_LAUNCH "\xee\xae\x9b" // U+eb9b +#define ICON_MD_ROLLER_SHADES "\xee\xb0\x92" // U+ec12 +#define ICON_MD_ROLLER_SHADES_CLOSED "\xee\xb0\x91" // U+ec11 +#define ICON_MD_ROLLER_SKATING "\xee\xaf\x8d" // U+ebcd +#define ICON_MD_ROOFING "\xef\x88\x81" // U+f201 +#define ICON_MD_ROOM "\xee\xa2\xb4" // U+e8b4 +#define ICON_MD_ROOM_PREFERENCES "\xef\x86\xb8" // U+f1b8 +#define ICON_MD_ROOM_SERVICE "\xee\xad\x89" // U+eb49 +#define ICON_MD_ROTATE_90_DEGREES_CCW "\xee\x90\x98" // U+e418 +#define ICON_MD_ROTATE_90_DEGREES_CW "\xee\xaa\xab" // U+eaab +#define ICON_MD_ROTATE_LEFT "\xee\x90\x99" // U+e419 +#define ICON_MD_ROTATE_RIGHT "\xee\x90\x9a" // U+e41a +#define ICON_MD_ROUNDABOUT_LEFT "\xee\xae\x99" // U+eb99 +#define ICON_MD_ROUNDABOUT_RIGHT "\xee\xae\xa3" // U+eba3 +#define ICON_MD_ROUNDED_CORNER "\xee\xa4\xa0" // U+e920 +#define ICON_MD_ROUTE "\xee\xab\x8d" // U+eacd +#define ICON_MD_ROUTER "\xee\x8c\xa8" // U+e328 +#define ICON_MD_ROWING "\xee\xa4\xa1" // U+e921 +#define ICON_MD_RSS_FEED "\xee\x83\xa5" // U+e0e5 +#define ICON_MD_RSVP "\xef\x81\x95" // U+f055 +#define ICON_MD_RTT "\xee\xa6\xad" // U+e9ad +#define ICON_MD_RULE "\xef\x87\x82" // U+f1c2 +#define ICON_MD_RULE_FOLDER "\xef\x87\x89" // U+f1c9 +#define ICON_MD_RUN_CIRCLE "\xee\xbd\xaf" // U+ef6f +#define ICON_MD_RUNNING_WITH_ERRORS "\xee\x94\x9d" // U+e51d +#define ICON_MD_RV_HOOKUP "\xee\x99\x82" // U+e642 +#define ICON_MD_SAFETY_CHECK "\xee\xaf\xaf" // U+ebef +#define ICON_MD_SAFETY_DIVIDER "\xee\x87\x8c" // U+e1cc +#define ICON_MD_SAILING "\xee\x94\x82" // U+e502 +#define ICON_MD_SANITIZER "\xef\x88\x9d" // U+f21d +#define ICON_MD_SATELLITE "\xee\x95\xa2" // U+e562 +#define ICON_MD_SATELLITE_ALT "\xee\xac\xba" // U+eb3a +#define ICON_MD_SAVE "\xee\x85\xa1" // U+e161 +#define ICON_MD_SAVE_ALT "\xee\x85\xb1" // U+e171 +#define ICON_MD_SAVE_AS "\xee\xad\xa0" // U+eb60 +#define ICON_MD_SAVED_SEARCH "\xee\xa8\x91" // U+ea11 +#define ICON_MD_SAVINGS "\xee\x8b\xab" // U+e2eb +#define ICON_MD_SCALE "\xee\xad\x9f" // U+eb5f +#define ICON_MD_SCANNER "\xee\x8c\xa9" // U+e329 +#define ICON_MD_SCATTER_PLOT "\xee\x89\xa8" // U+e268 +#define ICON_MD_SCHEDULE "\xee\xa2\xb5" // U+e8b5 +#define ICON_MD_SCHEDULE_SEND "\xee\xa8\x8a" // U+ea0a +#define ICON_MD_SCHEMA "\xee\x93\xbd" // U+e4fd +#define ICON_MD_SCHOOL "\xee\xa0\x8c" // U+e80c +#define ICON_MD_SCIENCE "\xee\xa9\x8b" // U+ea4b +#define ICON_MD_SCORE "\xee\x89\xa9" // U+e269 +#define ICON_MD_SCOREBOARD "\xee\xaf\x90" // U+ebd0 +#define ICON_MD_SCREEN_LOCK_LANDSCAPE "\xee\x86\xbe" // U+e1be +#define ICON_MD_SCREEN_LOCK_PORTRAIT "\xee\x86\xbf" // U+e1bf +#define ICON_MD_SCREEN_LOCK_ROTATION "\xee\x87\x80" // U+e1c0 +#define ICON_MD_SCREEN_ROTATION "\xee\x87\x81" // U+e1c1 +#define ICON_MD_SCREEN_ROTATION_ALT "\xee\xaf\xae" // U+ebee +#define ICON_MD_SCREEN_SEARCH_DESKTOP "\xee\xbd\xb0" // U+ef70 +#define ICON_MD_SCREEN_SHARE "\xee\x83\xa2" // U+e0e2 +#define ICON_MD_SCREENSHOT "\xef\x81\x96" // U+f056 +#define ICON_MD_SCREENSHOT_MONITOR "\xee\xb0\x88" // U+ec08 +#define ICON_MD_SCUBA_DIVING "\xee\xaf\x8e" // U+ebce +#define ICON_MD_SD "\xee\xa7\x9d" // U+e9dd +#define ICON_MD_SD_CARD "\xee\x98\xa3" // U+e623 +#define ICON_MD_SD_CARD_ALERT "\xef\x81\x97" // U+f057 +#define ICON_MD_SD_STORAGE "\xee\x87\x82" // U+e1c2 +#define ICON_MD_SEARCH "\xee\xa2\xb6" // U+e8b6 +#define ICON_MD_SEARCH_OFF "\xee\xa9\xb6" // U+ea76 +#define ICON_MD_SECURITY "\xee\x8c\xaa" // U+e32a +#define ICON_MD_SECURITY_UPDATE "\xef\x81\x98" // U+f058 +#define ICON_MD_SECURITY_UPDATE_GOOD "\xef\x81\x99" // U+f059 +#define ICON_MD_SECURITY_UPDATE_WARNING "\xef\x81\x9a" // U+f05a +#define ICON_MD_SEGMENT "\xee\xa5\x8b" // U+e94b +#define ICON_MD_SELECT_ALL "\xee\x85\xa2" // U+e162 +#define ICON_MD_SELF_IMPROVEMENT "\xee\xa9\xb8" // U+ea78 +#define ICON_MD_SELL "\xef\x81\x9b" // U+f05b +#define ICON_MD_SEND "\xee\x85\xa3" // U+e163 +#define ICON_MD_SEND_AND_ARCHIVE "\xee\xa8\x8c" // U+ea0c +#define ICON_MD_SEND_TIME_EXTENSION "\xee\xab\x9b" // U+eadb +#define ICON_MD_SEND_TO_MOBILE "\xef\x81\x9c" // U+f05c +#define ICON_MD_SENSOR_DOOR "\xef\x86\xb5" // U+f1b5 +#define ICON_MD_SENSOR_OCCUPIED "\xee\xb0\x90" // U+ec10 +#define ICON_MD_SENSOR_WINDOW "\xef\x86\xb4" // U+f1b4 +#define ICON_MD_SENSORS "\xee\x94\x9e" // U+e51e +#define ICON_MD_SENSORS_OFF "\xee\x94\x9f" // U+e51f +#define ICON_MD_SENTIMENT_DISSATISFIED "\xee\xa0\x91" // U+e811 +#define ICON_MD_SENTIMENT_NEUTRAL "\xee\xa0\x92" // U+e812 +#define ICON_MD_SENTIMENT_SATISFIED "\xee\xa0\x93" // U+e813 +#define ICON_MD_SENTIMENT_SATISFIED_ALT "\xee\x83\xad" // U+e0ed +#define ICON_MD_SENTIMENT_VERY_DISSATISFIED "\xee\xa0\x94" // U+e814 +#define ICON_MD_SENTIMENT_VERY_SATISFIED "\xee\xa0\x95" // U+e815 +#define ICON_MD_SET_MEAL "\xef\x87\xaa" // U+f1ea +#define ICON_MD_SETTINGS "\xee\xa2\xb8" // U+e8b8 +#define ICON_MD_SETTINGS_ACCESSIBILITY "\xef\x81\x9d" // U+f05d +#define ICON_MD_SETTINGS_APPLICATIONS "\xee\xa2\xb9" // U+e8b9 +#define ICON_MD_SETTINGS_BACKUP_RESTORE "\xee\xa2\xba" // U+e8ba +#define ICON_MD_SETTINGS_BLUETOOTH "\xee\xa2\xbb" // U+e8bb +#define ICON_MD_SETTINGS_BRIGHTNESS "\xee\xa2\xbd" // U+e8bd +#define ICON_MD_SETTINGS_CELL "\xee\xa2\xbc" // U+e8bc +#define ICON_MD_SETTINGS_DISPLAY "\xee\xa2\xbd" // U+e8bd +#define ICON_MD_SETTINGS_ETHERNET "\xee\xa2\xbe" // U+e8be +#define ICON_MD_SETTINGS_INPUT_ANTENNA "\xee\xa2\xbf" // U+e8bf +#define ICON_MD_SETTINGS_INPUT_COMPONENT "\xee\xa3\x80" // U+e8c0 +#define ICON_MD_SETTINGS_INPUT_COMPOSITE "\xee\xa3\x81" // U+e8c1 +#define ICON_MD_SETTINGS_INPUT_HDMI "\xee\xa3\x82" // U+e8c2 +#define ICON_MD_SETTINGS_INPUT_SVIDEO "\xee\xa3\x83" // U+e8c3 +#define ICON_MD_SETTINGS_OVERSCAN "\xee\xa3\x84" // U+e8c4 +#define ICON_MD_SETTINGS_PHONE "\xee\xa3\x85" // U+e8c5 +#define ICON_MD_SETTINGS_POWER "\xee\xa3\x86" // U+e8c6 +#define ICON_MD_SETTINGS_REMOTE "\xee\xa3\x87" // U+e8c7 +#define ICON_MD_SETTINGS_SUGGEST "\xef\x81\x9e" // U+f05e +#define ICON_MD_SETTINGS_SYSTEM_DAYDREAM "\xee\x87\x83" // U+e1c3 +#define ICON_MD_SETTINGS_VOICE "\xee\xa3\x88" // U+e8c8 +#define ICON_MD_SEVERE_COLD "\xee\xaf\x93" // U+ebd3 +#define ICON_MD_SHAPE_LINE "\xef\xa3\x93" // U+f8d3 +#define ICON_MD_SHARE "\xee\xa0\x8d" // U+e80d +#define ICON_MD_SHARE_ARRIVAL_TIME "\xee\x94\xa4" // U+e524 +#define ICON_MD_SHARE_LOCATION "\xef\x81\x9f" // U+f05f +#define ICON_MD_SHELVES "\xef\xa1\xae" // U+f86e +#define ICON_MD_SHIELD "\xee\xa7\xa0" // U+e9e0 +#define ICON_MD_SHIELD_MOON "\xee\xaa\xa9" // U+eaa9 +#define ICON_MD_SHOP "\xee\xa3\x89" // U+e8c9 +#define ICON_MD_SHOP_2 "\xee\x86\x9e" // U+e19e +#define ICON_MD_SHOP_TWO "\xee\xa3\x8a" // U+e8ca +#define ICON_MD_SHOPIFY "\xee\xaa\x9d" // U+ea9d +#define ICON_MD_SHOPPING_BAG "\xef\x87\x8c" // U+f1cc +#define ICON_MD_SHOPPING_BASKET "\xee\xa3\x8b" // U+e8cb +#define ICON_MD_SHOPPING_CART "\xee\xa3\x8c" // U+e8cc +#define ICON_MD_SHOPPING_CART_CHECKOUT "\xee\xae\x88" // U+eb88 +#define ICON_MD_SHORT_TEXT "\xee\x89\xa1" // U+e261 +#define ICON_MD_SHORTCUT "\xef\x81\xa0" // U+f060 +#define ICON_MD_SHOW_CHART "\xee\x9b\xa1" // U+e6e1 +#define ICON_MD_SHOWER "\xef\x81\xa1" // U+f061 +#define ICON_MD_SHUFFLE "\xee\x81\x83" // U+e043 +#define ICON_MD_SHUFFLE_ON "\xee\xa7\xa1" // U+e9e1 +#define ICON_MD_SHUTTER_SPEED "\xee\x90\xbd" // U+e43d +#define ICON_MD_SICK "\xef\x88\xa0" // U+f220 +#define ICON_MD_SIGN_LANGUAGE "\xee\xaf\xa5" // U+ebe5 +#define ICON_MD_SIGNAL_CELLULAR_0_BAR "\xef\x82\xa8" // U+f0a8 +#define ICON_MD_SIGNAL_CELLULAR_4_BAR "\xee\x87\x88" // U+e1c8 +#define ICON_MD_SIGNAL_CELLULAR_ALT "\xee\x88\x82" // U+e202 +#define ICON_MD_SIGNAL_CELLULAR_ALT_1_BAR "\xee\xaf\x9f" // U+ebdf +#define ICON_MD_SIGNAL_CELLULAR_ALT_2_BAR "\xee\xaf\xa3" // U+ebe3 +#define ICON_MD_SIGNAL_CELLULAR_CONNECTED_NO_INTERNET_0_BAR "\xef\x82\xac" // U+f0ac +#define ICON_MD_SIGNAL_CELLULAR_CONNECTED_NO_INTERNET_4_BAR "\xee\x87\x8d" // U+e1cd +#define ICON_MD_SIGNAL_CELLULAR_NO_SIM "\xee\x87\x8e" // U+e1ce +#define ICON_MD_SIGNAL_CELLULAR_NODATA "\xef\x81\xa2" // U+f062 +#define ICON_MD_SIGNAL_CELLULAR_NULL "\xee\x87\x8f" // U+e1cf +#define ICON_MD_SIGNAL_CELLULAR_OFF "\xee\x87\x90" // U+e1d0 +#define ICON_MD_SIGNAL_WIFI_0_BAR "\xef\x82\xb0" // U+f0b0 +#define ICON_MD_SIGNAL_WIFI_4_BAR "\xee\x87\x98" // U+e1d8 +#define ICON_MD_SIGNAL_WIFI_4_BAR_LOCK "\xee\x87\x99" // U+e1d9 +#define ICON_MD_SIGNAL_WIFI_BAD "\xef\x81\xa3" // U+f063 +#define ICON_MD_SIGNAL_WIFI_CONNECTED_NO_INTERNET_4 "\xef\x81\xa4" // U+f064 +#define ICON_MD_SIGNAL_WIFI_OFF "\xee\x87\x9a" // U+e1da +#define ICON_MD_SIGNAL_WIFI_STATUSBAR_4_BAR "\xef\x81\xa5" // U+f065 +#define ICON_MD_SIGNAL_WIFI_STATUSBAR_CONNECTED_NO_INTERNET_4 "\xef\x81\xa6" // U+f066 +#define ICON_MD_SIGNAL_WIFI_STATUSBAR_NULL "\xef\x81\xa7" // U+f067 +#define ICON_MD_SIGNPOST "\xee\xae\x91" // U+eb91 +#define ICON_MD_SIM_CARD "\xee\x8c\xab" // U+e32b +#define ICON_MD_SIM_CARD_ALERT "\xee\x98\xa4" // U+e624 +#define ICON_MD_SIM_CARD_DOWNLOAD "\xef\x81\xa8" // U+f068 +#define ICON_MD_SINGLE_BED "\xee\xa9\x88" // U+ea48 +#define ICON_MD_SIP "\xef\x81\xa9" // U+f069 +#define ICON_MD_SKATEBOARDING "\xee\x94\x91" // U+e511 +#define ICON_MD_SKIP_NEXT "\xee\x81\x84" // U+e044 +#define ICON_MD_SKIP_PREVIOUS "\xee\x81\x85" // U+e045 +#define ICON_MD_SLEDDING "\xee\x94\x92" // U+e512 +#define ICON_MD_SLIDESHOW "\xee\x90\x9b" // U+e41b +#define ICON_MD_SLOW_MOTION_VIDEO "\xee\x81\xa8" // U+e068 +#define ICON_MD_SMART_BUTTON "\xef\x87\x81" // U+f1c1 +#define ICON_MD_SMART_DISPLAY "\xef\x81\xaa" // U+f06a +#define ICON_MD_SMART_SCREEN "\xef\x81\xab" // U+f06b +#define ICON_MD_SMART_TOY "\xef\x81\xac" // U+f06c +#define ICON_MD_SMARTPHONE "\xee\x8c\xac" // U+e32c +#define ICON_MD_SMOKE_FREE "\xee\xad\x8a" // U+eb4a +#define ICON_MD_SMOKING_ROOMS "\xee\xad\x8b" // U+eb4b +#define ICON_MD_SMS "\xee\x98\xa5" // U+e625 +#define ICON_MD_SMS_FAILED "\xee\x98\xa6" // U+e626 +#define ICON_MD_SNAPCHAT "\xee\xa9\xae" // U+ea6e +#define ICON_MD_SNIPPET_FOLDER "\xef\x87\x87" // U+f1c7 +#define ICON_MD_SNOOZE "\xee\x81\x86" // U+e046 +#define ICON_MD_SNOWBOARDING "\xee\x94\x93" // U+e513 +#define ICON_MD_SNOWING "\xee\xa0\x8f" // U+e80f +#define ICON_MD_SNOWMOBILE "\xee\x94\x83" // U+e503 +#define ICON_MD_SNOWSHOEING "\xee\x94\x94" // U+e514 +#define ICON_MD_SOAP "\xef\x86\xb2" // U+f1b2 +#define ICON_MD_SOCIAL_DISTANCE "\xee\x87\x8b" // U+e1cb +#define ICON_MD_SOLAR_POWER "\xee\xb0\x8f" // U+ec0f +#define ICON_MD_SORT "\xee\x85\xa4" // U+e164 +#define ICON_MD_SORT_BY_ALPHA "\xee\x81\x93" // U+e053 +#define ICON_MD_SOS "\xee\xaf\xb7" // U+ebf7 +#define ICON_MD_SOUP_KITCHEN "\xee\x9f\x93" // U+e7d3 +#define ICON_MD_SOURCE "\xef\x87\x84" // U+f1c4 +#define ICON_MD_SOUTH "\xef\x87\xa3" // U+f1e3 +#define ICON_MD_SOUTH_AMERICA "\xee\x9f\xa4" // U+e7e4 +#define ICON_MD_SOUTH_EAST "\xef\x87\xa4" // U+f1e4 +#define ICON_MD_SOUTH_WEST "\xef\x87\xa5" // U+f1e5 +#define ICON_MD_SPA "\xee\xad\x8c" // U+eb4c +#define ICON_MD_SPACE_BAR "\xee\x89\x96" // U+e256 +#define ICON_MD_SPACE_DASHBOARD "\xee\x99\xab" // U+e66b +#define ICON_MD_SPATIAL_AUDIO "\xee\xaf\xab" // U+ebeb +#define ICON_MD_SPATIAL_AUDIO_OFF "\xee\xaf\xa8" // U+ebe8 +#define ICON_MD_SPATIAL_TRACKING "\xee\xaf\xaa" // U+ebea +#define ICON_MD_SPEAKER "\xee\x8c\xad" // U+e32d +#define ICON_MD_SPEAKER_GROUP "\xee\x8c\xae" // U+e32e +#define ICON_MD_SPEAKER_NOTES "\xee\xa3\x8d" // U+e8cd +#define ICON_MD_SPEAKER_NOTES_OFF "\xee\xa4\xaa" // U+e92a +#define ICON_MD_SPEAKER_PHONE "\xee\x83\x92" // U+e0d2 +#define ICON_MD_SPEED "\xee\xa7\xa4" // U+e9e4 +#define ICON_MD_SPELLCHECK "\xee\xa3\x8e" // U+e8ce +#define ICON_MD_SPLITSCREEN "\xef\x81\xad" // U+f06d +#define ICON_MD_SPOKE "\xee\xa6\xa7" // U+e9a7 +#define ICON_MD_SPORTS "\xee\xa8\xb0" // U+ea30 +#define ICON_MD_SPORTS_BAR "\xef\x87\xb3" // U+f1f3 +#define ICON_MD_SPORTS_BASEBALL "\xee\xa9\x91" // U+ea51 +#define ICON_MD_SPORTS_BASKETBALL "\xee\xa8\xa6" // U+ea26 +#define ICON_MD_SPORTS_CRICKET "\xee\xa8\xa7" // U+ea27 +#define ICON_MD_SPORTS_ESPORTS "\xee\xa8\xa8" // U+ea28 +#define ICON_MD_SPORTS_FOOTBALL "\xee\xa8\xa9" // U+ea29 +#define ICON_MD_SPORTS_GOLF "\xee\xa8\xaa" // U+ea2a +#define ICON_MD_SPORTS_GYMNASTICS "\xee\xaf\x84" // U+ebc4 +#define ICON_MD_SPORTS_HANDBALL "\xee\xa8\xb3" // U+ea33 +#define ICON_MD_SPORTS_HOCKEY "\xee\xa8\xab" // U+ea2b +#define ICON_MD_SPORTS_KABADDI "\xee\xa8\xb4" // U+ea34 +#define ICON_MD_SPORTS_MARTIAL_ARTS "\xee\xab\xa9" // U+eae9 +#define ICON_MD_SPORTS_MMA "\xee\xa8\xac" // U+ea2c +#define ICON_MD_SPORTS_MOTORSPORTS "\xee\xa8\xad" // U+ea2d +#define ICON_MD_SPORTS_RUGBY "\xee\xa8\xae" // U+ea2e +#define ICON_MD_SPORTS_SCORE "\xef\x81\xae" // U+f06e +#define ICON_MD_SPORTS_SOCCER "\xee\xa8\xaf" // U+ea2f +#define ICON_MD_SPORTS_TENNIS "\xee\xa8\xb2" // U+ea32 +#define ICON_MD_SPORTS_VOLLEYBALL "\xee\xa8\xb1" // U+ea31 +#define ICON_MD_SQUARE "\xee\xac\xb6" // U+eb36 +#define ICON_MD_SQUARE_FOOT "\xee\xa9\x89" // U+ea49 +#define ICON_MD_SSID_CHART "\xee\xad\xa6" // U+eb66 +#define ICON_MD_STACKED_BAR_CHART "\xee\xa7\xa6" // U+e9e6 +#define ICON_MD_STACKED_LINE_CHART "\xef\x88\xab" // U+f22b +#define ICON_MD_STADIUM "\xee\xae\x90" // U+eb90 +#define ICON_MD_STAIRS "\xef\x86\xa9" // U+f1a9 +#define ICON_MD_STAR "\xee\xa0\xb8" // U+e838 +#define ICON_MD_STAR_BORDER "\xee\xa0\xba" // U+e83a +#define ICON_MD_STAR_BORDER_PURPLE500 "\xef\x82\x99" // U+f099 +#define ICON_MD_STAR_HALF "\xee\xa0\xb9" // U+e839 +#define ICON_MD_STAR_OUTLINE "\xef\x81\xaf" // U+f06f +#define ICON_MD_STAR_PURPLE500 "\xef\x82\x9a" // U+f09a +#define ICON_MD_STAR_RATE "\xef\x83\xac" // U+f0ec +#define ICON_MD_STARS "\xee\xa3\x90" // U+e8d0 +#define ICON_MD_START "\xee\x82\x89" // U+e089 +#define ICON_MD_STAY_CURRENT_LANDSCAPE "\xee\x83\x93" // U+e0d3 +#define ICON_MD_STAY_CURRENT_PORTRAIT "\xee\x83\x94" // U+e0d4 +#define ICON_MD_STAY_PRIMARY_LANDSCAPE "\xee\x83\x95" // U+e0d5 +#define ICON_MD_STAY_PRIMARY_PORTRAIT "\xee\x83\x96" // U+e0d6 +#define ICON_MD_STICKY_NOTE_2 "\xef\x87\xbc" // U+f1fc +#define ICON_MD_STOP "\xee\x81\x87" // U+e047 +#define ICON_MD_STOP_CIRCLE "\xee\xbd\xb1" // U+ef71 +#define ICON_MD_STOP_SCREEN_SHARE "\xee\x83\xa3" // U+e0e3 +#define ICON_MD_STORAGE "\xee\x87\x9b" // U+e1db +#define ICON_MD_STORE "\xee\xa3\x91" // U+e8d1 +#define ICON_MD_STORE_MALL_DIRECTORY "\xee\x95\xa3" // U+e563 +#define ICON_MD_STOREFRONT "\xee\xa8\x92" // U+ea12 +#define ICON_MD_STORM "\xef\x81\xb0" // U+f070 +#define ICON_MD_STRAIGHT "\xee\xae\x95" // U+eb95 +#define ICON_MD_STRAIGHTEN "\xee\x90\x9c" // U+e41c +#define ICON_MD_STREAM "\xee\xa7\xa9" // U+e9e9 +#define ICON_MD_STREETVIEW "\xee\x95\xae" // U+e56e +#define ICON_MD_STRIKETHROUGH_S "\xee\x89\x97" // U+e257 +#define ICON_MD_STROLLER "\xef\x86\xae" // U+f1ae +#define ICON_MD_STYLE "\xee\x90\x9d" // U+e41d +#define ICON_MD_SUBDIRECTORY_ARROW_LEFT "\xee\x97\x99" // U+e5d9 +#define ICON_MD_SUBDIRECTORY_ARROW_RIGHT "\xee\x97\x9a" // U+e5da +#define ICON_MD_SUBJECT "\xee\xa3\x92" // U+e8d2 +#define ICON_MD_SUBSCRIPT "\xef\x84\x91" // U+f111 +#define ICON_MD_SUBSCRIPTIONS "\xee\x81\xa4" // U+e064 +#define ICON_MD_SUBTITLES "\xee\x81\x88" // U+e048 +#define ICON_MD_SUBTITLES_OFF "\xee\xbd\xb2" // U+ef72 +#define ICON_MD_SUBWAY "\xee\x95\xaf" // U+e56f +#define ICON_MD_SUMMARIZE "\xef\x81\xb1" // U+f071 +#define ICON_MD_SUNNY "\xee\xa0\x9a" // U+e81a +#define ICON_MD_SUNNY_SNOWING "\xee\xa0\x99" // U+e819 +#define ICON_MD_SUPERSCRIPT "\xef\x84\x92" // U+f112 +#define ICON_MD_SUPERVISED_USER_CIRCLE "\xee\xa4\xb9" // U+e939 +#define ICON_MD_SUPERVISOR_ACCOUNT "\xee\xa3\x93" // U+e8d3 +#define ICON_MD_SUPPORT "\xee\xbd\xb3" // U+ef73 +#define ICON_MD_SUPPORT_AGENT "\xef\x83\xa2" // U+f0e2 +#define ICON_MD_SURFING "\xee\x94\x95" // U+e515 +#define ICON_MD_SURROUND_SOUND "\xee\x81\x89" // U+e049 +#define ICON_MD_SWAP_CALLS "\xee\x83\x97" // U+e0d7 +#define ICON_MD_SWAP_HORIZ "\xee\xa3\x94" // U+e8d4 +#define ICON_MD_SWAP_HORIZONTAL_CIRCLE "\xee\xa4\xb3" // U+e933 +#define ICON_MD_SWAP_VERT "\xee\xa3\x95" // U+e8d5 +#define ICON_MD_SWAP_VERT_CIRCLE "\xee\xa3\x96" // U+e8d6 +#define ICON_MD_SWAP_VERTICAL_CIRCLE "\xee\xa3\x96" // U+e8d6 +#define ICON_MD_SWIPE "\xee\xa7\xac" // U+e9ec +#define ICON_MD_SWIPE_DOWN "\xee\xad\x93" // U+eb53 +#define ICON_MD_SWIPE_DOWN_ALT "\xee\xac\xb0" // U+eb30 +#define ICON_MD_SWIPE_LEFT "\xee\xad\x99" // U+eb59 +#define ICON_MD_SWIPE_LEFT_ALT "\xee\xac\xb3" // U+eb33 +#define ICON_MD_SWIPE_RIGHT "\xee\xad\x92" // U+eb52 +#define ICON_MD_SWIPE_RIGHT_ALT "\xee\xad\x96" // U+eb56 +#define ICON_MD_SWIPE_UP "\xee\xac\xae" // U+eb2e +#define ICON_MD_SWIPE_UP_ALT "\xee\xac\xb5" // U+eb35 +#define ICON_MD_SWIPE_VERTICAL "\xee\xad\x91" // U+eb51 +#define ICON_MD_SWITCH_ACCESS_SHORTCUT "\xee\x9f\xa1" // U+e7e1 +#define ICON_MD_SWITCH_ACCESS_SHORTCUT_ADD "\xee\x9f\xa2" // U+e7e2 +#define ICON_MD_SWITCH_ACCOUNT "\xee\xa7\xad" // U+e9ed +#define ICON_MD_SWITCH_CAMERA "\xee\x90\x9e" // U+e41e +#define ICON_MD_SWITCH_LEFT "\xef\x87\x91" // U+f1d1 +#define ICON_MD_SWITCH_RIGHT "\xef\x87\x92" // U+f1d2 +#define ICON_MD_SWITCH_VIDEO "\xee\x90\x9f" // U+e41f +#define ICON_MD_SYNAGOGUE "\xee\xaa\xb0" // U+eab0 +#define ICON_MD_SYNC "\xee\x98\xa7" // U+e627 +#define ICON_MD_SYNC_ALT "\xee\xa8\x98" // U+ea18 +#define ICON_MD_SYNC_DISABLED "\xee\x98\xa8" // U+e628 +#define ICON_MD_SYNC_LOCK "\xee\xab\xae" // U+eaee +#define ICON_MD_SYNC_PROBLEM "\xee\x98\xa9" // U+e629 +#define ICON_MD_SYSTEM_SECURITY_UPDATE "\xef\x81\xb2" // U+f072 +#define ICON_MD_SYSTEM_SECURITY_UPDATE_GOOD "\xef\x81\xb3" // U+f073 +#define ICON_MD_SYSTEM_SECURITY_UPDATE_WARNING "\xef\x81\xb4" // U+f074 +#define ICON_MD_SYSTEM_UPDATE "\xee\x98\xaa" // U+e62a +#define ICON_MD_SYSTEM_UPDATE_ALT "\xee\xa3\x97" // U+e8d7 +#define ICON_MD_SYSTEM_UPDATE_TV "\xee\xa3\x97" // U+e8d7 +#define ICON_MD_TAB "\xee\xa3\x98" // U+e8d8 +#define ICON_MD_TAB_UNSELECTED "\xee\xa3\x99" // U+e8d9 +#define ICON_MD_TABLE_BAR "\xee\xab\x92" // U+ead2 +#define ICON_MD_TABLE_CHART "\xee\x89\xa5" // U+e265 +#define ICON_MD_TABLE_RESTAURANT "\xee\xab\x86" // U+eac6 +#define ICON_MD_TABLE_ROWS "\xef\x84\x81" // U+f101 +#define ICON_MD_TABLE_VIEW "\xef\x86\xbe" // U+f1be +#define ICON_MD_TABLET "\xee\x8c\xaf" // U+e32f +#define ICON_MD_TABLET_ANDROID "\xee\x8c\xb0" // U+e330 +#define ICON_MD_TABLET_MAC "\xee\x8c\xb1" // U+e331 +#define ICON_MD_TAG "\xee\xa7\xaf" // U+e9ef +#define ICON_MD_TAG_FACES "\xee\x90\xa0" // U+e420 +#define ICON_MD_TAKEOUT_DINING "\xee\xa9\xb4" // U+ea74 +#define ICON_MD_TAP_AND_PLAY "\xee\x98\xab" // U+e62b +#define ICON_MD_TAPAS "\xef\x87\xa9" // U+f1e9 +#define ICON_MD_TASK "\xef\x81\xb5" // U+f075 +#define ICON_MD_TASK_ALT "\xee\x8b\xa6" // U+e2e6 +#define ICON_MD_TAXI_ALERT "\xee\xbd\xb4" // U+ef74 +#define ICON_MD_TELEGRAM "\xee\xa9\xab" // U+ea6b +#define ICON_MD_TEMPLE_BUDDHIST "\xee\xaa\xb3" // U+eab3 +#define ICON_MD_TEMPLE_HINDU "\xee\xaa\xaf" // U+eaaf +#define ICON_MD_TERMINAL "\xee\xae\x8e" // U+eb8e +#define ICON_MD_TERRAIN "\xee\x95\xa4" // U+e564 +#define ICON_MD_TEXT_DECREASE "\xee\xab\x9d" // U+eadd +#define ICON_MD_TEXT_FIELDS "\xee\x89\xa2" // U+e262 +#define ICON_MD_TEXT_FORMAT "\xee\x85\xa5" // U+e165 +#define ICON_MD_TEXT_INCREASE "\xee\xab\xa2" // U+eae2 +#define ICON_MD_TEXT_ROTATE_UP "\xee\xa4\xba" // U+e93a +#define ICON_MD_TEXT_ROTATE_VERTICAL "\xee\xa4\xbb" // U+e93b +#define ICON_MD_TEXT_ROTATION_ANGLEDOWN "\xee\xa4\xbc" // U+e93c +#define ICON_MD_TEXT_ROTATION_ANGLEUP "\xee\xa4\xbd" // U+e93d +#define ICON_MD_TEXT_ROTATION_DOWN "\xee\xa4\xbe" // U+e93e +#define ICON_MD_TEXT_ROTATION_NONE "\xee\xa4\xbf" // U+e93f +#define ICON_MD_TEXT_SNIPPET "\xef\x87\x86" // U+f1c6 +#define ICON_MD_TEXTSMS "\xee\x83\x98" // U+e0d8 +#define ICON_MD_TEXTURE "\xee\x90\xa1" // U+e421 +#define ICON_MD_THEATER_COMEDY "\xee\xa9\xa6" // U+ea66 +#define ICON_MD_THEATERS "\xee\xa3\x9a" // U+e8da +#define ICON_MD_THERMOSTAT "\xef\x81\xb6" // U+f076 +#define ICON_MD_THERMOSTAT_AUTO "\xef\x81\xb7" // U+f077 +#define ICON_MD_THUMB_DOWN "\xee\xa3\x9b" // U+e8db +#define ICON_MD_THUMB_DOWN_ALT "\xee\xa0\x96" // U+e816 +#define ICON_MD_THUMB_DOWN_OFF_ALT "\xee\xa7\xb2" // U+e9f2 +#define ICON_MD_THUMB_UP "\xee\xa3\x9c" // U+e8dc +#define ICON_MD_THUMB_UP_ALT "\xee\xa0\x97" // U+e817 +#define ICON_MD_THUMB_UP_OFF_ALT "\xee\xa7\xb3" // U+e9f3 +#define ICON_MD_THUMBS_UP_DOWN "\xee\xa3\x9d" // U+e8dd +#define ICON_MD_THUNDERSTORM "\xee\xaf\x9b" // U+ebdb +#define ICON_MD_TIKTOK "\xee\xa9\xbe" // U+ea7e +#define ICON_MD_TIME_TO_LEAVE "\xee\x98\xac" // U+e62c +#define ICON_MD_TIMELAPSE "\xee\x90\xa2" // U+e422 +#define ICON_MD_TIMELINE "\xee\xa4\xa2" // U+e922 +#define ICON_MD_TIMER "\xee\x90\xa5" // U+e425 +#define ICON_MD_TIMER_10 "\xee\x90\xa3" // U+e423 +#define ICON_MD_TIMER_10_SELECT "\xef\x81\xba" // U+f07a +#define ICON_MD_TIMER_3 "\xee\x90\xa4" // U+e424 +#define ICON_MD_TIMER_3_SELECT "\xef\x81\xbb" // U+f07b +#define ICON_MD_TIMER_OFF "\xee\x90\xa6" // U+e426 +#define ICON_MD_TIPS_AND_UPDATES "\xee\x9e\x9a" // U+e79a +#define ICON_MD_TIRE_REPAIR "\xee\xaf\x88" // U+ebc8 +#define ICON_MD_TITLE "\xee\x89\xa4" // U+e264 +#define ICON_MD_TOC "\xee\xa3\x9e" // U+e8de +#define ICON_MD_TODAY "\xee\xa3\x9f" // U+e8df +#define ICON_MD_TOGGLE_OFF "\xee\xa7\xb5" // U+e9f5 +#define ICON_MD_TOGGLE_ON "\xee\xa7\xb6" // U+e9f6 +#define ICON_MD_TOKEN "\xee\xa8\xa5" // U+ea25 +#define ICON_MD_TOLL "\xee\xa3\xa0" // U+e8e0 +#define ICON_MD_TONALITY "\xee\x90\xa7" // U+e427 +#define ICON_MD_TOPIC "\xef\x87\x88" // U+f1c8 +#define ICON_MD_TORNADO "\xee\x86\x99" // U+e199 +#define ICON_MD_TOUCH_APP "\xee\xa4\x93" // U+e913 +#define ICON_MD_TOUR "\xee\xbd\xb5" // U+ef75 +#define ICON_MD_TOYS "\xee\x8c\xb2" // U+e332 +#define ICON_MD_TRACK_CHANGES "\xee\xa3\xa1" // U+e8e1 +#define ICON_MD_TRAFFIC "\xee\x95\xa5" // U+e565 +#define ICON_MD_TRAIN "\xee\x95\xb0" // U+e570 +#define ICON_MD_TRAM "\xee\x95\xb1" // U+e571 +#define ICON_MD_TRANSCRIBE "\xef\xa3\xac" // U+f8ec +#define ICON_MD_TRANSFER_WITHIN_A_STATION "\xee\x95\xb2" // U+e572 +#define ICON_MD_TRANSFORM "\xee\x90\xa8" // U+e428 +#define ICON_MD_TRANSGENDER "\xee\x96\x8d" // U+e58d +#define ICON_MD_TRANSIT_ENTEREXIT "\xee\x95\xb9" // U+e579 +#define ICON_MD_TRANSLATE "\xee\xa3\xa2" // U+e8e2 +#define ICON_MD_TRAVEL_EXPLORE "\xee\x8b\x9b" // U+e2db +#define ICON_MD_TRENDING_DOWN "\xee\xa3\xa3" // U+e8e3 +#define ICON_MD_TRENDING_FLAT "\xee\xa3\xa4" // U+e8e4 +#define ICON_MD_TRENDING_NEUTRAL "\xee\xa3\xa4" // U+e8e4 +#define ICON_MD_TRENDING_UP "\xee\xa3\xa5" // U+e8e5 +#define ICON_MD_TRIP_ORIGIN "\xee\x95\xbb" // U+e57b +#define ICON_MD_TROLLEY "\xef\xa1\xab" // U+f86b +#define ICON_MD_TROUBLESHOOT "\xee\x87\x92" // U+e1d2 +#define ICON_MD_TRY "\xef\x81\xbc" // U+f07c +#define ICON_MD_TSUNAMI "\xee\xaf\x98" // U+ebd8 +#define ICON_MD_TTY "\xef\x86\xaa" // U+f1aa +#define ICON_MD_TUNE "\xee\x90\xa9" // U+e429 +#define ICON_MD_TUNGSTEN "\xef\x81\xbd" // U+f07d +#define ICON_MD_TURN_LEFT "\xee\xae\xa6" // U+eba6 +#define ICON_MD_TURN_RIGHT "\xee\xae\xab" // U+ebab +#define ICON_MD_TURN_SHARP_LEFT "\xee\xae\xa7" // U+eba7 +#define ICON_MD_TURN_SHARP_RIGHT "\xee\xae\xaa" // U+ebaa +#define ICON_MD_TURN_SLIGHT_LEFT "\xee\xae\xa4" // U+eba4 +#define ICON_MD_TURN_SLIGHT_RIGHT "\xee\xae\x9a" // U+eb9a +#define ICON_MD_TURNED_IN "\xee\xa3\xa6" // U+e8e6 +#define ICON_MD_TURNED_IN_NOT "\xee\xa3\xa7" // U+e8e7 +#define ICON_MD_TV "\xee\x8c\xb3" // U+e333 +#define ICON_MD_TV_OFF "\xee\x99\x87" // U+e647 +#define ICON_MD_TWO_WHEELER "\xee\xa7\xb9" // U+e9f9 +#define ICON_MD_TYPE_SPECIMEN "\xef\xa3\xb0" // U+f8f0 +#define ICON_MD_U_TURN_LEFT "\xee\xae\xa1" // U+eba1 +#define ICON_MD_U_TURN_RIGHT "\xee\xae\xa2" // U+eba2 +#define ICON_MD_UMBRELLA "\xef\x86\xad" // U+f1ad +#define ICON_MD_UNARCHIVE "\xee\x85\xa9" // U+e169 +#define ICON_MD_UNDO "\xee\x85\xa6" // U+e166 +#define ICON_MD_UNFOLD_LESS "\xee\x97\x96" // U+e5d6 +#define ICON_MD_UNFOLD_LESS_DOUBLE "\xef\xa3\x8f" // U+f8cf +#define ICON_MD_UNFOLD_MORE "\xee\x97\x97" // U+e5d7 +#define ICON_MD_UNFOLD_MORE_DOUBLE "\xef\xa3\x90" // U+f8d0 +#define ICON_MD_UNPUBLISHED "\xef\x88\xb6" // U+f236 +#define ICON_MD_UNSUBSCRIBE "\xee\x83\xab" // U+e0eb +#define ICON_MD_UPCOMING "\xef\x81\xbe" // U+f07e +#define ICON_MD_UPDATE "\xee\xa4\xa3" // U+e923 +#define ICON_MD_UPDATE_DISABLED "\xee\x81\xb5" // U+e075 +#define ICON_MD_UPGRADE "\xef\x83\xbb" // U+f0fb +#define ICON_MD_UPLOAD "\xef\x82\x9b" // U+f09b +#define ICON_MD_UPLOAD_FILE "\xee\xa7\xbc" // U+e9fc +#define ICON_MD_USB "\xee\x87\xa0" // U+e1e0 +#define ICON_MD_USB_OFF "\xee\x93\xba" // U+e4fa +#define ICON_MD_VACCINES "\xee\x84\xb8" // U+e138 +#define ICON_MD_VAPE_FREE "\xee\xaf\x86" // U+ebc6 +#define ICON_MD_VAPING_ROOMS "\xee\xaf\x8f" // U+ebcf +#define ICON_MD_VERIFIED "\xee\xbd\xb6" // U+ef76 +#define ICON_MD_VERIFIED_USER "\xee\xa3\xa8" // U+e8e8 +#define ICON_MD_VERTICAL_ALIGN_BOTTOM "\xee\x89\x98" // U+e258 +#define ICON_MD_VERTICAL_ALIGN_CENTER "\xee\x89\x99" // U+e259 +#define ICON_MD_VERTICAL_ALIGN_TOP "\xee\x89\x9a" // U+e25a +#define ICON_MD_VERTICAL_DISTRIBUTE "\xee\x81\xb6" // U+e076 +#define ICON_MD_VERTICAL_SHADES "\xee\xb0\x8e" // U+ec0e +#define ICON_MD_VERTICAL_SHADES_CLOSED "\xee\xb0\x8d" // U+ec0d +#define ICON_MD_VERTICAL_SPLIT "\xee\xa5\x89" // U+e949 +#define ICON_MD_VIBRATION "\xee\x98\xad" // U+e62d +#define ICON_MD_VIDEO_CALL "\xee\x81\xb0" // U+e070 +#define ICON_MD_VIDEO_CAMERA_BACK "\xef\x81\xbf" // U+f07f +#define ICON_MD_VIDEO_CAMERA_FRONT "\xef\x82\x80" // U+f080 +#define ICON_MD_VIDEO_CHAT "\xef\xa2\xa0" // U+f8a0 +#define ICON_MD_VIDEO_COLLECTION "\xee\x81\x8a" // U+e04a +#define ICON_MD_VIDEO_FILE "\xee\xae\x87" // U+eb87 +#define ICON_MD_VIDEO_LABEL "\xee\x81\xb1" // U+e071 +#define ICON_MD_VIDEO_LIBRARY "\xee\x81\x8a" // U+e04a +#define ICON_MD_VIDEO_SETTINGS "\xee\xa9\xb5" // U+ea75 +#define ICON_MD_VIDEO_STABLE "\xef\x82\x81" // U+f081 +#define ICON_MD_VIDEOCAM "\xee\x81\x8b" // U+e04b +#define ICON_MD_VIDEOCAM_OFF "\xee\x81\x8c" // U+e04c +#define ICON_MD_VIDEOGAME_ASSET "\xee\x8c\xb8" // U+e338 +#define ICON_MD_VIDEOGAME_ASSET_OFF "\xee\x94\x80" // U+e500 +#define ICON_MD_VIEW_AGENDA "\xee\xa3\xa9" // U+e8e9 +#define ICON_MD_VIEW_ARRAY "\xee\xa3\xaa" // U+e8ea +#define ICON_MD_VIEW_CAROUSEL "\xee\xa3\xab" // U+e8eb +#define ICON_MD_VIEW_COLUMN "\xee\xa3\xac" // U+e8ec +#define ICON_MD_VIEW_COMFORTABLE "\xee\x90\xaa" // U+e42a +#define ICON_MD_VIEW_COMFY "\xee\x90\xaa" // U+e42a +#define ICON_MD_VIEW_COMFY_ALT "\xee\xad\xb3" // U+eb73 +#define ICON_MD_VIEW_COMPACT "\xee\x90\xab" // U+e42b +#define ICON_MD_VIEW_COMPACT_ALT "\xee\xad\xb4" // U+eb74 +#define ICON_MD_VIEW_COZY "\xee\xad\xb5" // U+eb75 +#define ICON_MD_VIEW_DAY "\xee\xa3\xad" // U+e8ed +#define ICON_MD_VIEW_HEADLINE "\xee\xa3\xae" // U+e8ee +#define ICON_MD_VIEW_IN_AR "\xee\xa7\xbe" // U+e9fe +#define ICON_MD_VIEW_KANBAN "\xee\xad\xbf" // U+eb7f +#define ICON_MD_VIEW_LIST "\xee\xa3\xaf" // U+e8ef +#define ICON_MD_VIEW_MODULE "\xee\xa3\xb0" // U+e8f0 +#define ICON_MD_VIEW_QUILT "\xee\xa3\xb1" // U+e8f1 +#define ICON_MD_VIEW_SIDEBAR "\xef\x84\x94" // U+f114 +#define ICON_MD_VIEW_STREAM "\xee\xa3\xb2" // U+e8f2 +#define ICON_MD_VIEW_TIMELINE "\xee\xae\x85" // U+eb85 +#define ICON_MD_VIEW_WEEK "\xee\xa3\xb3" // U+e8f3 +#define ICON_MD_VIGNETTE "\xee\x90\xb5" // U+e435 +#define ICON_MD_VILLA "\xee\x96\x86" // U+e586 +#define ICON_MD_VISIBILITY "\xee\xa3\xb4" // U+e8f4 +#define ICON_MD_VISIBILITY_OFF "\xee\xa3\xb5" // U+e8f5 +#define ICON_MD_VOICE_CHAT "\xee\x98\xae" // U+e62e +#define ICON_MD_VOICE_OVER_OFF "\xee\xa5\x8a" // U+e94a +#define ICON_MD_VOICEMAIL "\xee\x83\x99" // U+e0d9 +#define ICON_MD_VOLCANO "\xee\xaf\x9a" // U+ebda +#define ICON_MD_VOLUME_DOWN "\xee\x81\x8d" // U+e04d +#define ICON_MD_VOLUME_DOWN_ALT "\xee\x9e\x9c" // U+e79c +#define ICON_MD_VOLUME_MUTE "\xee\x81\x8e" // U+e04e +#define ICON_MD_VOLUME_OFF "\xee\x81\x8f" // U+e04f +#define ICON_MD_VOLUME_UP "\xee\x81\x90" // U+e050 +#define ICON_MD_VOLUNTEER_ACTIVISM "\xee\xa9\xb0" // U+ea70 +#define ICON_MD_VPN_KEY "\xee\x83\x9a" // U+e0da +#define ICON_MD_VPN_KEY_OFF "\xee\xad\xba" // U+eb7a +#define ICON_MD_VPN_LOCK "\xee\x98\xaf" // U+e62f +#define ICON_MD_VRPANO "\xef\x82\x82" // U+f082 +#define ICON_MD_WALLET "\xef\xa3\xbf" // U+f8ff +#define ICON_MD_WALLET_GIFTCARD "\xee\xa3\xb6" // U+e8f6 +#define ICON_MD_WALLET_MEMBERSHIP "\xee\xa3\xb7" // U+e8f7 +#define ICON_MD_WALLET_TRAVEL "\xee\xa3\xb8" // U+e8f8 +#define ICON_MD_WALLPAPER "\xee\x86\xbc" // U+e1bc +#define ICON_MD_WAREHOUSE "\xee\xae\xb8" // U+ebb8 +#define ICON_MD_WARNING "\xee\x80\x82" // U+e002 +#define ICON_MD_WARNING_AMBER "\xef\x82\x83" // U+f083 +#define ICON_MD_WASH "\xef\x86\xb1" // U+f1b1 +#define ICON_MD_WATCH "\xee\x8c\xb4" // U+e334 +#define ICON_MD_WATCH_LATER "\xee\xa4\xa4" // U+e924 +#define ICON_MD_WATCH_OFF "\xee\xab\xa3" // U+eae3 +#define ICON_MD_WATER "\xef\x82\x84" // U+f084 +#define ICON_MD_WATER_DAMAGE "\xef\x88\x83" // U+f203 +#define ICON_MD_WATER_DROP "\xee\x9e\x98" // U+e798 +#define ICON_MD_WATERFALL_CHART "\xee\xa8\x80" // U+ea00 +#define ICON_MD_WAVES "\xee\x85\xb6" // U+e176 +#define ICON_MD_WAVING_HAND "\xee\x9d\xa6" // U+e766 +#define ICON_MD_WB_AUTO "\xee\x90\xac" // U+e42c +#define ICON_MD_WB_CLOUDY "\xee\x90\xad" // U+e42d +#define ICON_MD_WB_INCANDESCENT "\xee\x90\xae" // U+e42e +#define ICON_MD_WB_IRIDESCENT "\xee\x90\xb6" // U+e436 +#define ICON_MD_WB_SHADE "\xee\xa8\x81" // U+ea01 +#define ICON_MD_WB_SUNNY "\xee\x90\xb0" // U+e430 +#define ICON_MD_WB_TWIGHLIGHT "\xee\xa8\x82" // U+ea02 +#define ICON_MD_WB_TWILIGHT "\xee\x87\x86" // U+e1c6 +#define ICON_MD_WC "\xee\x98\xbd" // U+e63d +#define ICON_MD_WEB "\xee\x81\x91" // U+e051 +#define ICON_MD_WEB_ASSET "\xee\x81\xa9" // U+e069 +#define ICON_MD_WEB_ASSET_OFF "\xee\x93\xb7" // U+e4f7 +#define ICON_MD_WEB_STORIES "\xee\x96\x95" // U+e595 +#define ICON_MD_WEBHOOK "\xee\xae\x92" // U+eb92 +#define ICON_MD_WECHAT "\xee\xaa\x81" // U+ea81 +#define ICON_MD_WEEKEND "\xee\x85\xab" // U+e16b +#define ICON_MD_WEST "\xef\x87\xa6" // U+f1e6 +#define ICON_MD_WHATSHOT "\xee\xa0\x8e" // U+e80e +#define ICON_MD_WHEELCHAIR_PICKUP "\xef\x86\xab" // U+f1ab +#define ICON_MD_WHERE_TO_VOTE "\xee\x85\xb7" // U+e177 +#define ICON_MD_WIDGETS "\xee\x86\xbd" // U+e1bd +#define ICON_MD_WIDTH_FULL "\xef\xa3\xb5" // U+f8f5 +#define ICON_MD_WIDTH_NORMAL "\xef\xa3\xb6" // U+f8f6 +#define ICON_MD_WIDTH_WIDE "\xef\xa3\xb7" // U+f8f7 +#define ICON_MD_WIFI "\xee\x98\xbe" // U+e63e +#define ICON_MD_WIFI_1_BAR "\xee\x93\x8a" // U+e4ca +#define ICON_MD_WIFI_2_BAR "\xee\x93\x99" // U+e4d9 +#define ICON_MD_WIFI_CALLING "\xee\xbd\xb7" // U+ef77 +#define ICON_MD_WIFI_CALLING_3 "\xef\x82\x85" // U+f085 +#define ICON_MD_WIFI_CHANNEL "\xee\xad\xaa" // U+eb6a +#define ICON_MD_WIFI_FIND "\xee\xac\xb1" // U+eb31 +#define ICON_MD_WIFI_LOCK "\xee\x87\xa1" // U+e1e1 +#define ICON_MD_WIFI_OFF "\xee\x99\x88" // U+e648 +#define ICON_MD_WIFI_PASSWORD "\xee\xad\xab" // U+eb6b +#define ICON_MD_WIFI_PROTECTED_SETUP "\xef\x83\xbc" // U+f0fc +#define ICON_MD_WIFI_TETHERING "\xee\x87\xa2" // U+e1e2 +#define ICON_MD_WIFI_TETHERING_ERROR "\xee\xab\x99" // U+ead9 +#define ICON_MD_WIFI_TETHERING_ERROR_ROUNDED "\xef\x82\x86" // U+f086 +#define ICON_MD_WIFI_TETHERING_OFF "\xef\x82\x87" // U+f087 +#define ICON_MD_WIND_POWER "\xee\xb0\x8c" // U+ec0c +#define ICON_MD_WINDOW "\xef\x82\x88" // U+f088 +#define ICON_MD_WINE_BAR "\xef\x87\xa8" // U+f1e8 +#define ICON_MD_WOMAN "\xee\x84\xbe" // U+e13e +#define ICON_MD_WOMAN_2 "\xef\xa3\xa7" // U+f8e7 +#define ICON_MD_WOO_COMMERCE "\xee\xa9\xad" // U+ea6d +#define ICON_MD_WORDPRESS "\xee\xaa\x9f" // U+ea9f +#define ICON_MD_WORK "\xee\xa3\xb9" // U+e8f9 +#define ICON_MD_WORK_HISTORY "\xee\xb0\x89" // U+ec09 +#define ICON_MD_WORK_OFF "\xee\xa5\x82" // U+e942 +#define ICON_MD_WORK_OUTLINE "\xee\xa5\x83" // U+e943 +#define ICON_MD_WORKSPACE_PREMIUM "\xee\x9e\xaf" // U+e7af +#define ICON_MD_WORKSPACES "\xee\x86\xa0" // U+e1a0 +#define ICON_MD_WORKSPACES_FILLED "\xee\xa8\x8d" // U+ea0d +#define ICON_MD_WORKSPACES_OUTLINE "\xee\xa8\x8f" // U+ea0f +#define ICON_MD_WRAP_TEXT "\xee\x89\x9b" // U+e25b +#define ICON_MD_WRONG_LOCATION "\xee\xbd\xb8" // U+ef78 +#define ICON_MD_WYSIWYG "\xef\x87\x83" // U+f1c3 +#define ICON_MD_YARD "\xef\x82\x89" // U+f089 +#define ICON_MD_YOUTUBE_SEARCHED_FOR "\xee\xa3\xba" // U+e8fa +#define ICON_MD_ZOOM_IN "\xee\xa3\xbf" // U+e8ff +#define ICON_MD_ZOOM_IN_MAP "\xee\xac\xad" // U+eb2d +#define ICON_MD_ZOOM_OUT "\xee\xa4\x80" // U+e900 +#define ICON_MD_ZOOM_OUT_MAP "\xee\x95\xab" // U+e56b diff --git a/src/embedded/embedded_fonts.cpp.in b/src/embedded/embedded_fonts.cpp.in new file mode 100644 index 0000000..0313928 --- /dev/null +++ b/src/embedded/embedded_fonts.cpp.in @@ -0,0 +1,14 @@ +// DragonX Wallet - INCBIN font embedding (CMake-generated) +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// This file is generated by CMake's configure_file() from +// src/embedded/embedded_fonts.cpp.in — do NOT edit the generated copy. +// The absolute paths below are resolved at CMake configure time. + +#include "incbin.h" + +INCBIN(ubuntu_regular, "@CMAKE_SOURCE_DIR@/res/fonts/Ubuntu-R.ttf"); +INCBIN(ubuntu_light, "@CMAKE_SOURCE_DIR@/res/fonts/Ubuntu-Light.ttf"); +INCBIN(ubuntu_medium, "@CMAKE_SOURCE_DIR@/res/fonts/Ubuntu-Medium.ttf"); +INCBIN(material_icons, "@CMAKE_SOURCE_DIR@/res/fonts/MaterialIcons-Regular.ttf"); diff --git a/src/embedded/embedded_fonts.h b/src/embedded/embedded_fonts.h new file mode 100644 index 0000000..f7fe12d --- /dev/null +++ b/src/embedded/embedded_fonts.h @@ -0,0 +1,29 @@ +// DragonX Wallet - Embedded font data declarations (INCBIN) +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// The actual data is emitted in generated/embedded_fonts.cpp via the +// assembler .incbin directive, so the compiler never parses 122K lines +// of hex literals. + +#pragma once +#include + +// These symbols are defined in generated/embedded_fonts.cpp (via INCBIN). +// INCBIN creates: g__data[] (const unsigned char) +// g__size (const unsigned int) +// g__end (const unsigned char*) + +extern "C" { + extern const unsigned char g_ubuntu_regular_data[]; + extern const unsigned int g_ubuntu_regular_size; + + extern const unsigned char g_ubuntu_light_data[]; + extern const unsigned int g_ubuntu_light_size; + + extern const unsigned char g_ubuntu_medium_data[]; + extern const unsigned int g_ubuntu_medium_size; + + extern const unsigned char g_material_icons_data[]; + extern const unsigned int g_material_icons_size; +} diff --git a/src/embedded/lang_de.h b/src/embedded/lang_de.h new file mode 100644 index 0000000..c1d4b8f --- /dev/null +++ b/src/embedded/lang_de.h @@ -0,0 +1,382 @@ +unsigned char res_lang_de_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4b, 0x6f, 0x6e, 0x74, 0x6f, 0x73, + 0x74, 0x61, 0x6e, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x65, 0x6e, 0x64, + 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, + 0x63, 0x65, 0x69, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6d, 0x70, + 0x66, 0x61, 0x6e, 0x67, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, + 0x6b, 0x74, 0x69, 0x6f, 0x6e, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0x4d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x4b, 0x6e, 0x6f, 0x74, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x4d, 0x61, 0x72, 0x6b, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x69, 0x6e, 0x73, 0x74, 0x65, 0x6c, 0x6c, 0x75, 0x6e, 0x67, + 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xc3, 0x9c, + 0x62, 0x65, 0x72, 0x73, 0x69, 0x63, 0x68, 0x74, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x74, + 0x7a, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, + 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x73, 0x61, 0x6d, 0x74, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x55, 0x6e, + 0x62, 0x65, 0x73, 0x74, 0xc3, 0xa4, 0x74, 0x69, 0x67, 0x74, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, 0x72, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x68, 0x72, 0x65, 0x20, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x5a, 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x2d, 0x41, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4b, 0x65, 0x69, 0x6e, 0x65, + 0x20, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x6e, 0x20, 0x67, 0x65, + 0x66, 0x75, 0x6e, 0x64, 0x65, 0x6e, 0x2e, 0x20, 0x45, 0x72, 0x73, 0x74, + 0x65, 0x6c, 0x6c, 0x65, 0x6e, 0x20, 0x53, 0x69, 0x65, 0x20, 0x65, 0x69, + 0x6e, 0x65, 0x20, 0x6d, 0x69, 0x74, 0x20, 0x64, 0x65, 0x6e, 0x20, 0x53, + 0x63, 0x68, 0x61, 0x6c, 0x74, 0x66, 0x6c, 0xc3, 0xa4, 0x63, 0x68, 0x65, + 0x6e, 0x20, 0x6f, 0x62, 0x65, 0x6e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x65, 0x75, 0x65, + 0x20, 0x5a, 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x65, 0x75, 0x65, 0x20, 0x54, 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x79, 0x70, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x79, 0x70, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x6f, + 0x6c, 0x6c, 0x73, 0x74, 0xc3, 0xa4, 0x6e, 0x64, 0x69, 0x67, 0x65, 0x20, + 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, 0x6b, 0x6f, 0x70, 0x69, + 0x65, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x74, 0x68, + 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x56, 0x6f, 0x6e, 0x20, 0x64, 0x69, 0x65, 0x73, 0x65, 0x72, + 0x20, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, 0x73, 0x65, 0x6e, + 0x64, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, + 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x72, 0x69, + 0x76, 0x61, 0x74, 0x65, 0x6e, 0x20, 0x53, 0x63, 0x68, 0x6c, 0xc3, 0xbc, + 0x73, 0x73, 0x65, 0x6c, 0x20, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x69, + 0x65, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x69, + 0x6e, 0x67, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6e, + 0x73, 0x69, 0x63, 0x68, 0x74, 0x73, 0x73, 0x63, 0x68, 0x6c, 0xc3, 0xbc, + 0x73, 0x73, 0x65, 0x6c, 0x20, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x69, + 0x65, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x68, 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x51, 0x52, 0x2d, 0x43, 0x6f, 0x64, 0x65, 0x20, + 0x61, 0x6e, 0x7a, 0x65, 0x69, 0x67, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x69, 0x63, + 0x68, 0x74, 0x20, 0x6d, 0x69, 0x74, 0x20, 0x44, 0x61, 0x65, 0x6d, 0x6f, + 0x6e, 0x20, 0x76, 0x65, 0x72, 0x62, 0x75, 0x6e, 0x64, 0x65, 0x6e, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x61, 0x79, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x5a, + 0x61, 0x68, 0x6c, 0x65, 0x6e, 0x20, 0x76, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x6f, + 0x22, 0x3a, 0x20, 0x22, 0x53, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x20, 0x61, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, + 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, 0x74, 0x72, 0x61, + 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, + 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x65, 0x6d, 0x6f, 0x20, 0x28, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x2c, 0x20, 0x76, 0x65, 0x72, + 0x73, 0x63, 0x68, 0x6c, 0xc3, 0xbc, 0x73, 0x73, 0x65, 0x6c, 0x74, 0x29, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, + 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, + 0x65, 0x72, 0x2d, 0x47, 0x65, 0x62, 0xc3, 0xbc, 0x68, 0x72, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x47, 0x65, 0x62, 0xc3, 0xbc, 0x68, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x6b, 0x74, 0x69, 0x6f, 0x6e, 0x20, + 0x73, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x4c, + 0xc3, 0xb6, 0x73, 0x63, 0x68, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x20, 0x61, 0x75, 0x73, 0x77, 0xc3, 0xa4, 0x68, + 0x6c, 0x65, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x70, 0x61, 0x73, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x69, 0x6e, 0x66, 0xc3, 0xbc, 0x67, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, 0x3a, 0x20, 0x22, 0x4d, + 0x61, 0x78, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, + 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x56, + 0x65, 0x72, 0x66, 0xc3, 0xbc, 0x67, 0x62, 0x61, 0x72, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x55, 0x6e, 0x67, 0xc3, 0xbc, 0x6c, 0x74, 0x69, 0x67, 0x65, 0x73, 0x20, + 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, + 0x5f, 0x7a, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x48, + 0x69, 0x6e, 0x77, 0x65, 0x69, 0x73, 0x3a, 0x20, 0x4d, 0x65, 0x6d, 0x6f, + 0x73, 0x20, 0x73, 0x69, 0x6e, 0x64, 0x20, 0x6e, 0x75, 0x72, 0x20, 0x62, + 0x65, 0x69, 0x6d, 0x20, 0x53, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x20, 0x61, + 0x6e, 0x20, 0x67, 0x65, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x74, 0x7a, 0x74, + 0x65, 0x20, 0x28, 0x7a, 0x29, 0x20, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x6e, 0x20, 0x76, 0x65, 0x72, 0x66, 0xc3, 0xbc, 0x67, 0x62, 0x61, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x68, 0x61, + 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x5a, + 0x65, 0x69, 0x63, 0x68, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x6f, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x22, + 0x3a, 0x20, 0x22, 0x41, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x6b, 0x74, 0x69, 0x6f, 0x6e, 0x20, + 0x77, 0x69, 0x72, 0x64, 0x20, 0x67, 0x65, 0x73, 0x65, 0x6e, 0x64, 0x65, + 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x53, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x20, 0x62, 0x65, 0x73, 0x74, + 0xc3, 0xa4, 0x74, 0x69, 0x67, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, + 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x6b, 0x74, 0x69, 0x6f, + 0x6e, 0x20, 0x62, 0x65, 0x73, 0x74, 0xc3, 0xa4, 0x74, 0x69, 0x67, 0x65, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x6e, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, 0x73, 0x74, 0xc3, 0xa4, 0x74, + 0x69, 0x67, 0x65, 0x6e, 0x20, 0x26, 0x20, 0x53, 0x65, 0x6e, 0x64, 0x65, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, + 0x63, 0x65, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x62, 0x62, 0x72, 0x65, + 0x63, 0x68, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x69, 0x6e, 0x67, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x68, 0x72, 0x65, 0x20, 0x45, 0x6d, 0x70, 0x66, 0x61, 0x6e, 0x67, + 0x73, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x6e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, 0x73, + 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x65, 0x75, 0x65, 0x20, 0x7a, 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x20, 0x28, 0x67, 0x65, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x74, 0x7a, + 0x74, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x65, 0x75, 0x65, 0x20, + 0x74, 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, 0x28, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x29, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x64, 0x65, 0x74, 0x61, + 0x69, 0x6c, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, + 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, 0x65, 0x78, 0x70, 0x6c, 0x6f, + 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, 0x20, 0x45, 0x78, + 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x20, 0x61, 0x6e, 0x73, 0x65, 0x68, + 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x71, 0x72, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x51, 0x52, 0x2d, + 0x43, 0x6f, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x5a, 0x61, 0x68, 0x6c, 0x75, + 0x6e, 0x67, 0x20, 0x61, 0x6e, 0x66, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x6e, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x61, 0x74, 0x75, 0x6d, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x42, + 0x65, 0x73, 0x74, 0xc3, 0xa4, 0x74, 0x69, 0x67, 0x75, 0x6e, 0x67, 0x65, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, + 0x73, 0x74, 0xc3, 0xa4, 0x74, 0x69, 0x67, 0x74, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0x41, 0x75, 0x73, 0x73, 0x74, 0x65, 0x68, 0x65, 0x6e, + 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x67, 0x65, 0x73, 0x65, 0x6e, 0x64, 0x65, + 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, + 0x65, 0x69, 0x76, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x65, 0x6d, 0x70, + 0x66, 0x61, 0x6e, 0x67, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x67, + 0x65, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x72, 0x66, 0x74, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, + 0x4d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x2d, 0x53, 0x74, 0x65, 0x75, 0x65, + 0x72, 0x75, 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x20, + 0x73, 0x74, 0x6f, 0x70, 0x70, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x68, + 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x2d, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x2d, 0x53, + 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x6b, 0x65, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, + 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x4c, 0x6f, 0x6b, 0x61, 0x6c, 0x65, 0x20, 0x48, 0x61, 0x73, 0x68, 0x72, + 0x61, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, + 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x65, 0x74, 0x7a, 0x77, + 0x65, 0x72, 0x6b, 0x2d, 0x48, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x66, 0x66, + 0x69, 0x63, 0x75, 0x6c, 0x74, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x63, + 0x68, 0x77, 0x69, 0x65, 0x72, 0x69, 0x67, 0x6b, 0x65, 0x69, 0x74, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x73, 0x74, 0x5f, 0x74, + 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x73, 0x63, 0x68, 0x2e, 0x20, 0x5a, + 0x65, 0x69, 0x74, 0x20, 0x62, 0x69, 0x73, 0x20, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, 0x66, 0x22, 0x3a, 0x20, 0x22, 0x4d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x69, 0x73, 0x74, 0x20, 0x41, 0x55, + 0x53, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, + 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x69, 0x73, 0x74, 0x20, 0x41, 0x4e, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x56, 0x65, 0x72, 0x62, 0x75, 0x6e, 0x64, 0x65, 0x6e, + 0x65, 0x20, 0x4b, 0x6e, 0x6f, 0x74, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x73, 0x70, + 0x65, 0x72, 0x72, 0x74, 0x65, 0x20, 0x4b, 0x6e, 0x6f, 0x74, 0x65, 0x6e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x70, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x50, + 0x2d, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, + 0x3a, 0x20, 0x22, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0x48, 0xc3, 0xb6, 0x68, 0x65, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0x50, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x70, 0x65, 0x72, + 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, + 0x6e, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x74, 0x73, + 0x70, 0x65, 0x72, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, 0x5f, + 0x62, 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6c, 0x6c, 0x65, + 0x20, 0x53, 0x70, 0x65, 0x72, 0x72, 0x65, 0x6e, 0x20, 0x61, 0x75, 0x66, + 0x68, 0x65, 0x62, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x72, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x72, 0x65, 0x69, 0x73, 0x64, 0x69, + 0x61, 0x67, 0x72, 0x61, 0x6d, 0x6d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, + 0x69, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6b, 0x74, 0x75, 0x65, + 0x6c, 0x6c, 0x65, 0x72, 0x20, 0x50, 0x72, 0x65, 0x69, 0x73, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, + 0x61, 0x6e, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0x68, 0x2d, + 0xc3, 0x84, 0x6e, 0x64, 0x65, 0x72, 0x75, 0x6e, 0x67, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x76, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0x68, 0x2d, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x61, 0x70, + 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x61, 0x72, 0x6b, 0x74, 0x6b, 0x61, 0x70, + 0x69, 0x74, 0x61, 0x6c, 0x69, 0x73, 0x69, 0x65, 0x72, 0x75, 0x6e, 0x67, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, 0x6e, + 0x65, 0x72, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6c, 0x6c, 0x67, + 0x65, 0x6d, 0x65, 0x69, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, + 0x41, 0x6e, 0x7a, 0x65, 0x69, 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, + 0x20, 0x22, 0x4e, 0x65, 0x74, 0x7a, 0x77, 0x65, 0x72, 0x6b, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x44, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x70, 0x72, 0x61, 0x63, 0x68, 0x65, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, + 0x6f, 0x6e, 0x78, 0x5f, 0x67, 0x72, 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, + 0x22, 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x58, 0x20, 0x28, 0x47, 0x72, + 0xc3, 0xbc, 0x6e, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x64, 0x61, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x75, 0x6e, 0x6b, + 0x65, 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, + 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x48, 0x65, 0x6c, 0x6c, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, + 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, 0x6e, 0x75, 0x74, 0x7a, 0x65, 0x72, + 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x65, 0x72, 0x74, 0x65, 0x20, 0x47, + 0x65, 0x62, 0xc3, 0xbc, 0x68, 0x72, 0x65, 0x6e, 0x20, 0x65, 0x72, 0x6c, + 0x61, 0x75, 0x62, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, + 0x64, 0x5f, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x6e, 0x74, 0x65, 0x67, 0x72, 0x69, 0x65, 0x72, 0x74, 0x65, 0x6e, + 0x20, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x20, 0x76, 0x65, + 0x72, 0x77, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x53, + 0x70, 0x65, 0x69, 0x63, 0x68, 0x65, 0x72, 0x6e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x53, 0x63, 0x68, 0x6c, 0x69, 0x65, 0xc3, 0x9f, 0x65, 0x6e, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x44, 0x61, 0x74, 0x65, 0x69, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0x42, 0x65, 0x61, 0x72, 0x62, 0x65, 0x69, 0x74, 0x65, 0x6e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x22, + 0x3a, 0x20, 0x22, 0x41, 0x6e, 0x73, 0x69, 0x63, 0x68, 0x74, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x70, 0x22, 0x3a, + 0x20, 0x22, 0x48, 0x69, 0x6c, 0x66, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, + 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x6e, 0x20, 0x53, 0x63, + 0x68, 0x6c, 0xc3, 0xbc, 0x73, 0x73, 0x65, 0x6c, 0x20, 0x69, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x69, 0x65, 0x72, 0x65, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, 0x6b, 0x75, + 0x70, 0x5f, 0x77, 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x57, 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x20, 0x73, 0x69, 0x63, 0x68, 0x65, + 0x72, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x65, 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, 0x65, + 0x6e, 0x64, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x61, 0x62, 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x78, 0x22, 0x3a, 0x20, 0x22, 0xc3, 0x9c, 0x62, 0x65, 0x72, 0x20, 0x4f, + 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, 0x6e, 0x44, 0x72, 0x61, 0x67, 0x6f, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x66, + 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, 0x77, 0x22, 0x3a, 0x20, 0x22, + 0x4a, 0x65, 0x74, 0x7a, 0x74, 0x20, 0x61, 0x6b, 0x74, 0x75, 0x61, 0x6c, + 0x69, 0x73, 0x69, 0x65, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xc3, 0x9c, 0x62, 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x69, 0x65, 0x72, 0x65, 0x6e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x69, + 0x65, 0x72, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, 0x63, 0x6c, 0x69, 0x70, + 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6e, 0x20, + 0x5a, 0x77, 0x69, 0x73, 0x63, 0x68, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x61, + 0x67, 0x65, 0x20, 0x6b, 0x6f, 0x70, 0x69, 0x65, 0x72, 0x65, 0x6e, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x65, 0x72, + 0x62, 0x75, 0x6e, 0x64, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x74, 0x72, 0x65, 0x6e, + 0x6e, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x56, 0x65, 0x72, 0x62, 0x69, 0x6e, 0x64, 0x65, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, + 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x79, 0x6e, 0x63, 0x68, 0x72, + 0x6f, 0x6e, 0x69, 0x73, 0x69, 0x65, 0x72, 0x65, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x22, 0x3a, 0x20, 0x22, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4b, 0x65, 0x69, 0x6e, 0x65, + 0x20, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x6e, 0x20, 0x76, 0x65, + 0x72, 0x66, 0xc3, 0xbc, 0x67, 0x62, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, + 0x20, 0x22, 0x46, 0x65, 0x68, 0x6c, 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x72, 0x66, 0x6f, 0x6c, 0x67, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0x57, 0x61, 0x72, 0x6e, 0x75, 0x6e, 0x67, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, + 0x74, 0x5f, 0x65, 0x78, 0x63, 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, + 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x65, 0x74, + 0x72, 0x61, 0x67, 0x20, 0xc3, 0xbc, 0x62, 0x65, 0x72, 0x73, 0x74, 0x65, + 0x69, 0x67, 0x74, 0x20, 0x4b, 0x6f, 0x6e, 0x74, 0x6f, 0x73, 0x74, 0x61, + 0x6e, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, + 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, + 0x6b, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x65, 0x72, 0x66, 0x6f, 0x6c, 0x67, + 0x72, 0x65, 0x69, 0x63, 0x68, 0x20, 0x67, 0x65, 0x73, 0x65, 0x6e, 0x64, + 0x65, 0x74, 0x22, 0x0a, 0x7d, 0x0a +}; +unsigned int res_lang_de_json_len = 4542; diff --git a/src/embedded/lang_es.h b/src/embedded/lang_es.h new file mode 100644 index 0000000..06835e6 --- /dev/null +++ b/src/embedded/lang_es.h @@ -0,0 +1,386 @@ +unsigned char res_lang_es_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x61, 0x6c, 0x64, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x63, 0x69, 0x62, 0x69, 0x72, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, + 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, + 0xad, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, + 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x64, 0x6f, 0x73, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, + 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x65, 0x72, 0x63, 0x61, 0x64, + 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x52, + 0x65, 0x73, 0x75, 0x6d, 0x65, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0x50, 0x72, 0x6f, 0x74, 0x65, 0x67, 0x69, 0x64, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x72, + 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x65, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, + 0x3a, 0x20, 0x22, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x69, 0x6e, 0x20, 0x43, + 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, 0x72, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x75, + 0x73, 0x20, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, + 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x2d, + 0x5a, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x2d, + 0x54, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x4e, 0x6f, 0x20, 0x73, 0x65, 0x20, 0x65, 0x6e, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x61, 0x72, 0x6f, 0x6e, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, + 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x2e, 0x20, 0x43, 0x72, 0x65, 0x61, + 0x20, 0x75, 0x6e, 0x61, 0x20, 0x75, 0x73, 0x61, 0x6e, 0x64, 0x6f, 0x20, + 0x6c, 0x6f, 0x73, 0x20, 0x62, 0x6f, 0x74, 0x6f, 0x6e, 0x65, 0x73, 0x20, + 0x64, 0x65, 0x20, 0x61, 0x72, 0x72, 0x69, 0x62, 0x61, 0x2e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x75, 0x65, 0x76, 0x61, 0x20, 0x44, 0x69, 0x72, 0x2d, 0x5a, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x75, 0x65, 0x76, 0x61, 0x20, 0x44, 0x69, 0x72, 0x2d, 0x54, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x54, 0x69, 0x70, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, + 0x6f, 0x70, 0x69, 0x61, 0x72, 0x20, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, + 0x69, 0xc3, 0xb3, 0x6e, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x74, + 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x74, 0x68, 0x69, 0x73, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x6e, 0x76, 0x69, 0x61, 0x72, 0x20, 0x44, 0x65, 0x73, 0x64, 0x65, 0x20, + 0x45, 0x73, 0x74, 0x61, 0x20, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, + 0xc3, 0xb3, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, + 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x70, + 0x6f, 0x72, 0x74, 0x61, 0x72, 0x20, 0x43, 0x6c, 0x61, 0x76, 0x65, 0x20, + 0x50, 0x72, 0x69, 0x76, 0x61, 0x64, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x69, + 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, 0x20, 0x43, 0x6c, + 0x61, 0x76, 0x65, 0x20, 0x64, 0x65, 0x20, 0x56, 0x69, 0x73, 0x74, 0x61, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x6f, 0x77, + 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x4d, 0x6f, 0x73, 0x74, 0x72, 0x61, 0x72, 0x20, 0x43, 0xc3, 0xb3, 0x64, + 0x69, 0x67, 0x6f, 0x20, 0x51, 0x52, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x20, 0x63, 0x6f, + 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x20, 0x61, 0x6c, 0x20, 0x64, + 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x79, + 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x61, 0x67, + 0x61, 0x72, 0x20, 0x44, 0x65, 0x73, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x20, 0x41, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x61, 0x6e, 0x74, 0x69, 0x64, 0x61, + 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, + 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x65, 0x6d, 0x6f, 0x20, 0x28, 0x6f, + 0x70, 0x63, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x2c, 0x20, 0x65, 0x6e, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x61, 0x64, 0x6f, 0x29, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x66, 0x65, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6d, 0x69, 0x73, 0x69, 0xc3, + 0xb3, 0x6e, 0x20, 0x64, 0x65, 0x20, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0x6f, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6d, 0x69, 0x73, 0x69, 0xc3, 0xb3, 0x6e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, + 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x20, 0x54, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, + 0x22, 0x3a, 0x20, 0x22, 0x4c, 0x69, 0x6d, 0x70, 0x69, 0x61, 0x72, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6c, 0x65, 0x63, + 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x61, 0x72, + 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, + 0x73, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x65, 0x67, 0x61, 0x72, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, + 0x3a, 0x20, 0x22, 0x4d, 0xc3, 0xa1, 0x78, 0x69, 0x6d, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x69, 0x73, 0x70, 0x6f, + 0x6e, 0x69, 0x62, 0x6c, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x6f, 0x72, 0x6d, + 0x61, 0x74, 0x6f, 0x20, 0x64, 0x65, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, + 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x20, 0x69, 0x6e, 0x76, 0xc3, 0xa1, 0x6c, + 0x69, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x65, 0x6d, 0x6f, 0x5f, 0x7a, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x22, 0x3a, + 0x20, 0x22, 0x4e, 0x6f, 0x74, 0x61, 0x3a, 0x20, 0x4c, 0x6f, 0x73, 0x20, + 0x6d, 0x65, 0x6d, 0x6f, 0x73, 0x20, 0x73, 0x6f, 0x6c, 0x6f, 0x20, 0x65, + 0x73, 0x74, 0xc3, 0xa1, 0x6e, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6f, 0x6e, + 0x69, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x76, + 0x69, 0x61, 0x72, 0x20, 0x61, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x63, + 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x65, 0x67, + 0x69, 0x64, 0x61, 0x73, 0x20, 0x28, 0x7a, 0x29, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, + 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x63, 0x61, 0x72, 0x61, 0x63, 0x74, + 0x65, 0x72, 0x65, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, 0x73, 0x64, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x22, + 0x3a, 0x20, 0x22, 0x41, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x6e, 0x76, 0x69, 0x61, 0x6e, 0x64, 0x6f, 0x20, 0x74, 0x72, 0x61, 0x6e, + 0x73, 0x61, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, + 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x72, 0x6d, 0x61, 0x72, 0x20, 0x45, 0x6e, 0x76, 0xc3, 0xad, 0x6f, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x72, 0x6d, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x72, 0x6d, 0x61, 0x72, 0x20, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, + 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, + 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0x20, 0x79, 0x20, 0x45, 0x6e, 0x76, + 0x69, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x61, 0x6e, + 0x63, 0x65, 0x6c, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, + 0x69, 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x75, 0x73, 0x20, 0x44, 0x69, 0x72, + 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x20, 0x64, 0x65, 0x20, + 0x52, 0x65, 0x63, 0x65, 0x70, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, + 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x75, 0x65, 0x76, 0x61, 0x20, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, + 0x69, 0xc3, 0xb3, 0x6e, 0x2d, 0x7a, 0x20, 0x28, 0x50, 0x72, 0x6f, 0x74, + 0x65, 0x67, 0x69, 0x64, 0x61, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, + 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x75, 0x65, 0x76, 0x61, 0x20, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, + 0xc3, 0xb3, 0x6e, 0x2d, 0x74, 0x20, 0x28, 0x54, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x65, 0x29, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, + 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x44, + 0x65, 0x74, 0x61, 0x6c, 0x6c, 0x65, 0x73, 0x20, 0x64, 0x65, 0x20, 0x44, + 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, + 0x5f, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, + 0x22, 0x56, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x20, 0x45, 0x78, 0x70, 0x6c, + 0x6f, 0x72, 0x61, 0x64, 0x6f, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0xc3, 0xb3, 0x64, 0x69, 0x67, 0x6f, 0x20, 0x51, 0x52, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0x53, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x61, 0x72, 0x20, + 0x50, 0x61, 0x67, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x46, 0x65, 0x63, 0x68, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x73, 0x74, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x72, 0x6d, 0x61, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x61, 0x64, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x70, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x50, + 0x65, 0x6e, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x65, 0x6e, 0x76, 0x69, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0x72, 0x65, 0x63, 0x69, 0x62, 0x69, 0x64, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x61, 0x64, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x20, 0x64, 0x65, 0x20, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, 0xad, 0x61, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x72, + 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x6e, 0x69, 0x63, 0x69, 0x61, 0x72, 0x20, 0x4d, 0x69, 0x6e, 0x65, + 0x72, 0xc3, 0xad, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0x44, 0x65, 0x74, 0x65, 0x6e, 0x65, 0x72, 0x20, 0x4d, + 0x69, 0x6e, 0x65, 0x72, 0xc3, 0xad, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x68, + 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x48, 0x69, 0x6c, + 0x6f, 0x73, 0x20, 0x64, 0x65, 0x20, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, + 0xad, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, + 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, + 0x69, 0x63, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x73, 0x74, 0x61, 0x64, + 0xc3, 0xad, 0x73, 0x74, 0x69, 0x63, 0x61, 0x73, 0x20, 0x64, 0x65, 0x20, + 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, 0xad, 0x61, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, + 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x61, + 0x73, 0x61, 0x20, 0x48, 0x61, 0x73, 0x68, 0x20, 0x4c, 0x6f, 0x63, 0x61, + 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, + 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x61, 0x73, 0x61, 0x20, 0x48, 0x61, + 0x73, 0x68, 0x20, 0x64, 0x65, 0x20, 0x52, 0x65, 0x64, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, + 0x6c, 0x74, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x69, 0x66, 0x69, 0x63, + 0x75, 0x6c, 0x74, 0x61, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, + 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x69, + 0x65, 0x6d, 0x70, 0x6f, 0x20, 0x45, 0x73, 0x74, 0x2e, 0x20, 0x61, 0x6c, + 0x20, 0x42, 0x6c, 0x6f, 0x71, 0x75, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, + 0x66, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, 0xad, + 0x61, 0x20, 0x41, 0x50, 0x41, 0x47, 0x41, 0x44, 0x41, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, + 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0xc3, + 0xad, 0x61, 0x20, 0x45, 0x4e, 0x43, 0x45, 0x4e, 0x44, 0x49, 0x44, 0x41, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x64, 0x6f, + 0x73, 0x20, 0x43, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x73, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, + 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x6f, 0x64, 0x6f, 0x73, 0x20, 0x42, 0x6c, 0x6f, 0x71, 0x75, 0x65, + 0x61, 0x64, 0x6f, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x44, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0xc3, 0xb3, 0x6e, + 0x20, 0x49, 0x50, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x65, + 0x72, 0x73, 0x69, 0xc3, 0xb3, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x41, 0x6c, 0x74, 0x75, 0x72, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x69, + 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x6c, 0x6f, 0x71, 0x75, 0x65, 0x61, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, + 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, 0x73, 0x62, 0x6c, 0x6f, + 0x71, 0x75, 0x65, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, 0x5f, 0x62, + 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4c, 0x69, 0x6d, 0x70, 0x69, + 0x61, 0x72, 0x20, 0x54, 0x6f, 0x64, 0x6f, 0x73, 0x20, 0x6c, 0x6f, 0x73, + 0x20, 0x42, 0x6c, 0x6f, 0x71, 0x75, 0x65, 0x6f, 0x73, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72, + 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x72, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0x47, 0x72, 0xc3, 0xa1, 0x66, 0x69, 0x63, 0x6f, 0x20, 0x64, 0x65, + 0x20, 0x50, 0x72, 0x65, 0x63, 0x69, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, + 0x72, 0x69, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x72, 0x65, 0x63, + 0x69, 0x6f, 0x20, 0x41, 0x63, 0x74, 0x75, 0x61, 0x6c, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, 0x61, + 0x6e, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x61, 0x6d, 0x62, 0x69, + 0x6f, 0x20, 0x32, 0x34, 0x68, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x32, 0x34, 0x68, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x6e, 0x20, 0x32, + 0x34, 0x68, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, + 0x72, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x61, 0x70, 0x22, 0x3a, 0x20, 0x22, + 0x43, 0x61, 0x70, 0x2e, 0x20, 0x64, 0x65, 0x20, 0x4d, 0x65, 0x72, 0x63, + 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, + 0x3a, 0x20, 0x22, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, + 0x79, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x61, 0x6e, 0x74, 0x61, 0x6c, 0x6c, + 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, + 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x64, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x54, 0x65, 0x6d, 0x61, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x49, 0x64, 0x69, 0x6f, 0x6d, 0x61, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x78, 0x5f, 0x67, 0x72, 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x58, 0x20, 0x28, 0x56, 0x65, 0x72, 0x64, + 0x65, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, + 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x4f, 0x73, 0x63, 0x75, 0x72, 0x6f, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6c, 0x61, 0x72, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, + 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x74, 0x69, 0x72, 0x20, + 0x63, 0x6f, 0x6d, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x20, 0x70, + 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x61, 0x6c, 0x69, 0x7a, 0x61, 0x64, 0x61, + 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x73, 0x65, + 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x5f, 0x64, 0x61, + 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x55, 0x73, 0x61, 0x72, + 0x20, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x20, 0x69, 0x6e, + 0x74, 0x65, 0x67, 0x72, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x47, + 0x75, 0x61, 0x72, 0x64, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, + 0x65, 0x72, 0x72, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x41, 0x72, 0x63, 0x68, 0x69, 0x76, 0x6f, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x64, 0x69, 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x22, 0x3a, 0x20, 0x22, 0x56, + 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, + 0x6c, 0x70, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x79, 0x75, 0x64, 0x61, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, + 0x74, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, + 0x79, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x61, + 0x72, 0x20, 0x43, 0x6c, 0x61, 0x76, 0x65, 0x20, 0x50, 0x72, 0x69, 0x76, + 0x61, 0x64, 0x61, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x5f, 0x77, 0x61, 0x6c, + 0x6c, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x73, 0x70, 0x61, + 0x6c, 0x64, 0x61, 0x72, 0x20, 0x43, 0x61, 0x72, 0x74, 0x65, 0x72, 0x61, + 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x61, 0x6c, 0x69, 0x72, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, + 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x22, 0x3a, 0x20, + 0x22, 0x41, 0x63, 0x65, 0x72, 0x63, 0x61, 0x20, 0x64, 0x65, 0x20, 0x44, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x58, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, + 0x77, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x63, 0x74, 0x75, 0x61, 0x6c, 0x69, + 0x7a, 0x61, 0x72, 0x20, 0x41, 0x68, 0x6f, 0x72, 0x61, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, + 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x63, 0x65, 0x72, 0x63, + 0x61, 0x20, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, + 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, + 0x63, 0x6c, 0x69, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0x6f, 0x70, 0x69, 0x61, 0x72, 0x20, 0x61, 0x6c, 0x20, 0x50, + 0x6f, 0x72, 0x74, 0x61, 0x70, 0x61, 0x70, 0x65, 0x6c, 0x65, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, + 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, + 0x73, 0x63, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x65, + 0x63, 0x74, 0x61, 0x6e, 0x64, 0x6f, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0x53, 0x69, 0x6e, 0x63, 0x72, 0x6f, 0x6e, 0x69, + 0x7a, 0x61, 0x6e, 0x64, 0x6f, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, + 0x22, 0x42, 0x6c, 0x6f, 0x71, 0x75, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x65, 0x73, 0x5f, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x20, 0x68, 0x61, 0x79, 0x20, + 0x64, 0x69, 0x72, 0x65, 0x63, 0x63, 0x69, 0x6f, 0x6e, 0x65, 0x73, 0x20, + 0x64, 0x69, 0x73, 0x70, 0x6f, 0x6e, 0x69, 0x62, 0x6c, 0x65, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x72, 0x72, + 0x6f, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, + 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xc3, 0x89, 0x78, + 0x69, 0x74, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x77, + 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x64, + 0x76, 0x65, 0x72, 0x74, 0x65, 0x6e, 0x63, 0x69, 0x61, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, + 0x65, 0x78, 0x63, 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, + 0x6e, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x4c, 0x61, 0x20, 0x63, 0x61, + 0x6e, 0x74, 0x69, 0x64, 0x61, 0x64, 0x20, 0x65, 0x78, 0x63, 0x65, 0x64, + 0x65, 0x20, 0x65, 0x6c, 0x20, 0x73, 0x61, 0x6c, 0x64, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x63, 0x69, 0xc3, + 0xb3, 0x6e, 0x20, 0x65, 0x6e, 0x76, 0x69, 0x61, 0x64, 0x61, 0x20, 0x65, + 0x78, 0x69, 0x74, 0x6f, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x22, + 0x0a, 0x7d, 0x0a +}; +unsigned int res_lang_es_json_len = 4587; diff --git a/src/embedded/lang_fr.h b/src/embedded/lang_fr.h new file mode 100644 index 0000000..b83a63c --- /dev/null +++ b/src/embedded/lang_fr.h @@ -0,0 +1,388 @@ +unsigned char res_lang_fr_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x6f, 0x6c, 0x64, 0x65, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x65, 0x72, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x63, 0x65, 0x76, 0x6f, 0x69, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x61, 0x67, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x65, + 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc5, 0x93, 0x75, 0x64, 0x73, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, + 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x61, 0x72, 0x63, 0x68, 0xc3, + 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x61, 0x72, + 0x61, 0x6d, 0xc3, 0xa8, 0x74, 0x72, 0x65, 0x73, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0x52, 0xc3, 0xa9, 0x73, 0x75, 0x6d, 0xc3, 0xa9, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, + 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x72, 0x6f, 0x74, + 0xc3, 0xa9, 0x67, 0xc3, 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, + 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x6f, 0x74, 0x61, + 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x6f, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0xc3, + 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, + 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x56, 0x6f, 0x73, 0x20, 0x61, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x65, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x2d, 0x5a, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x2d, 0x54, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x75, 0x63, + 0x75, 0x6e, 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, + 0x74, 0x72, 0x6f, 0x75, 0x76, 0xc3, 0xa9, 0x65, 0x2e, 0x20, 0x43, 0x72, + 0xc3, 0xa9, 0x65, 0x7a, 0x2d, 0x65, 0x6e, 0x20, 0x75, 0x6e, 0x65, 0x20, + 0x61, 0x76, 0x65, 0x63, 0x20, 0x6c, 0x65, 0x73, 0x20, 0x62, 0x6f, 0x75, + 0x74, 0x6f, 0x6e, 0x73, 0x20, 0x63, 0x69, 0x2d, 0x64, 0x65, 0x73, 0x73, + 0x75, 0x73, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x65, 0x77, 0x5f, 0x7a, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x75, 0x76, 0x65, 0x6c, 0x6c, 0x65, + 0x20, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x2d, 0x5a, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x6f, 0x75, 0x76, 0x65, 0x6c, 0x6c, 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x2d, 0x54, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x79, 0x70, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x70, 0x79, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x70, 0x69, 0x65, 0x72, 0x20, 0x6c, 0x27, + 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, 0x63, 0x6f, 0x6d, 0x70, + 0x6c, 0xc3, 0xa8, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x74, + 0x68, 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x65, 0x72, 0x20, 0x64, + 0x65, 0x70, 0x75, 0x69, 0x73, 0x20, 0x63, 0x65, 0x74, 0x74, 0x65, 0x20, + 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, + 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x20, 0x6c, 0x61, + 0x20, 0x63, 0x6c, 0xc3, 0xa9, 0x20, 0x70, 0x72, 0x69, 0x76, 0xc3, 0xa9, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, + 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, + 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x70, 0x6f, 0x72, + 0x74, 0x65, 0x72, 0x20, 0x6c, 0x61, 0x20, 0x63, 0x6c, 0xc3, 0xa9, 0x20, + 0x64, 0x65, 0x20, 0x76, 0x69, 0x73, 0x75, 0x61, 0x6c, 0x69, 0x73, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x68, 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x41, 0x66, 0x66, 0x69, 0x63, 0x68, 0x65, 0x72, + 0x20, 0x6c, 0x65, 0x20, 0x51, 0x52, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x6f, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0xc3, + 0xa9, 0x20, 0x61, 0x75, 0x20, 0x64, 0xc3, 0xa9, 0x6d, 0x6f, 0x6e, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x61, 0x79, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x50, + 0x61, 0x79, 0x65, 0x72, 0x20, 0x64, 0x65, 0x70, 0x75, 0x69, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, + 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x65, + 0x72, 0x20, 0xc3, 0xa0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x6f, + 0x6e, 0x74, 0x61, 0x6e, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0xc3, 0xa9, + 0x6d, 0x6f, 0x20, 0x28, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x6e, 0x65, + 0x6c, 0x2c, 0x20, 0x63, 0x68, 0x69, 0x66, 0x66, 0x72, 0xc3, 0xa9, 0x29, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, + 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x72, 0x61, + 0x69, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, 0x6e, 0x65, 0x75, 0x72, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x46, 0x72, 0x61, 0x69, 0x73, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x65, 0x72, 0x20, 0x6c, 0x61, 0x20, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x66, 0x66, 0x61, 0x63, 0x65, 0x72, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x53, 0xc3, 0xa9, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x6e, 0x65, + 0x72, 0x20, 0x75, 0x6e, 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x70, 0x61, 0x73, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6c, + 0x6c, 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x61, 0x78, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x61, 0x78, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, + 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x69, 0x73, 0x70, 0x6f, 0x6e, + 0x69, 0x62, 0x6c, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x6f, 0x72, 0x6d, 0x61, + 0x74, 0x20, 0x64, 0x27, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, + 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x5f, 0x7a, 0x5f, 0x6f, + 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x74, 0x65, 0x20, + 0x3a, 0x20, 0x6c, 0x65, 0x73, 0x20, 0x6d, 0xc3, 0xa9, 0x6d, 0x6f, 0x73, + 0x20, 0x6e, 0x65, 0x20, 0x73, 0x6f, 0x6e, 0x74, 0x20, 0x64, 0x69, 0x73, + 0x70, 0x6f, 0x6e, 0x69, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x71, 0x75, 0x27, + 0x65, 0x6e, 0x20, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x61, 0x6e, 0x74, 0x20, + 0x76, 0x65, 0x72, 0x73, 0x20, 0x64, 0x65, 0x73, 0x20, 0x61, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x74, 0xc3, 0xa9, + 0x67, 0xc3, 0xa9, 0x65, 0x73, 0x20, 0x28, 0x7a, 0x29, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, + 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x63, 0x61, 0x72, 0x61, 0x63, + 0x74, 0xc3, 0xa8, 0x72, 0x65, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x22, 0x3a, + 0x20, 0x22, 0xc3, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x6e, 0x76, 0x6f, 0x69, 0x20, 0x64, 0x65, 0x20, 0x6c, 0x61, 0x20, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x72, 0x20, 0x6c, 0x27, 0x65, 0x6e, + 0x76, 0x6f, 0x69, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x72, 0x20, 0x6c, 0x61, 0x20, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x72, 0x20, + 0x65, 0x74, 0x20, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x65, 0x72, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, 0x63, 0x65, 0x6c, + 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6e, 0x6e, 0x75, 0x6c, 0x65, 0x72, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, + 0x69, 0x76, 0x69, 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x6f, 0x73, 0x20, 0x61, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x20, 0x64, 0x65, 0x20, 0x72, + 0xc3, 0xa9, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, 0x73, + 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x6f, 0x75, 0x76, 0x65, 0x6c, 0x6c, 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x2d, 0x7a, 0x20, 0x28, 0x70, 0x72, 0x6f, 0x74, 0xc3, + 0xa9, 0x67, 0xc3, 0xa9, 0x65, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, + 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x6f, 0x75, 0x76, 0x65, 0x6c, 0x6c, 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x2d, 0x74, 0x20, 0x28, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x65, 0x29, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, + 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x44, + 0xc3, 0xa9, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6c, + 0x27, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, + 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, + 0x56, 0x6f, 0x69, 0x72, 0x20, 0x73, 0x75, 0x72, 0x20, 0x6c, 0x27, 0x65, + 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x61, 0x74, 0x65, 0x75, 0x72, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x51, 0x52, 0x20, 0x43, 0x6f, 0x64, 0x65, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0x44, 0x65, 0x6d, 0x61, 0x6e, 0x64, 0x65, 0x72, 0x20, + 0x75, 0x6e, 0x20, 0x70, 0x61, 0x69, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x44, 0x61, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x53, 0x74, 0x61, 0x74, 0x75, 0x74, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x72, 0x6d, 0xc3, 0xa9, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x70, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x6e, 0x20, 0x61, 0x74, 0x74, 0x65, 0x6e, 0x74, 0x65, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0xc3, 0xa9, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0x72, 0x65, 0xc3, 0xa7, 0x75, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0xc3, 0xa9, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x43, + 0x6f, 0x6e, 0x74, 0x72, 0xc3, 0xb4, 0x6c, 0x65, 0x20, 0x64, 0x75, 0x20, + 0x6d, 0x69, 0x6e, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, + 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x44, 0xc3, 0xa9, 0x6d, 0x61, 0x72, + 0x72, 0x65, 0x72, 0x20, 0x6c, 0x65, 0x20, 0x6d, 0x69, 0x6e, 0x61, 0x67, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x6f, + 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x41, 0x72, 0x72, 0xc3, 0xaa, 0x74, 0x65, 0x72, 0x20, 0x6c, 0x65, 0x20, + 0x6d, 0x69, 0x6e, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x68, 0x72, + 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x68, 0x72, 0x65, + 0x61, 0x64, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, 0x6e, 0x61, 0x67, + 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, + 0x63, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x74, 0x61, 0x74, 0x69, 0x73, + 0x74, 0x69, 0x71, 0x75, 0x65, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, + 0x6e, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, + 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x48, 0x61, 0x73, 0x68, 0x72, 0x61, + 0x74, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, + 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x48, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x20, 0x64, 0x75, 0x20, + 0x72, 0xc3, 0xa9, 0x73, 0x65, 0x61, 0x75, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, + 0x79, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, + 0x6c, 0x74, 0xc3, 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x65, 0x6d, + 0x70, 0x73, 0x20, 0x65, 0x73, 0x74, 0x2e, 0x20, 0x61, 0x76, 0x61, 0x6e, + 0x74, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, 0x66, + 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x61, 0x67, 0x65, 0x20, 0x44, + 0xc3, 0x89, 0x53, 0x41, 0x43, 0x54, 0x49, 0x56, 0xc3, 0x89, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x5f, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x61, 0x67, + 0x65, 0x20, 0x41, 0x43, 0x54, 0x49, 0x56, 0xc3, 0x89, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x4e, 0xc5, 0x93, 0x75, 0x64, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0xc3, 0xa9, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, + 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc5, 0x93, 0x75, 0x64, 0x73, + 0x20, 0x62, 0x61, 0x6e, 0x6e, 0x69, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x20, 0x49, 0x50, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x48, + 0x61, 0x75, 0x74, 0x65, 0x75, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x69, + 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x61, 0x6e, 0x6e, 0x69, 0x72, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, 0x61, 0x6e, + 0x22, 0x3a, 0x20, 0x22, 0x44, 0xc3, 0xa9, 0x62, 0x61, 0x6e, 0x6e, 0x69, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, + 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, 0x5f, 0x62, 0x61, 0x6e, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x4c, 0x65, 0x76, 0x65, 0x72, 0x20, 0x74, 0x6f, 0x75, + 0x73, 0x20, 0x6c, 0x65, 0x73, 0x20, 0x62, 0x61, 0x6e, 0x6e, 0x69, 0x73, + 0x73, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, + 0x61, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x72, 0x61, 0x70, 0x68, + 0x69, 0x71, 0x75, 0x65, 0x20, 0x64, 0x65, 0x73, 0x20, 0x70, 0x72, 0x69, + 0x78, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x75, 0x72, + 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x50, 0x72, 0x69, 0x78, 0x20, 0x61, 0x63, 0x74, 0x75, 0x65, + 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, + 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x56, + 0x61, 0x72, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x32, 0x34, 0x68, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x20, 0x32, 0x34, 0x68, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x5f, 0x63, + 0x61, 0x70, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x61, 0x70, 0x69, 0x74, 0x61, + 0x6c, 0x69, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, + 0x22, 0x3a, 0x20, 0x22, 0x47, 0xc3, 0xa9, 0x6e, 0xc3, 0xa9, 0x72, 0x61, + 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, + 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x66, 0x66, 0x69, + 0x63, 0x68, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, + 0x52, 0xc3, 0xa9, 0x73, 0x65, 0x61, 0x75, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x68, 0xc3, 0xa8, 0x6d, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x5f, + 0x67, 0x72, 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x61, + 0x67, 0x6f, 0x6e, 0x58, 0x20, 0x28, 0x56, 0x65, 0x72, 0x74, 0x29, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x72, 0x6b, 0x22, + 0x3a, 0x20, 0x22, 0x53, 0x6f, 0x6d, 0x62, 0x72, 0x65, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0x43, 0x6c, 0x61, 0x69, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, + 0x74, 0x6f, 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x41, 0x75, 0x74, 0x6f, 0x72, 0x69, 0x73, 0x65, 0x72, 0x20, 0x6c, 0x65, + 0x73, 0x20, 0x66, 0x72, 0x61, 0x69, 0x73, 0x20, 0x70, 0x65, 0x72, 0x73, + 0x6f, 0x6e, 0x6e, 0x61, 0x6c, 0x69, 0x73, 0xc3, 0xa9, 0x73, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6d, + 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x5f, 0x64, 0x61, 0x65, 0x6d, 0x6f, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x73, 0x65, + 0x72, 0x20, 0x6c, 0x65, 0x20, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, + 0x64, 0x20, 0x69, 0x6e, 0x74, 0xc3, 0xa9, 0x67, 0x72, 0xc3, 0xa9, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, + 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, + 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x65, 0x72, 0x6d, 0x65, + 0x72, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, + 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x69, 0x63, 0x68, 0x69, 0x65, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x64, 0x69, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0xc3, 0x89, 0x64, 0x69, 0x74, 0x69, 0x6f, + 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, + 0x77, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x66, 0x66, 0x69, 0x63, 0x68, 0x61, + 0x67, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, + 0x6c, 0x70, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x69, 0x64, 0x65, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, + 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, + 0x20, 0x75, 0x6e, 0x65, 0x20, 0x63, 0x6c, 0xc3, 0xa9, 0x20, 0x70, 0x72, + 0x69, 0x76, 0xc3, 0xa9, 0x65, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x5f, 0x77, + 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x61, 0x75, + 0x76, 0x65, 0x67, 0x61, 0x72, 0x64, 0x65, 0x72, 0x20, 0x6c, 0x65, 0x20, + 0x70, 0x6f, 0x72, 0x74, 0x65, 0x66, 0x65, 0x75, 0x69, 0x6c, 0x6c, 0x65, + 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x51, 0x75, 0x69, 0x74, 0x74, + 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, + 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x22, + 0x3a, 0x20, 0x22, 0xc3, 0x80, 0x20, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, + 0x20, 0x64, 0x27, 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, 0x6e, 0x44, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, 0x77, + 0x22, 0x3a, 0x20, 0x22, 0x41, 0x63, 0x74, 0x75, 0x61, 0x6c, 0x69, 0x73, + 0x65, 0x72, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x61, 0x6e, + 0x74, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, + 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xc3, 0x80, 0x20, 0x70, 0x72, + 0x6f, 0x70, 0x6f, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, + 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, + 0x63, 0x6c, 0x69, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0x6f, 0x70, 0x69, 0x65, 0x72, 0x20, 0x64, 0x61, 0x6e, 0x73, + 0x20, 0x6c, 0x65, 0x20, 0x70, 0x72, 0x65, 0x73, 0x73, 0x65, 0x2d, 0x70, + 0x61, 0x70, 0x69, 0x65, 0x72, 0x73, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0xc3, + 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x44, 0xc3, 0xa9, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0xc3, + 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x43, + 0x6f, 0x6e, 0x6e, 0x65, 0x78, 0x69, 0x6f, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, + 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x79, 0x6e, 0x63, 0x68, 0x72, + 0x6f, 0x6e, 0x69, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x2e, 0x2e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x6c, 0x6f, 0x63, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x75, 0x63, 0x75, 0x6e, + 0x65, 0x20, 0x61, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x20, 0x64, 0x69, + 0x73, 0x70, 0x6f, 0x6e, 0x69, 0x62, 0x6c, 0x65, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, + 0x20, 0x22, 0x45, 0x72, 0x72, 0x65, 0x75, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x53, 0x75, 0x63, 0x63, 0xc3, 0xa8, 0x73, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x76, 0x65, 0x72, 0x74, 0x69, 0x73, + 0x73, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x65, 0x78, 0x63, + 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x4c, 0x65, 0x20, 0x6d, 0x6f, 0x6e, 0x74, 0x61, + 0x6e, 0x74, 0x20, 0x64, 0xc3, 0xa9, 0x70, 0x61, 0x73, 0x73, 0x65, 0x20, + 0x6c, 0x65, 0x20, 0x73, 0x6f, 0x6c, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0xc3, 0xa9, 0x65, 0x20, 0x61, 0x76, 0x65, + 0x63, 0x20, 0x73, 0x75, 0x63, 0x63, 0xc3, 0xa8, 0x73, 0x22, 0x0a, 0x7d, + 0x0a +}; +unsigned int res_lang_fr_json_len = 4609; diff --git a/src/embedded/lang_ja.h b/src/embedded/lang_ja.h new file mode 100644 index 0000000..a96913b --- /dev/null +++ b/src/embedded/lang_ja.h @@ -0,0 +1,416 @@ +unsigned char res_lang_ja_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xae, 0x8b, 0xe9, 0xab, 0x98, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x97, 0xe5, 0x8f, 0x96, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe5, + 0x8f, 0x96, 0xe5, 0xbc, 0x95, 0xe5, 0xb1, 0xa5, 0xe6, 0xad, 0xb4, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, 0xe3, + 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x83, 0x8e, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x89, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x83, 0xbc, 0xe3, 0x82, + 0xb1, 0xe3, 0x83, 0x83, 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe8, 0xa8, 0xad, 0xe5, 0xae, 0x9a, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, + 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xa6, 0x82, 0xe8, 0xa6, 0x81, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, 0x6c, + 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xb7, 0xe3, 0x83, + 0xbc, 0xe3, 0x83, 0xab, 0xe3, 0x83, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, + 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x88, 0xe3, 0x83, 0xa9, + 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0x91, 0xe3, 0x83, 0xac, + 0xe3, 0x83, 0xb3, 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe5, + 0x90, 0x88, 0xe8, 0xa8, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x75, 0x6e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x9c, 0xaa, 0xe7, 0xa2, 0xba, 0xe8, 0xaa, + 0x8d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, + 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, + 0xe3, 0x82, 0xb9, 0xe4, 0xb8, 0x80, 0xe8, 0xa6, 0xa7, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x5a, 0x2d, 0xe3, 0x82, + 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x2d, 0xe3, + 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, + 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xe3, + 0x81, 0x8c, 0xe8, 0xa6, 0x8b, 0xe3, 0x81, 0xa4, 0xe3, 0x81, 0x8b, 0xe3, + 0x82, 0x8a, 0xe3, 0x81, 0xbe, 0xe3, 0x81, 0x9b, 0xe3, 0x82, 0x93, 0xe3, + 0x80, 0x82, 0xe4, 0xb8, 0x8a, 0xe3, 0x81, 0xae, 0xe3, 0x83, 0x9c, 0xe3, + 0x82, 0xbf, 0xe3, 0x83, 0xb3, 0xe3, 0x81, 0xa7, 0xe4, 0xbd, 0x9c, 0xe6, + 0x88, 0x90, 0xe3, 0x81, 0x97, 0xe3, 0x81, 0xa6, 0xe3, 0x81, 0x8f, 0xe3, + 0x81, 0xa0, 0xe3, 0x81, 0x95, 0xe3, 0x81, 0x84, 0xe3, 0x80, 0x82, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x96, 0xb0, 0xe8, 0xa6, 0x8f, 0x20, 0x5a, 0x2d, 0xe3, 0x82, 0xa2, + 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, + 0xb0, 0xe8, 0xa6, 0x8f, 0x20, 0x54, 0x2d, 0xe3, 0x82, 0xa2, 0xe3, 0x83, + 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe3, + 0x82, 0xbf, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x97, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, + 0xe3, 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x70, 0x79, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, + 0xe3, 0x82, 0xb9, 0xe3, 0x82, 0x92, 0xe3, 0x82, 0xb3, 0xe3, 0x83, 0x94, + 0xe3, 0x83, 0xbc, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x74, 0x68, 0x69, + 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x81, 0x93, 0xe3, 0x81, 0xae, 0xe3, 0x82, 0xa2, 0xe3, 0x83, + 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xe3, 0x81, 0x8b, 0xe3, 0x82, + 0x89, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, + 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0xe7, 0xa7, 0x98, 0xe5, 0xaf, 0x86, 0xe9, 0x8d, 0xb5, 0xe3, 0x82, + 0x92, 0xe3, 0x82, 0xa8, 0xe3, 0x82, 0xaf, 0xe3, 0x82, 0xb9, 0xe3, 0x83, + 0x9d, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x69, + 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0xe9, 0x96, 0xb2, 0xe8, 0xa6, 0xa7, 0xe9, 0x8d, 0xb5, 0xe3, 0x82, + 0x92, 0xe3, 0x82, 0xa8, 0xe3, 0x82, 0xaf, 0xe3, 0x82, 0xb9, 0xe3, 0x83, + 0x9d, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x68, 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, + 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x51, 0x52, 0xe3, 0x82, 0xb3, + 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x89, 0xe3, 0x82, 0x92, 0xe8, 0xa1, 0xa8, + 0xe7, 0xa4, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x87, 0xe3, 0x83, 0xbc, 0xe3, 0x83, + 0xa2, 0xe3, 0x83, 0xb3, 0xe3, 0x81, 0xab, 0xe6, 0x9c, 0xaa, 0xe6, 0x8e, + 0xa5, 0xe7, 0xb6, 0x9a, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x79, 0x5f, 0x66, 0x72, 0x6f, 0x6d, + 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x94, 0xaf, 0xe6, 0x89, 0x95, 0xe5, 0x85, + 0x83, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x64, 0x5f, 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, + 0x87, 0x91, 0xe5, 0x85, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe9, + 0x87, 0x91, 0xe9, 0xa1, 0x8d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0xa1, + 0xe3, 0x83, 0xa2, 0xef, 0xbc, 0x88, 0xe4, 0xbb, 0xbb, 0xe6, 0x84, 0x8f, + 0xe3, 0x80, 0x81, 0xe6, 0x9a, 0x97, 0xe5, 0x8f, 0xb7, 0xe5, 0x8c, 0x96, + 0xef, 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8a, 0xe3, 0x83, 0xbc, + 0xe6, 0x89, 0x8b, 0xe6, 0x95, 0xb0, 0xe6, 0x96, 0x99, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x89, 0x8b, 0xe6, 0x95, 0xb0, 0xe6, 0x96, 0x99, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, + 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0xe3, 0x81, 0x99, 0xe3, 0x82, + 0x8b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, + 0x61, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xaf, 0xe3, 0x83, 0xaa, + 0xe3, 0x82, 0xa2, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6c, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, + 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xe3, 0x82, 0x92, 0xe9, 0x81, 0xb8, 0xe6, + 0x8a, 0x9e, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x70, 0x61, 0x73, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe8, 0xb2, + 0xbc, 0xe3, 0x82, 0x8a, 0xe4, 0xbb, 0x98, 0xe3, 0x81, 0x91, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, 0x3a, 0x20, + 0x22, 0xe6, 0x9c, 0x80, 0xe5, 0xa4, 0xa7, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x88, 0xa9, 0xe7, 0x94, 0xa8, 0xe5, 0x8f, + 0xaf, 0xe8, 0x83, 0xbd, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0x84, 0xa1, 0xe5, 0x8a, + 0xb9, 0xe3, 0x81, 0xaa, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, + 0xac, 0xe3, 0x82, 0xb9, 0xe5, 0xbd, 0xa2, 0xe5, 0xbc, 0x8f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x5f, 0x7a, + 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xb3, 0xa8, + 0xef, 0xbc, 0x9a, 0xe3, 0x83, 0xa1, 0xe3, 0x83, 0xa2, 0xe3, 0x81, 0xaf, + 0xe3, 0x82, 0xb7, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0xab, 0xe3, 0x83, 0x89, + 0xef, 0xbc, 0x88, 0x7a, 0xef, 0xbc, 0x89, 0xe3, 0x82, 0xa2, 0xe3, 0x83, + 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xe3, 0x81, 0xb8, 0xe3, 0x81, + 0xae, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0xe6, 0x99, 0x82, 0xe3, 0x81, + 0xae, 0xe3, 0x81, 0xbf, 0xe5, 0x88, 0xa9, 0xe7, 0x94, 0xa8, 0xe5, 0x8f, + 0xaf, 0xe8, 0x83, 0xbd, 0xe3, 0x81, 0xa7, 0xe3, 0x81, 0x99, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, + 0x74, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, 0x87, 0xe5, + 0xad, 0x97, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x72, + 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, + 0xe5, 0x85, 0x83, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, + 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0xe5, + 0x85, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, + 0xe9, 0x87, 0x91, 0xe4, 0xb8, 0xad, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x73, 0x65, + 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, + 0xe7, 0xa2, 0xba, 0xe8, 0xaa, 0x8d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, + 0x22, 0xe5, 0x8f, 0x96, 0xe5, 0xbc, 0x95, 0xe7, 0xa2, 0xba, 0xe8, 0xaa, + 0x8d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x6e, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa2, 0xba, 0xe8, 0xaa, 0x8d, 0xe3, + 0x81, 0x97, 0xe3, 0x81, 0xa6, 0xe9, 0x80, 0x81, 0xe9, 0x87, 0x91, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, 0x63, 0x65, + 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xad, 0xe3, 0x83, 0xa3, 0xe3, + 0x83, 0xb3, 0xe3, 0x82, 0xbb, 0xe3, 0x83, 0xab, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x69, + 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x97, 0xe5, 0x8f, 0x96, 0xe3, 0x82, + 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, + 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x96, 0xb0, 0xe8, 0xa6, 0x8f, 0x20, 0x7a, 0x2d, 0xe3, 0x82, 0xa2, + 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xef, 0xbc, 0x88, + 0xe3, 0x82, 0xb7, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0xab, 0xe3, 0x83, 0x89, + 0xef, 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, + 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, 0xb0, 0xe8, + 0xa6, 0x8f, 0x20, 0x74, 0x2d, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, + 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xef, 0xbc, 0x88, 0xe3, 0x83, 0x88, 0xe3, + 0x83, 0xa9, 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0x91, 0xe3, + 0x83, 0xac, 0xe3, 0x83, 0xb3, 0xe3, 0x83, 0x88, 0xef, 0xbc, 0x89, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, + 0x82, 0xb9, 0xe8, 0xa9, 0xb3, 0xe7, 0xb4, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, + 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, + 0xe3, 0x82, 0xa8, 0xe3, 0x82, 0xaf, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0x97, + 0xe3, 0x83, 0xad, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0xa9, 0xe3, 0x83, 0xbc, + 0xe3, 0x81, 0xa7, 0xe8, 0xa1, 0xa8, 0xe7, 0xa4, 0xba, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x51, 0x52, 0xe3, 0x82, 0xb3, 0xe3, 0x83, 0xbc, + 0xe3, 0x83, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, + 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x94, 0xaf, 0xe6, 0x89, 0x95, + 0xe3, 0x81, 0x84, 0xe3, 0x82, 0x92, 0xe8, 0xa6, 0x81, 0xe6, 0xb1, 0x82, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x97, 0xa5, 0xe4, 0xbb, 0x98, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0x86, 0xe3, + 0x83, 0xbc, 0xe3, 0x82, 0xbf, 0xe3, 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa2, 0xba, + 0xe8, 0xaa, 0x8d, 0xe6, 0x95, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0xe7, 0xa2, 0xba, 0xe8, 0xaa, 0x8d, 0xe6, 0xb8, 0x88, + 0xe3, 0x81, 0xbf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbf, + 0x9d, 0xe7, 0x95, 0x99, 0xe4, 0xb8, 0xad, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe9, + 0x80, 0x81, 0xe9, 0x87, 0x91, 0xe6, 0xb8, 0x88, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x97, 0xe5, 0x8f, 0x96, 0xe6, 0xb8, + 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8e, 0xa1, 0xe6, 0x8e, 0x98, + 0xe6, 0xb8, 0x88, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, + 0xe3, 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb0, 0xe5, 0x88, 0xb6, + 0xe5, 0xbe, 0xa1, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8b, + 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb0, 0xe9, 0x96, 0x8b, 0xe5, 0xa7, 0x8b, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x6f, 0x70, + 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe3, + 0x83, 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, + 0x82, 0xb0, 0xe5, 0x81, 0x9c, 0xe6, 0xad, 0xa2, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, + 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, + 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, 0x82, + 0xb0, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0xac, 0xe3, 0x83, 0x83, 0xe3, 0x83, + 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, + 0x63, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, + 0xe3, 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, 0x82, 0xb0, 0xe7, 0xb5, 0xb1, + 0xe8, 0xa8, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, + 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0xad, 0xe3, 0x83, 0xbc, 0xe3, + 0x82, 0xab, 0xe3, 0x83, 0xab, 0xe3, 0x83, 0x8f, 0xe3, 0x83, 0x83, 0xe3, + 0x82, 0xb7, 0xe3, 0x83, 0xa5, 0xe3, 0x83, 0xac, 0xe3, 0x83, 0xbc, 0xe3, + 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, + 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x8d, 0xe3, 0x83, 0x83, + 0xe3, 0x83, 0x88, 0xe3, 0x83, 0xaf, 0xe3, 0x83, 0xbc, 0xe3, 0x82, 0xaf, + 0xe3, 0x83, 0x8f, 0xe3, 0x83, 0x83, 0xe3, 0x82, 0xb7, 0xe3, 0x83, 0xa5, + 0xe3, 0x83, 0xac, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, + 0x6c, 0x74, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x9b, 0xa3, 0xe6, 0x98, + 0x93, 0xe5, 0xba, 0xa6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8e, 0xa8, + 0xe5, 0xae, 0x9a, 0xe3, 0x83, 0x96, 0xe3, 0x83, 0xad, 0xe3, 0x83, 0x83, + 0xe3, 0x82, 0xaf, 0xe7, 0x99, 0xba, 0xe8, 0xa6, 0x8b, 0xe6, 0x99, 0x82, + 0xe9, 0x96, 0x93, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, 0x66, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x83, 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8b, 0xe3, 0x83, + 0xb3, 0xe3, 0x82, 0xb0, 0xe5, 0x81, 0x9c, 0xe6, 0xad, 0xa2, 0xe4, 0xb8, + 0xad, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, + 0x9e, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x8b, 0xe3, 0x83, 0xb3, 0xe3, 0x82, + 0xb0, 0xe7, 0xa8, 0xbc, 0xe5, 0x83, 0x8d, 0xe4, 0xb8, 0xad, 0x22, 0x2c, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, + 0x63, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xe6, 0x8e, 0xa5, 0xe7, 0xb6, 0x9a, 0xe4, 0xb8, 0xad, 0xe3, + 0x81, 0xae, 0xe3, 0x83, 0x8e, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x89, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, 0x65, + 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, + 0x83, 0x96, 0xe3, 0x83, 0xad, 0xe3, 0x83, 0x83, 0xe3, 0x82, 0xaf, 0xe6, + 0xb8, 0x88, 0xe3, 0x81, 0xbf, 0xe3, 0x83, 0x8e, 0xe3, 0x83, 0xbc, 0xe3, + 0x83, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x70, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x49, 0x50, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, 0xe3, 0x83, 0xac, 0xe3, + 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x90, + 0xe3, 0x83, 0xbc, 0xe3, 0x82, 0xb8, 0xe3, 0x83, 0xa7, 0xe3, 0x83, 0xb3, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x96, 0xe3, 0x83, 0xad, + 0xe3, 0x83, 0x83, 0xe3, 0x82, 0xaf, 0xe9, 0xab, 0x98, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0x50, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x96, 0xe3, + 0x83, 0xad, 0xe3, 0x83, 0x83, 0xe3, 0x82, 0xaf, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x83, 0x96, 0xe3, 0x83, 0xad, 0xe3, 0x83, 0x83, 0xe3, 0x82, + 0xaf, 0xe8, 0xa7, 0xa3, 0xe9, 0x99, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, + 0x5f, 0x62, 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x81, 0x99, + 0xe3, 0x81, 0xb9, 0xe3, 0x81, 0xa6, 0xe3, 0x81, 0xae, 0xe3, 0x83, 0x96, + 0xe3, 0x83, 0xad, 0xe3, 0x83, 0x83, 0xe3, 0x82, 0xaf, 0xe3, 0x82, 0x92, + 0xe8, 0xa7, 0xa3, 0xe9, 0x99, 0xa4, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, + 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbe, 0xa1, 0xe6, 0xa0, 0xbc, + 0xe3, 0x83, 0x81, 0xe3, 0x83, 0xa3, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x88, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x75, 0x72, 0x72, + 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0xe7, 0x8f, 0xbe, 0xe5, 0x9c, 0xa8, 0xe4, 0xbe, 0xa1, 0xe6, 0xa0, + 0xbc, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, + 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x32, + 0x34, 0xe6, 0x99, 0x82, 0xe9, 0x96, 0x93, 0xe5, 0xa4, 0x89, 0xe5, 0x8b, + 0x95, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, + 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x32, + 0x34, 0xe6, 0x99, 0x82, 0xe9, 0x96, 0x93, 0xe5, 0x8f, 0x96, 0xe5, 0xbc, + 0x95, 0xe9, 0x87, 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x61, 0x70, 0x22, 0x3a, + 0x20, 0x22, 0xe6, 0x99, 0x82, 0xe4, 0xbe, 0xa1, 0xe7, 0xb7, 0x8f, 0xe9, + 0xa1, 0x8d, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, + 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xb8, + 0x80, 0xe8, 0x88, 0xac, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe8, + 0xa1, 0xa8, 0xe7, 0xa4, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, + 0xe3, 0x83, 0x8d, 0xe3, 0x83, 0x83, 0xe3, 0x83, 0x88, 0xe3, 0x83, 0xaf, + 0xe3, 0x83, 0xbc, 0xe3, 0x82, 0xaf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe3, + 0x83, 0x86, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x9e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xe8, 0xa8, 0x80, 0xe8, 0xaa, 0x9e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x78, 0x5f, 0x67, 0x72, 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x58, 0xef, 0xbc, 0x88, 0xe3, 0x82, 0xb0, + 0xe3, 0x83, 0xaa, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0xb3, 0xef, 0xbc, 0x89, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x72, 0x6b, + 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x80, 0xe3, 0x83, 0xbc, 0xe3, 0x82, + 0xaf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, + 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0xa9, 0xe3, 0x82, 0xa4, + 0xe3, 0x83, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, + 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, + 0x66, 0x65, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xab, 0xe3, + 0x82, 0xb9, 0xe3, 0x82, 0xbf, 0xe3, 0x83, 0xa0, 0xe6, 0x89, 0x8b, 0xe6, + 0x95, 0xb0, 0xe6, 0x96, 0x99, 0xe3, 0x82, 0x92, 0xe8, 0xa8, 0xb1, 0xe5, + 0x8f, 0xaf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x73, + 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x5f, 0x64, + 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x86, 0x85, + 0xe8, 0x94, 0xb5, 0x20, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, + 0x20, 0xe3, 0x82, 0x92, 0xe4, 0xbd, 0xbf, 0xe7, 0x94, 0xa8, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xe4, 0xbf, 0x9d, 0xe5, 0xad, 0x98, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0xe9, 0x96, 0x89, 0xe3, 0x81, 0x98, 0xe3, 0x82, 0x8b, 0x22, 0x2c, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x95, 0xe3, 0x82, 0xa1, 0xe3, 0x82, 0xa4, + 0xe3, 0x83, 0xab, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xb7, 0xa8, 0xe9, 0x9b, + 0x86, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, + 0x77, 0x22, 0x3a, 0x20, 0x22, 0xe8, 0xa1, 0xa8, 0xe7, 0xa4, 0xba, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x70, 0x22, + 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x98, 0xe3, 0x83, 0xab, 0xe3, 0x83, 0x97, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, + 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, + 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa7, 0x98, 0xe5, 0xaf, 0x86, + 0xe9, 0x8d, 0xb5, 0xe3, 0x82, 0x92, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0xb3, + 0xe3, 0x83, 0x9d, 0xe3, 0x83, 0xbc, 0xe3, 0x83, 0x88, 0x2e, 0x2e, 0x2e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, 0x6b, + 0x75, 0x70, 0x5f, 0x77, 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x82, 0xa6, 0xe3, 0x82, 0xa9, 0xe3, 0x83, 0xac, 0xe3, 0x83, + 0x83, 0xe3, 0x83, 0x88, 0xe3, 0x82, 0x92, 0xe3, 0x83, 0x90, 0xe3, 0x83, + 0x83, 0xe3, 0x82, 0xaf, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x83, 0xe3, 0x83, + 0x97, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xb5, 0x82, 0xe4, + 0xba, 0x86, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, + 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x22, + 0x3a, 0x20, 0x22, 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, 0x6e, 0x44, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0xe3, 0x81, 0xab, 0xe3, 0x81, 0xa4, 0xe3, + 0x81, 0x84, 0xe3, 0x81, 0xa6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, 0x77, + 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbb, 0x8a, 0xe3, 0x81, 0x99, 0xe3, 0x81, + 0x90, 0xe6, 0x9b, 0xb4, 0xe6, 0x96, 0xb0, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xe3, 0x81, 0x93, 0xe3, 0x81, 0xae, 0xe3, 0x82, 0xa2, 0xe3, 0x83, + 0x97, 0xe3, 0x83, 0xaa, 0xe3, 0x81, 0xab, 0xe3, 0x81, 0xa4, 0xe3, 0x81, + 0x84, 0xe3, 0x81, 0xa6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, + 0xa4, 0xe3, 0x83, 0xb3, 0xe3, 0x83, 0x9d, 0xe3, 0x83, 0xbc, 0xe3, 0x83, + 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, + 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa8, 0xe3, 0x82, + 0xaf, 0xe3, 0x82, 0xb9, 0xe3, 0x83, 0x9d, 0xe3, 0x83, 0xbc, 0xe3, 0x83, + 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, + 0x79, 0x5f, 0x74, 0x6f, 0x5f, 0x63, 0x6c, 0x69, 0x70, 0x62, 0x6f, 0x61, + 0x72, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xaf, 0xe3, 0x83, 0xaa, + 0xe3, 0x83, 0x83, 0xe3, 0x83, 0x97, 0xe3, 0x83, 0x9c, 0xe3, 0x83, 0xbc, + 0xe3, 0x83, 0x89, 0xe3, 0x81, 0xab, 0xe3, 0x82, 0xb3, 0xe3, 0x83, 0x94, + 0xe3, 0x83, 0xbc, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0xe6, 0x8e, 0xa5, 0xe7, 0xb6, 0x9a, 0xe6, 0xb8, 0x88, 0xe3, 0x81, + 0xbf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0xe5, 0x88, 0x87, 0xe6, 0x96, 0xad, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8e, 0xa5, 0xe7, 0xb6, 0x9a, 0xe4, + 0xb8, 0xad, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0xe5, 0x90, 0x8c, 0xe6, 0x9c, 0x9f, 0xe4, 0xb8, 0xad, 0x2e, 0x2e, 0x2e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x83, 0x96, 0xe3, 0x83, 0xad, 0xe3, + 0x83, 0x83, 0xe3, 0x82, 0xaf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x5f, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0xe5, 0x88, 0xa9, 0xe7, 0x94, 0xa8, 0xe5, 0x8f, 0xaf, + 0xe8, 0x83, 0xbd, 0xe3, 0x81, 0xaa, 0xe3, 0x82, 0xa2, 0xe3, 0x83, 0x89, + 0xe3, 0x83, 0xac, 0xe3, 0x82, 0xb9, 0xe3, 0x81, 0x8c, 0xe3, 0x81, 0x82, + 0xe3, 0x82, 0x8a, 0xe3, 0x81, 0xbe, 0xe3, 0x81, 0x9b, 0xe3, 0x82, 0x93, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x72, 0x72, + 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xe3, 0x82, 0xa8, 0xe3, 0x83, 0xa9, + 0xe3, 0x83, 0xbc, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x88, + 0x90, 0xe5, 0x8a, 0x9f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe8, + 0xad, 0xa6, 0xe5, 0x91, 0x8a, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x65, 0x78, 0x63, 0x65, + 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0xe9, 0x87, 0x91, 0xe9, 0xa1, 0x8d, 0xe3, 0x81, 0x8c, + 0xe6, 0xae, 0x8b, 0xe9, 0xab, 0x98, 0xe3, 0x82, 0x92, 0xe8, 0xb6, 0x85, + 0xe3, 0x81, 0x88, 0xe3, 0x81, 0xa6, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0xbe, + 0xe3, 0x81, 0x99, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x81, 0xe9, 0x87, + 0x91, 0xe3, 0x81, 0x8c, 0xe5, 0xae, 0x8c, 0xe4, 0xba, 0x86, 0xe3, 0x81, + 0x97, 0xe3, 0x81, 0xbe, 0xe3, 0x81, 0x97, 0xe3, 0x81, 0x9f, 0x22, 0x0a, + 0x7d, 0x0a +}; +unsigned int res_lang_ja_json_len = 4946; diff --git a/src/embedded/lang_ko.h b/src/embedded/lang_ko.h new file mode 100644 index 0000000..d58f015 --- /dev/null +++ b/src/embedded/lang_ko.h @@ -0,0 +1,379 @@ +unsigned char res_lang_ko_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x9e, 0x94, 0xec, 0x95, 0xa1, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, + 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, + 0x65, 0x69, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb0, 0x9b, 0xea, + 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xea, 0xb1, 0xb0, 0xeb, 0x9e, 0x98, 0x20, 0xeb, 0x82, 0xb4, + 0xec, 0x97, 0xad, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, + 0xea, 0xb5, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x85, 0xb8, 0xeb, + 0x93, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, + 0x72, 0x6b, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x8b, 0x9c, 0xec, + 0x9e, 0xa5, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x84, + 0xa4, 0xec, 0xa0, 0x95, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, + 0xec, 0x9a, 0x94, 0xec, 0x95, 0xbd, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0xb0, 0xa8, 0xed, 0x8f, 0x90, 0xeb, 0x90, 0xa8, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x88, + 0xac, 0xeb, 0xaa, 0x85, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x95, 0xa9, + 0xea, 0xb3, 0x84, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, + 0x6e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0xeb, 0xaf, 0xb8, 0xed, 0x99, 0x95, 0xec, 0x9d, 0xb8, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, 0x72, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xeb, 0x82, 0xb4, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x5a, 0x2d, + 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x2d, 0xec, 0xa3, 0xbc, 0xec, 0x86, + 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0xeb, 0xa5, 0xbc, 0x20, 0xec, + 0xb0, 0xbe, 0xec, 0x9d, 0x84, 0x20, 0xec, 0x88, 0x98, 0x20, 0xec, 0x97, + 0x86, 0xec, 0x8a, 0xb5, 0xeb, 0x8b, 0x88, 0xeb, 0x8b, 0xa4, 0x2e, 0x20, + 0xec, 0x9c, 0x84, 0xec, 0x9d, 0x98, 0x20, 0xeb, 0xb2, 0x84, 0xed, 0x8a, + 0xbc, 0xec, 0x9d, 0x84, 0x20, 0xec, 0x82, 0xac, 0xec, 0x9a, 0xa9, 0xed, + 0x95, 0x98, 0xec, 0x97, 0xac, 0x20, 0xec, 0x83, 0x9d, 0xec, 0x84, 0xb1, + 0xed, 0x95, 0x98, 0xec, 0x84, 0xb8, 0xec, 0x9a, 0x94, 0x2e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, + 0x83, 0x88, 0x20, 0x5a, 0x2d, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xec, 0x83, 0x88, 0x20, 0x54, 0x2d, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x79, 0x70, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xec, 0x9c, 0xa0, 0xed, 0x98, 0x95, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, + 0xa0, 0x84, 0xec, 0xb2, 0xb4, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, + 0x20, 0xeb, 0xb3, 0xb5, 0xec, 0x82, 0xac, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, + 0x5f, 0x74, 0x68, 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x9d, 0xb4, 0x20, 0xec, 0xa3, 0xbc, + 0xec, 0x86, 0x8c, 0xec, 0x97, 0x90, 0xec, 0x84, 0x9c, 0x20, 0xeb, 0xb3, + 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, + 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0xea, 0xb0, 0x9c, 0xec, 0x9d, 0xb8, 0xed, 0x82, 0xa4, 0x20, 0xeb, + 0x82, 0xb4, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, 0xb0, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, + 0x74, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, 0x65, + 0x79, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa1, 0xb0, 0xed, 0x9a, 0x8c, 0xed, + 0x82, 0xa4, 0x20, 0xeb, 0x82, 0xb4, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb4, + 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x68, 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x51, 0x52, 0x20, 0xec, 0xbd, 0x94, 0xeb, 0x93, 0x9c, + 0x20, 0xed, 0x91, 0x9c, 0xec, 0x8b, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, + 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x8d, 0xb0, 0xeb, + 0xaa, 0xac, 0xec, 0x97, 0x90, 0x20, 0xec, 0x97, 0xb0, 0xea, 0xb2, 0xb0, + 0xeb, 0x90, 0x98, 0xec, 0xa7, 0x80, 0x20, 0xec, 0x95, 0x8a, 0xec, 0x9d, + 0x8c, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x70, 0x61, 0x79, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, + 0x22, 0xec, 0xb6, 0x9c, 0xea, 0xb8, 0x88, 0x20, 0xec, 0xa3, 0xbc, 0xec, + 0x86, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, + 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb0, 0x9b, + 0xeb, 0x8a, 0x94, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xea, 0xb8, 0x88, 0xec, 0x95, 0xa1, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, + 0x20, 0x22, 0xeb, 0xa9, 0x94, 0xeb, 0xaa, 0xa8, 0x20, 0x28, 0xec, 0x84, + 0xa0, 0xed, 0x83, 0x9d, 0xec, 0x82, 0xac, 0xed, 0x95, 0xad, 0x2c, 0x20, + 0xec, 0x95, 0x94, 0xed, 0x98, 0xb8, 0xed, 0x99, 0x94, 0xeb, 0x90, 0xa8, + 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x65, 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, + 0x84, 0xea, 0xb5, 0xb4, 0xec, 0x9e, 0x90, 0x20, 0xec, 0x88, 0x98, 0xec, + 0x88, 0x98, 0xeb, 0xa3, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x88, 0x98, 0xec, + 0x88, 0x98, 0xeb, 0xa3, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xea, 0xb1, 0xb0, + 0xeb, 0x9e, 0x98, 0x20, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, + 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, + 0x61, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa7, 0x80, 0xec, 0x9a, 0xb0, + 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6c, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x20, + 0xec, 0x84, 0xa0, 0xed, 0x83, 0x9d, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x73, 0x74, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xeb, 0xb6, 0x99, 0xec, 0x97, 0xac, 0xeb, 0x84, 0xa3, 0xea, + 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, + 0x78, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb5, 0x9c, 0xeb, 0x8c, 0x80, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, + 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x82, 0xac, 0xec, + 0x9a, 0xa9, 0x20, 0xea, 0xb0, 0x80, 0xeb, 0x8a, 0xa5, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xec, 0x9e, 0x98, 0xeb, 0xaa, 0xbb, 0xeb, 0x90, 0x9c, 0x20, 0xec, 0xa3, + 0xbc, 0xec, 0x86, 0x8c, 0x20, 0xed, 0x98, 0x95, 0xec, 0x8b, 0x9d, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x5f, + 0x7a, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb0, + 0xb8, 0xea, 0xb3, 0xa0, 0x3a, 0x20, 0xeb, 0xa9, 0x94, 0xeb, 0xaa, 0xa8, + 0xeb, 0x8a, 0x94, 0x20, 0xec, 0xb0, 0xa8, 0xed, 0x8f, 0x90, 0x28, 0x7a, + 0x29, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0xeb, 0xa1, 0x9c, 0x20, + 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xbc, 0x20, 0xeb, 0x95, 0x8c, 0xeb, 0xa7, + 0x8c, 0x20, 0xec, 0x82, 0xac, 0xec, 0x9a, 0xa9, 0xed, 0x95, 0xa0, 0x20, + 0xec, 0x88, 0x98, 0x20, 0xec, 0x9e, 0x88, 0xec, 0x8a, 0xb5, 0xeb, 0x8b, + 0x88, 0xeb, 0x8b, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xea, 0xb8, 0x80, 0xec, 0x9e, 0x90, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, + 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb8, 0x20, 0xec, 0x82, 0xac, 0xeb, 0x9e, + 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x22, + 0x3a, 0x20, 0x22, 0xeb, 0xb0, 0x9b, 0xeb, 0x8a, 0x94, 0x20, 0xec, 0x82, + 0xac, 0xeb, 0x9e, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xea, + 0xb1, 0xb0, 0xeb, 0x9e, 0x98, 0x20, 0xec, 0xa0, 0x84, 0xec, 0x86, 0xa1, + 0x20, 0xec, 0xa4, 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x73, 0x65, 0x6e, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, + 0xb0, 0x20, 0xed, 0x99, 0x95, 0xec, 0x9d, 0xb8, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, + 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, + 0x3a, 0x20, 0x22, 0xea, 0xb1, 0xb0, 0xeb, 0x9e, 0x98, 0x20, 0xed, 0x99, + 0x95, 0xec, 0x9d, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, 0x5f, + 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x99, 0x95, 0xec, + 0x9d, 0xb8, 0x20, 0xeb, 0xb0, 0x8f, 0x20, 0xeb, 0xb3, 0xb4, 0xeb, 0x82, + 0xb4, 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb7, + 0xa8, 0xec, 0x86, 0x8c, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x69, 0x6e, 0x67, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xec, 0x88, 0x98, 0xec, 0x8b, 0xa0, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, + 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, + 0x5f, 0x7a, 0x5f, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0xec, 0x83, 0x88, 0x20, 0x7a, 0x2d, 0xec, 0xa3, 0xbc, + 0xec, 0x86, 0x8c, 0x20, 0x28, 0xec, 0xb0, 0xa8, 0xed, 0x8f, 0x90, 0x29, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, + 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x83, 0x88, 0x20, 0x74, 0x2d, 0xec, + 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x20, 0x28, 0xed, 0x88, 0xac, 0xeb, 0xaa, + 0x85, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x20, + 0xec, 0x83, 0x81, 0xec, 0x84, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, 0x65, 0x78, + 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x83, + 0x90, 0xec, 0x83, 0x89, 0xea, 0xb8, 0xb0, 0xec, 0x97, 0x90, 0xec, 0x84, + 0x9c, 0x20, 0xeb, 0xb3, 0xb4, 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x51, 0x52, 0x20, 0xec, 0xbd, 0x94, 0xeb, 0x93, 0x9c, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xea, 0xb2, 0xb0, 0xec, 0xa0, 0x9c, 0x20, 0xec, 0x9a, + 0x94, 0xec, 0xb2, 0xad, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x82, 0xa0, + 0xec, 0xa7, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x83, 0x81, + 0xed, 0x83, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xed, 0x99, 0x95, 0xec, 0x9d, 0xb8, 0x20, 0xec, + 0x88, 0x98, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xed, + 0x99, 0x95, 0xec, 0x9d, 0xb8, 0xeb, 0x90, 0xa8, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0xeb, 0x8c, 0x80, 0xea, 0xb8, 0xb0, 0x20, 0xec, 0xa4, + 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb3, 0xb4, 0xeb, 0x83, 0x84, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, + 0x76, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb0, 0x9b, 0xec, 0x9d, + 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, 0xb4, + 0xeb, 0x90, 0xa8, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, 0xb4, + 0x20, 0xec, 0xa0, 0x9c, 0xec, 0x96, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, + 0xb4, 0x20, 0xec, 0x8b, 0x9c, 0xec, 0x9e, 0x91, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, + 0xb4, 0x20, 0xec, 0xa4, 0x91, 0xec, 0xa7, 0x80, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, + 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, + 0x84, 0xea, 0xb5, 0xb4, 0x20, 0xec, 0x8a, 0xa4, 0xeb, 0xa0, 0x88, 0xeb, + 0x93, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, + 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, + 0x69, 0x63, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, + 0xb4, 0x20, 0xed, 0x86, 0xb5, 0xea, 0xb3, 0x84, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, + 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xa1, + 0x9c, 0xec, 0xbb, 0xac, 0x20, 0xed, 0x95, 0xb4, 0xec, 0x8b, 0x9c, 0xeb, + 0xa0, 0x88, 0xec, 0x9d, 0xb4, 0xed, 0x8a, 0xb8, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, + 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xeb, 0x84, 0xa4, 0xed, 0x8a, 0xb8, 0xec, 0x9b, 0x8c, 0xed, 0x81, 0xac, + 0x20, 0xed, 0x95, 0xb4, 0xec, 0x8b, 0x9c, 0xeb, 0xa0, 0x88, 0xec, 0x9d, + 0xb4, 0xed, 0x8a, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x79, 0x22, 0x3a, + 0x20, 0x22, 0xeb, 0x82, 0x9c, 0xec, 0x9d, 0xb4, 0xeb, 0x8f, 0x84, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x73, 0x74, 0x5f, 0x74, + 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x22, 0x3a, 0x20, 0x22, 0xec, 0x98, 0x88, 0xec, 0x83, 0x81, 0x20, 0xeb, + 0xb8, 0x94, 0xeb, 0xa1, 0x9d, 0x20, 0xeb, 0xb0, 0x9c, 0xea, 0xb2, 0xac, + 0x20, 0xec, 0x8b, 0x9c, 0xea, 0xb0, 0x84, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, + 0x66, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, 0xb4, 0x20, + 0xea, 0xba, 0xbc, 0xec, 0xa7, 0x90, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x6e, 0x22, + 0x3a, 0x20, 0x22, 0xec, 0xb1, 0x84, 0xea, 0xb5, 0xb4, 0x20, 0xec, 0xbc, + 0x9c, 0xec, 0xa7, 0x90, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x97, 0xb0, 0xea, + 0xb2, 0xb0, 0xeb, 0x90, 0x9c, 0x20, 0xeb, 0x85, 0xb8, 0xeb, 0x93, 0x9c, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, + 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xec, 0xb0, 0xa8, 0xeb, 0x8b, 0xa8, 0xeb, 0x90, 0x9c, 0x20, 0xeb, 0x85, + 0xb8, 0xeb, 0x93, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x49, 0x50, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, 0x8c, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb2, 0x84, 0xec, 0xa0, 0x84, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb8, 0x94, 0xeb, 0xa1, 0x9d, + 0x20, 0xeb, 0x86, 0x92, 0xec, 0x9d, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xed, + 0x95, 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb0, 0xa8, 0xeb, 0x8b, 0xa8, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, 0x61, 0x6e, + 0x22, 0x3a, 0x20, 0x22, 0xec, 0xb0, 0xa8, 0xeb, 0x8b, 0xa8, 0x20, 0xed, + 0x95, 0xb4, 0xec, 0xa0, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, 0x5f, 0x62, + 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xaa, 0xa8, 0xeb, 0x93, + 0xa0, 0x20, 0xec, 0xb0, 0xa8, 0xeb, 0x8b, 0xa8, 0x20, 0xed, 0x95, 0xb4, + 0xec, 0xa0, 0x9c, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x72, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xea, 0xb0, 0x80, 0xea, 0xb2, 0xa9, 0x20, 0xec, 0xb0, + 0xa8, 0xed, 0x8a, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x63, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x98, 0x84, 0xec, 0x9e, 0xac, 0x20, + 0xea, 0xb0, 0x80, 0xea, 0xb2, 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0xec, 0x8b, 0x9c, 0xea, 0xb0, 0x84, + 0x20, 0xeb, 0xb3, 0x80, 0xeb, 0x8f, 0x99, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0xec, 0x8b, 0x9c, 0xea, 0xb0, + 0x84, 0x20, 0xea, 0xb1, 0xb0, 0xeb, 0x9e, 0x98, 0xeb, 0x9f, 0x89, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, + 0x74, 0x5f, 0x63, 0x61, 0x70, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x8b, 0x9c, + 0xea, 0xb0, 0x80, 0xec, 0xb4, 0x9d, 0xec, 0x95, 0xa1, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, + 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x9d, 0xbc, 0xeb, 0xb0, 0x98, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, 0x70, 0x6c, + 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xed, 0x99, 0x94, 0xeb, 0xa9, 0xb4, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, + 0x6f, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x84, 0xa4, 0xed, 0x8a, + 0xb8, 0xec, 0x9b, 0x8c, 0xed, 0x81, 0xac, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xed, 0x85, 0x8c, 0xeb, 0xa7, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0x96, 0xb8, 0xec, 0x96, 0xb4, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x5f, + 0x67, 0x72, 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x61, + 0x67, 0x6f, 0x6e, 0x58, 0x20, 0x28, 0xeb, 0x85, 0xb9, 0xec, 0x83, 0x89, + 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x72, + 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x8b, 0xa4, 0xed, 0x81, 0xac, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x9d, 0xbc, 0xec, 0x9d, 0xb4, 0xed, 0x8a, + 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6c, 0x6c, + 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x66, 0x65, + 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x82, 0xac, 0xec, 0x9a, 0xa9, + 0xec, 0x9e, 0x90, 0x20, 0xec, 0x88, 0x98, 0xec, 0x88, 0x98, 0xeb, 0xa3, + 0x8c, 0x20, 0xed, 0x97, 0x88, 0xec, 0x9a, 0xa9, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, + 0x64, 0x64, 0x65, 0x64, 0x5f, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, + 0x3a, 0x20, 0x22, 0xeb, 0x82, 0xb4, 0xec, 0x9e, 0xa5, 0x20, 0x64, 0x72, + 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x20, 0xec, 0x82, 0xac, 0xec, 0x9a, + 0xa9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa0, 0x80, 0xec, 0x9e, 0xa5, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x8b, 0xab, 0xea, 0xb8, 0xb0, 0x22, 0x2c, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0xed, 0x8c, 0x8c, 0xec, 0x9d, 0xbc, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xed, 0x8e, 0xb8, 0xec, 0xa7, 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x22, 0x3a, 0x20, 0x22, 0xeb, + 0xb3, 0xb4, 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x68, 0x65, 0x6c, 0x70, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x8f, 0x84, + 0xec, 0x9b, 0x80, 0xeb, 0xa7, 0x90, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, + 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, + 0xea, 0xb0, 0x9c, 0xec, 0x9d, 0xb8, 0xed, 0x82, 0xa4, 0x20, 0xea, 0xb0, + 0x80, 0xec, 0xa0, 0xb8, 0xec, 0x98, 0xa4, 0xea, 0xb8, 0xb0, 0x2e, 0x2e, + 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, + 0x6b, 0x75, 0x70, 0x5f, 0x77, 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0xa7, 0x80, 0xea, 0xb0, 0x91, 0x20, 0xeb, 0xb0, 0xb1, + 0xec, 0x97, 0x85, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xec, 0xa2, + 0x85, 0xeb, 0xa3, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x61, 0x62, 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x78, 0x22, 0x3a, 0x20, 0x22, 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, + 0x6e, 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x20, 0xec, 0xa0, 0x95, 0xeb, + 0xb3, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, + 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, 0x77, 0x22, 0x3a, 0x20, + 0x22, 0xec, 0xa7, 0x80, 0xea, 0xb8, 0x88, 0x20, 0xec, 0x83, 0x88, 0xeb, + 0xa1, 0x9c, 0xea, 0xb3, 0xa0, 0xec, 0xb9, 0xa8, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0xa0, 0x95, 0xeb, 0xb3, 0xb4, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xea, 0xb0, 0x80, 0xec, 0xa0, 0xb8, 0xec, 0x98, 0xa4, 0xea, + 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, + 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0x82, 0xb4, 0xeb, + 0xb3, 0xb4, 0xeb, 0x82, 0xb4, 0xea, 0xb8, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, + 0x63, 0x6c, 0x69, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0xed, 0x81, 0xb4, 0xeb, 0xa6, 0xbd, 0xeb, 0xb3, 0xb4, 0xeb, 0x93, + 0x9c, 0xec, 0x97, 0x90, 0x20, 0xeb, 0xb3, 0xb5, 0xec, 0x82, 0xac, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x97, 0xb0, + 0xea, 0xb2, 0xb0, 0xeb, 0x90, 0xa8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x97, 0xb0, 0xea, 0xb2, 0xb0, + 0x20, 0xeb, 0x81, 0x8a, 0xea, 0xb9, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xec, 0x97, 0xb0, 0xea, 0xb2, 0xb0, 0x20, + 0xec, 0xa4, 0x91, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0xeb, 0x8f, 0x99, 0xea, 0xb8, 0xb0, 0xed, 0x99, 0x94, 0x20, 0xec, + 0xa4, 0x91, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xeb, 0xb8, + 0x94, 0xeb, 0xa1, 0x9d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, + 0x5f, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0x82, 0xac, 0xec, 0x9a, 0xa9, 0x20, 0xea, 0xb0, 0x80, + 0xeb, 0x8a, 0xa5, 0xed, 0x95, 0x9c, 0x20, 0xec, 0xa3, 0xbc, 0xec, 0x86, + 0x8c, 0x20, 0xec, 0x97, 0x86, 0xec, 0x9d, 0x8c, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, + 0x20, 0x22, 0xec, 0x98, 0xa4, 0xeb, 0xa5, 0x98, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xec, 0x84, 0xb1, 0xea, 0xb3, 0xb5, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0xea, 0xb2, 0xbd, 0xea, 0xb3, 0xa0, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, + 0x5f, 0x65, 0x78, 0x63, 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, + 0x61, 0x6e, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xea, 0xb8, 0x88, 0xec, + 0x95, 0xa1, 0xec, 0x9d, 0xb4, 0x20, 0xec, 0x9e, 0x94, 0xec, 0x95, 0xa1, + 0xec, 0x9d, 0x84, 0x20, 0xec, 0xb4, 0x88, 0xea, 0xb3, 0xbc, 0xed, 0x95, + 0xa9, 0xeb, 0x8b, 0x88, 0xeb, 0x8b, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xea, + 0xb1, 0xb0, 0xeb, 0x9e, 0x98, 0xea, 0xb0, 0x80, 0x20, 0xec, 0x84, 0xb1, + 0xea, 0xb3, 0xb5, 0xec, 0xa0, 0x81, 0xec, 0x9c, 0xbc, 0xeb, 0xa1, 0x9c, + 0x20, 0xec, 0xa0, 0x84, 0xec, 0x86, 0xa1, 0xeb, 0x90, 0x98, 0xec, 0x97, + 0x88, 0xec, 0x8a, 0xb5, 0xeb, 0x8b, 0x88, 0xeb, 0x8b, 0xa4, 0x22, 0x0a, + 0x7d, 0x0a +}; +unsigned int res_lang_ko_json_len = 4502; diff --git a/src/embedded/lang_pt.h b/src/embedded/lang_pt.h new file mode 100644 index 0000000..fbacdd0 --- /dev/null +++ b/src/embedded/lang_pt.h @@ -0,0 +1,382 @@ +unsigned char res_lang_pt_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x61, 0x6c, 0x64, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x63, 0x65, 0x62, 0x65, 0x72, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0xc3, 0xa7, 0xc3, 0xb5, 0x65, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0x61, 0xc3, + 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc3, 0xb3, + 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, + 0x6b, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x65, 0x72, 0x63, 0x61, + 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0xc3, 0xa7, 0xc3, 0xb5, 0x65, + 0x73, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x73, + 0x75, 0x6d, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x50, + 0x72, 0x6f, 0x74, 0x65, 0x67, 0x69, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x75, 0x6e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc3, 0xa3, 0x6f, 0x20, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x65, 0x75, + 0x73, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x73, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x7a, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x73, 0x2d, 0x5a, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, + 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x73, 0x2d, 0x54, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x65, + 0x6e, 0x68, 0x75, 0x6d, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, + 0xa7, 0x6f, 0x20, 0x65, 0x6e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x64, + 0x6f, 0x2e, 0x20, 0x43, 0x72, 0x69, 0x65, 0x20, 0x75, 0x6d, 0x20, 0x75, + 0x73, 0x61, 0x6e, 0x64, 0x6f, 0x20, 0x6f, 0x73, 0x20, 0x62, 0x6f, 0x74, + 0xc3, 0xb5, 0x65, 0x73, 0x20, 0x61, 0x63, 0x69, 0x6d, 0x61, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x6f, 0x76, 0x6f, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, + 0xa7, 0x6f, 0x2d, 0x5a, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, 0x76, 0x6f, 0x20, 0x65, 0x6e, + 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x2d, 0x54, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x54, 0x69, 0x70, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x70, + 0x69, 0x61, 0x72, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, + 0x6f, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x74, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, + 0x72, 0x6f, 0x6d, 0x5f, 0x74, 0x68, 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, + 0x61, 0x72, 0x20, 0x64, 0x65, 0x73, 0x74, 0x65, 0x20, 0x65, 0x6e, 0x64, + 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, + 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, + 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, 0x20, 0x63, 0x68, 0x61, + 0x76, 0x65, 0x20, 0x70, 0x72, 0x69, 0x76, 0x61, 0x64, 0x61, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, + 0x5f, 0x76, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, 0x65, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, + 0x20, 0x63, 0x68, 0x61, 0x76, 0x65, 0x20, 0x64, 0x65, 0x20, 0x76, 0x69, + 0x73, 0x75, 0x61, 0x6c, 0x69, 0x7a, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x6f, 0x77, + 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x4d, 0x6f, 0x73, 0x74, 0x72, 0x61, 0x72, 0x20, 0x63, 0xc3, 0xb3, 0x64, + 0x69, 0x67, 0x6f, 0x20, 0x51, 0x52, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc3, 0xa3, 0x6f, 0x20, + 0x63, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x20, 0x61, 0x6f, + 0x20, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x79, 0x5f, 0x66, + 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x61, 0x67, 0x61, 0x72, + 0x20, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, + 0x76, 0x69, 0x61, 0x72, 0x20, 0x70, 0x61, 0x72, 0x61, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0x56, 0x61, 0x6c, 0x6f, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, 0x20, 0x22, + 0x4d, 0x65, 0x6d, 0x6f, 0x20, 0x28, 0x6f, 0x70, 0x63, 0x69, 0x6f, 0x6e, + 0x61, 0x6c, 0x2c, 0x20, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x67, 0x72, + 0x61, 0x66, 0x61, 0x64, 0x6f, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, + 0x3a, 0x20, 0x22, 0x54, 0x61, 0x78, 0x61, 0x20, 0x64, 0x6f, 0x20, 0x6d, + 0x69, 0x6e, 0x65, 0x72, 0x61, 0x64, 0x6f, 0x72, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, + 0x61, 0x78, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, + 0x72, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, + 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, + 0x61, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x4c, 0x69, 0x6d, 0x70, 0x61, 0x72, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6c, 0x65, + 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x69, 0x6f, 0x6e, 0x61, 0x72, + 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x2e, 0x2e, + 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x73, + 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6c, 0x61, 0x72, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, 0x3a, + 0x20, 0x22, 0x4d, 0xc3, 0xa1, 0x78, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x44, 0x69, 0x73, 0x70, 0x6f, 0x6e, 0xc3, 0xad, + 0x76, 0x65, 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, + 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x6f, 0x20, 0x64, 0x65, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, + 0xa7, 0x6f, 0x20, 0x69, 0x6e, 0x76, 0xc3, 0xa1, 0x6c, 0x69, 0x64, 0x6f, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, + 0x5f, 0x7a, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0x6f, 0x74, 0x61, 0x3a, 0x20, 0x6d, 0x65, 0x6d, 0x6f, 0x73, 0x20, 0x73, + 0xc3, 0xb3, 0x20, 0x65, 0x73, 0x74, 0xc3, 0xa3, 0x6f, 0x20, 0x64, 0x69, + 0x73, 0x70, 0x6f, 0x6e, 0xc3, 0xad, 0x76, 0x65, 0x69, 0x73, 0x20, 0x61, + 0x6f, 0x20, 0x65, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x20, 0x70, 0x61, 0x72, + 0x61, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x73, + 0x20, 0x70, 0x72, 0x6f, 0x74, 0x65, 0x67, 0x69, 0x64, 0x6f, 0x73, 0x20, + 0x28, 0x7a, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x63, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x65, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, + 0x3a, 0x20, 0x22, 0x44, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x61, 0x72, 0x61, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x76, 0x69, 0x61, 0x6e, + 0x64, 0x6f, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0xc3, 0xa7, 0xc3, + 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0x20, + 0x65, 0x6e, 0x76, 0x69, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0x20, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, + 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0x20, 0x65, + 0x20, 0x65, 0x6e, 0x76, 0x69, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x22, 0x3a, 0x20, + 0x22, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x61, 0x72, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, + 0x69, 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x65, 0x75, 0x73, 0x20, 0x65, 0x6e, + 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x73, 0x20, 0x64, 0x65, 0x20, + 0x72, 0x65, 0x63, 0x65, 0x62, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, + 0x5f, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, + 0x22, 0x4e, 0x6f, 0x76, 0x6f, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, + 0xc3, 0xa7, 0x6f, 0x2d, 0x7a, 0x20, 0x28, 0x70, 0x72, 0x6f, 0x74, 0x65, + 0x67, 0x69, 0x64, 0x6f, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0x6f, + 0x76, 0x6f, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, + 0x2d, 0x74, 0x20, 0x28, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x65, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, + 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, 0x74, 0x61, + 0x6c, 0x68, 0x65, 0x73, 0x20, 0x64, 0x6f, 0x20, 0x65, 0x6e, 0x64, 0x65, + 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, 0x65, 0x78, 0x70, + 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x56, 0x65, 0x72, + 0x20, 0x6e, 0x6f, 0x20, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x61, 0x64, + 0x6f, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x71, 0x72, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x43, 0xc3, 0xb3, + 0x64, 0x69, 0x67, 0x6f, 0x20, 0x51, 0x52, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x70, + 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x6f, + 0x6c, 0x69, 0x63, 0x69, 0x74, 0x61, 0x72, 0x20, 0x70, 0x61, 0x67, 0x61, + 0x6d, 0x65, 0x6e, 0x74, 0x6f, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x61, + 0x74, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0xc3, + 0xa7, 0xc3, 0xb5, 0x65, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, + 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x64, 0x61, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x6e, 0x64, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x65, 0x6e, 0x64, 0x65, + 0x6e, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x65, 0x6e, 0x76, 0x69, 0x61, + 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, + 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x72, 0x65, + 0x63, 0x65, 0x62, 0x69, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x65, 0x72, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x65, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, + 0x6e, 0x65, 0x72, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6e, 0x69, + 0x63, 0x69, 0x61, 0x72, 0x20, 0x6d, 0x69, 0x6e, 0x65, 0x72, 0x61, 0xc3, + 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0x50, 0x61, 0x72, 0x61, 0x72, 0x20, 0x6d, 0x69, 0x6e, + 0x65, 0x72, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, + 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x68, + 0x72, 0x65, 0x61, 0x64, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, 0x6e, + 0x65, 0x72, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x73, + 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x73, 0x74, 0x61, 0x74, 0xc3, 0xad, 0x73, 0x74, 0x69, 0x63, + 0x61, 0x73, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x69, 0x6e, 0x65, 0x72, 0x61, + 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, + 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x48, 0x61, 0x73, 0x68, 0x72, + 0x61, 0x74, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, + 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x48, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x20, 0x64, 0x61, + 0x20, 0x72, 0x65, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x79, 0x22, + 0x3a, 0x20, 0x22, 0x44, 0x69, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x64, 0x61, + 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x73, + 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x65, 0x6d, 0x70, 0x6f, + 0x20, 0x65, 0x73, 0x74, 0x2e, 0x20, 0x61, 0x74, 0xc3, 0xa9, 0x20, 0x6f, + 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x66, 0x66, + 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, 0x6e, 0x65, 0x72, 0x61, 0xc3, 0xa7, + 0xc3, 0xa3, 0x6f, 0x20, 0x44, 0x45, 0x53, 0x4c, 0x49, 0x47, 0x41, 0x44, + 0x41, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, + 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x4d, 0x69, + 0x6e, 0x65, 0x72, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x20, 0x4c, 0x49, + 0x47, 0x41, 0x44, 0x41, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, 0xc3, 0xb3, 0x73, + 0x20, 0x63, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, 0x65, + 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x4e, + 0xc3, 0xb3, 0x73, 0x20, 0x62, 0x61, 0x6e, 0x69, 0x64, 0x6f, 0x73, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x70, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x6e, 0x64, + 0x65, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x20, 0x49, 0x50, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x22, 0x3a, 0x20, 0x22, 0x56, 0x65, 0x72, 0x73, 0xc3, 0xa3, 0x6f, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6c, 0x74, 0x75, 0x72, 0x61, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0x50, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x61, + 0x6e, 0x69, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, + 0x6e, 0x62, 0x61, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, 0x73, 0x62, + 0x61, 0x6e, 0x69, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, 0x6c, 0x6c, 0x5f, 0x62, 0x61, + 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, + 0x72, 0x20, 0x74, 0x6f, 0x64, 0x6f, 0x73, 0x20, 0x6f, 0x73, 0x20, 0x62, + 0x61, 0x6e, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x6f, 0x73, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, + 0x63, 0x68, 0x61, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x72, 0xc3, + 0xa1, 0x66, 0x69, 0x63, 0x6f, 0x20, 0x64, 0x65, 0x20, 0x70, 0x72, 0x65, + 0xc3, 0xa7, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x50, 0x72, 0x65, 0xc3, 0xa7, 0x6f, 0x20, 0x61, + 0x74, 0x75, 0x61, 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x56, 0x61, 0x72, 0x69, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, + 0x20, 0x32, 0x34, 0x68, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x32, 0x34, 0x68, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x20, 0x32, 0x34, 0x68, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, + 0x65, 0x74, 0x5f, 0x63, 0x61, 0x70, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x61, + 0x70, 0x2e, 0x20, 0x64, 0x65, 0x20, 0x6d, 0x65, 0x72, 0x63, 0x61, 0x64, + 0x6f, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, + 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0x47, 0x65, 0x72, + 0x61, 0x6c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, + 0x73, 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x69, + 0x62, 0x69, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, + 0x20, 0x22, 0x52, 0x65, 0x64, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x54, + 0x65, 0x6d, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, + 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x49, + 0x64, 0x69, 0x6f, 0x6d, 0x61, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x5f, 0x67, 0x72, 0x65, + 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x58, 0x20, 0x28, 0x56, 0x65, 0x72, 0x64, 0x65, 0x29, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x72, 0x6b, 0x22, 0x3a, 0x20, + 0x22, 0x45, 0x73, 0x63, 0x75, 0x72, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0x43, 0x6c, 0x61, 0x72, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, + 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x50, 0x65, + 0x72, 0x6d, 0x69, 0x74, 0x69, 0x72, 0x20, 0x74, 0x61, 0x78, 0x61, 0x73, + 0x20, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x61, 0x6c, 0x69, 0x7a, 0x61, + 0x64, 0x61, 0x73, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, + 0x73, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x5f, + 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x55, 0x73, + 0x61, 0x72, 0x20, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x20, + 0x65, 0x6d, 0x62, 0x75, 0x74, 0x69, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x53, 0x61, 0x6c, 0x76, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x46, + 0x65, 0x63, 0x68, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x72, + 0x71, 0x75, 0x69, 0x76, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x65, 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x64, 0x69, + 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, + 0x69, 0x65, 0x77, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x78, 0x69, 0x62, 0x69, + 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x6c, + 0x70, 0x22, 0x3a, 0x20, 0x22, 0x41, 0x6a, 0x75, 0x64, 0x61, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, + 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, + 0x20, 0x63, 0x68, 0x61, 0x76, 0x65, 0x20, 0x70, 0x72, 0x69, 0x76, 0x61, + 0x64, 0x61, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x5f, 0x77, 0x61, 0x6c, 0x6c, + 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x46, 0x61, 0x7a, 0x65, 0x72, 0x20, + 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x20, 0x64, 0x61, 0x20, 0x63, 0x61, + 0x72, 0x74, 0x65, 0x69, 0x72, 0x61, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0x53, 0x61, 0x69, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, + 0x6e, 0x78, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x6f, 0x62, 0x72, 0x65, 0x20, + 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, 0x6e, 0x44, 0x72, 0x61, 0x67, + 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, + 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, 0x77, 0x22, 0x3a, 0x20, + 0x22, 0x41, 0x74, 0x75, 0x61, 0x6c, 0x69, 0x7a, 0x61, 0x72, 0x20, 0x61, + 0x67, 0x6f, 0x72, 0x61, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x6f, + 0x62, 0x72, 0x65, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, + 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x45, + 0x78, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x72, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, 0x63, + 0x6c, 0x69, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0x43, 0x6f, 0x70, 0x69, 0x61, 0x72, 0x20, 0x70, 0x61, 0x72, 0x61, 0x20, + 0xc3, 0xa1, 0x72, 0x65, 0x61, 0x20, 0x64, 0x65, 0x20, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x66, 0x65, 0x72, 0xc3, 0xaa, 0x6e, 0x63, 0x69, 0x61, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, + 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x65, 0x73, 0x63, 0x6f, 0x6e, + 0x65, 0x63, 0x74, 0x61, 0x64, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x61, 0x6e, + 0x64, 0x6f, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, + 0x53, 0x69, 0x6e, 0x63, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x6e, 0x64, + 0x6f, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0x42, 0x6c, 0x6f, + 0x63, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, + 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, 0x61, + 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0x4e, 0x65, 0x6e, 0x68, 0x75, 0x6d, 0x20, 0x65, 0x6e, 0x64, 0x65, 0x72, + 0x65, 0xc3, 0xa7, 0x6f, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6f, 0x6e, 0xc3, + 0xad, 0x76, 0x65, 0x6c, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x22, 0x45, 0x72, + 0x72, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, + 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x53, 0x75, 0x63, + 0x65, 0x73, 0x73, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0x41, + 0x76, 0x69, 0x73, 0x6f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x65, 0x78, 0x63, 0x65, 0x65, + 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x56, 0x61, 0x6c, 0x6f, 0x72, 0x20, 0x65, 0x78, 0x63, 0x65, + 0x64, 0x65, 0x20, 0x6f, 0x20, 0x73, 0x61, 0x6c, 0x64, 0x6f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0xc3, 0xa7, 0xc3, 0xa3, + 0x6f, 0x20, 0x65, 0x6e, 0x76, 0x69, 0x61, 0x64, 0x61, 0x20, 0x63, 0x6f, + 0x6d, 0x20, 0x73, 0x75, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x22, 0x0a, 0x7d, + 0x0a +}; +unsigned int res_lang_pt_json_len = 4537; diff --git a/src/embedded/lang_ru.h b/src/embedded/lang_ru.h new file mode 100644 index 0000000..58acecf --- /dev/null +++ b/src/embedded/lang_ru.h @@ -0,0 +1,502 @@ +unsigned char res_lang_ru_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x91, 0xd0, 0xb0, 0xd0, 0xbb, + 0xd0, 0xb0, 0xd0, 0xbd, 0xd1, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, + 0xd1, 0x82, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xb8, + 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9f, 0xd0, 0xbe, 0xd0, 0xbb, 0xd1, 0x83, 0xd1, 0x87, 0xd0, 0xb8, 0xd1, + 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0xa2, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, + 0xb7, 0xd0, 0xb0, 0xd0, 0xba, 0xd1, 0x86, 0xd0, 0xb8, 0xd0, 0xb8, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9c, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, + 0xbd, 0xd0, 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xd0, 0xa3, 0xd0, 0xb7, 0xd0, 0xbb, 0xd1, 0x8b, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0xa0, 0xd1, 0x8b, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xba, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x74, 0x74, + 0x69, 0x6e, 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xb0, + 0xd1, 0x81, 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb9, 0xd0, 0xba, + 0xd0, 0xb8, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, + 0xd0, 0xb2, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xba, 0xd0, 0xb0, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, + 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x97, 0xd0, 0xb0, 0xd1, 0x89, + 0xd0, 0xb8, 0xd1, 0x89, 0xd1, 0x91, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, + 0xd0, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb7, 0xd1, 0x80, 0xd0, + 0xb0, 0xd1, 0x87, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x98, 0xd1, 0x82, 0xd0, 0xbe, 0xd0, 0xb3, 0xd0, 0xbe, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9d, 0xd0, 0xb5, 0xd0, 0xbf, 0xd0, 0xbe, 0xd0, 0xb4, 0xd1, 0x82, 0xd0, + 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb6, 0xd0, 0xb4, 0xd1, 0x91, 0xd0, + 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x79, 0x6f, 0x75, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd0, + 0xb0, 0xd1, 0x88, 0xd0, 0xb8, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, + 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x7a, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x5a, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, + 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x54, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, + 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x90, 0xd0, 0xb4, + 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x20, 0xd0, 0xbd, 0xd0, + 0xb5, 0x20, 0xd0, 0xbd, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xb4, 0xd0, 0xb5, + 0xd0, 0xbd, 0xd1, 0x8b, 0x2e, 0x20, 0xd0, 0xa1, 0xd0, 0xbe, 0xd0, 0xb7, + 0xd0, 0xb4, 0xd0, 0xb0, 0xd0, 0xb9, 0xd1, 0x82, 0xd0, 0xb5, 0x20, 0xd0, + 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0x20, 0xd1, 0x81, + 0x20, 0xd0, 0xbf, 0xd0, 0xbe, 0xd0, 0xbc, 0xd0, 0xbe, 0xd1, 0x89, 0xd1, + 0x8c, 0xd1, 0x8e, 0x20, 0xd0, 0xba, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xbf, + 0xd0, 0xbe, 0xd0, 0xba, 0x20, 0xd0, 0xb2, 0xd1, 0x8b, 0xd1, 0x88, 0xd0, + 0xb5, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x7a, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xbe, 0xd0, 0xb2, 0xd1, 0x8b, 0xd0, + 0xb9, 0x20, 0x5a, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, + 0xd1, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xbe, 0xd0, 0xb2, 0xd1, 0x8b, 0xd0, + 0xb9, 0x20, 0x54, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, + 0xd1, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x79, + 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa2, 0xd0, 0xb8, 0xd0, 0xbf, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x90, 0xd0, 0xb4, 0xd1, + 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9a, 0xd0, 0xbe, 0xd0, 0xbf, 0xd0, + 0xb8, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd1, 0x82, 0xd1, + 0x8c, 0x20, 0xd0, 0xbf, 0xd0, 0xbe, 0xd0, 0xbb, 0xd0, 0xbd, 0xd1, 0x8b, + 0xd0, 0xb9, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, + 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x74, 0x68, 0x69, 0x73, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9e, 0xd1, 0x82, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, + 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd1, 0x81, 0x20, 0xd1, 0x8d, 0xd1, + 0x82, 0xd0, 0xbe, 0xd0, 0xb3, 0xd0, 0xbe, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, + 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, + 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0xad, 0xd0, 0xba, 0xd1, 0x81, 0xd0, 0xbf, 0xd0, 0xbe, + 0xd1, 0x80, 0xd1, 0x82, 0x20, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, + 0xb2, 0xd0, 0xb0, 0xd1, 0x82, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xb3, 0xd0, + 0xbe, 0x20, 0xd0, 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, 0x87, 0xd0, 0xb0, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, + 0x72, 0x74, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, + 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xad, 0xd0, 0xba, 0xd1, 0x81, + 0xd0, 0xbf, 0xd0, 0xbe, 0xd1, 0x80, 0xd1, 0x82, 0x20, 0xd0, 0xba, 0xd0, + 0xbb, 0xd1, 0x8e, 0xd1, 0x87, 0xd0, 0xb0, 0x20, 0xd0, 0xbf, 0xd1, 0x80, + 0xd0, 0xbe, 0xd1, 0x81, 0xd0, 0xbc, 0xd0, 0xbe, 0xd1, 0x82, 0xd1, 0x80, + 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, + 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb0, 0xd0, 0xb7, + 0xd0, 0xb0, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0x51, 0x52, 0x2d, 0xd0, 0xba, + 0xd0, 0xbe, 0xd0, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xb5, 0x20, 0xd0, 0xbf, + 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, 0x87, + 0xd1, 0x91, 0xd0, 0xbd, 0x20, 0xd0, 0xba, 0x20, 0xd0, 0xb4, 0xd0, 0xb5, + 0xd0, 0xbc, 0xd0, 0xbe, 0xd0, 0xbd, 0xd1, 0x83, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x79, 0x5f, + 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd0, 0xbf, + 0xd0, 0xbb, 0xd0, 0xb0, 0xd1, 0x82, 0xd0, 0xb0, 0x20, 0xd1, 0x81, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, + 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd1, 0x82, 0xd0, 0xbf, + 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, + 0x20, 0xd0, 0xbd, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0xa1, 0xd1, 0x83, 0xd0, 0xbc, 0xd0, 0xbc, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, 0xbc, 0xd0, 0xb5, 0xd1, + 0x87, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x20, 0x28, 0xd0, + 0xbd, 0xd0, 0xb5, 0xd0, 0xbe, 0xd0, 0xb1, 0xd1, 0x8f, 0xd0, 0xb7, 0xd0, + 0xb0, 0xd1, 0x82, 0xd0, 0xb5, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xbd, 0xd0, + 0xbe, 0x2c, 0x20, 0xd0, 0xb7, 0xd0, 0xb0, 0xd1, 0x88, 0xd0, 0xb8, 0xd1, + 0x84, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, + 0xbe, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, + 0x6e, 0x65, 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9a, 0xd0, 0xbe, 0xd0, 0xbc, 0xd0, 0xb8, 0xd1, 0x81, 0xd1, 0x81, 0xd0, + 0xb8, 0xd1, 0x8f, 0x20, 0xd0, 0xbc, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, + 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9a, 0xd0, + 0xbe, 0xd0, 0xbc, 0xd0, 0xb8, 0xd1, 0x81, 0xd1, 0x81, 0xd0, 0xb8, 0xd1, + 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, + 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd1, 0x82, 0xd0, 0xbf, 0xd1, + 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x20, + 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xb7, 0xd0, 0xb0, + 0xd0, 0xba, 0xd1, 0x86, 0xd0, 0xb8, 0xd1, 0x8e, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9e, 0xd1, 0x87, 0xd0, 0xb8, 0xd1, 0x81, 0xd1, 0x82, 0xd0, + 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd1, 0x8b, 0xd0, + 0xb1, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb8, 0xd1, 0x82, 0xd0, 0xb5, 0x20, + 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0x2e, 0x2e, + 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x73, + 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd1, 0x81, 0xd1, 0x82, + 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9c, 0xd0, 0xb0, 0xd0, 0xba, 0xd1, 0x81, 0x2e, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x94, 0xd0, 0xbe, 0xd1, + 0x81, 0xd1, 0x82, 0xd1, 0x83, 0xd0, 0xbf, 0xd0, 0xbd, 0xd0, 0xbe, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, + 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xb5, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, + 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x20, 0xd1, 0x84, 0xd0, 0xbe, 0xd1, + 0x80, 0xd0, 0xbc, 0xd0, 0xb0, 0xd1, 0x82, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, + 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x5f, 0x7a, 0x5f, 0x6f, + 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd1, 0x80, 0xd0, + 0xb8, 0xd0, 0xbc, 0xd0, 0xb5, 0xd1, 0x87, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, + 0xb8, 0xd1, 0x8f, 0x20, 0xd0, 0xb4, 0xd0, 0xbe, 0xd1, 0x81, 0xd1, 0x82, + 0xd1, 0x83, 0xd0, 0xbf, 0xd0, 0xbd, 0xd1, 0x8b, 0x20, 0xd1, 0x82, 0xd0, + 0xbe, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xba, 0xd0, 0xbe, 0x20, 0xd0, 0xbf, + 0xd1, 0x80, 0xd0, 0xb8, 0x20, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, 0xbf, 0xd1, + 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xba, 0xd0, 0xb5, 0x20, 0xd0, 0xbd, + 0xd0, 0xb0, 0x20, 0xd0, 0xb7, 0xd0, 0xb0, 0xd1, 0x89, 0xd0, 0xb8, 0xd1, + 0x89, 0xd1, 0x91, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb5, 0x20, + 0x28, 0x7a, 0x29, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, + 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xd1, 0x81, 0xd0, 0xb8, 0xd0, 0xbc, 0xd0, 0xb2, 0xd0, 0xbe, + 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xb2, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, + 0xd1, 0x82, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9a, 0xd0, 0xbe, 0xd0, 0xbc, 0xd1, 0x83, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd1, 0x82, 0xd0, + 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xba, 0xd0, 0xb0, 0x20, + 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xb7, 0xd0, 0xb0, + 0xd0, 0xba, 0xd1, 0x86, 0xd0, 0xb8, 0xd0, 0xb8, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, + 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, + 0xd0, 0xb4, 0xd1, 0x82, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb4, + 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, + 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xba, 0xd1, 0x83, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x72, 0x6d, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, + 0xd1, 0x82, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb4, 0xd0, 0xb8, + 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, + 0xbd, 0xd0, 0xb7, 0xd0, 0xb0, 0xd0, 0xba, 0xd1, 0x86, 0xd0, 0xb8, 0xd1, + 0x8e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x73, 0x65, 0x6e, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd1, + 0x82, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb4, 0xd0, 0xb8, 0xd1, + 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xb8, 0x20, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, + 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, + 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, + 0x63, 0x65, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd1, 0x82, 0xd0, + 0xbc, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x69, 0x6e, + 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd0, 0xb0, 0xd1, 0x88, 0xd0, 0xb8, 0x20, + 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, + 0x20, 0xd0, 0xb4, 0xd0, 0xbb, 0xd1, 0x8f, 0x20, 0xd0, 0xbf, 0xd0, 0xbe, + 0xd0, 0xbb, 0xd1, 0x83, 0xd1, 0x87, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, + 0xd1, 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x7a, 0x5f, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xbe, 0xd0, 0xb2, 0xd1, 0x8b, + 0xd0, 0xb9, 0x20, 0x7a, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, + 0xb5, 0xd1, 0x81, 0x20, 0x28, 0xd0, 0xb7, 0xd0, 0xb0, 0xd1, 0x89, 0xd0, + 0xb8, 0xd1, 0x89, 0xd1, 0x91, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, + 0xb9, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xbe, 0xd0, + 0xb2, 0xd1, 0x8b, 0xd0, 0xb9, 0x20, 0x74, 0x2d, 0xd0, 0xb0, 0xd0, 0xb4, + 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0x20, 0x28, 0xd0, 0xbf, 0xd1, 0x80, + 0xd0, 0xbe, 0xd0, 0xb7, 0xd1, 0x80, 0xd0, 0xb0, 0xd1, 0x87, 0xd0, 0xbd, + 0xd1, 0x8b, 0xd0, 0xb9, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, + 0x61, 0x69, 0x6c, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x94, 0xd0, 0xb5, + 0xd1, 0x82, 0xd0, 0xb0, 0xd0, 0xbb, 0xd0, 0xb8, 0x20, 0xd0, 0xb0, 0xd0, + 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, + 0x5f, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9e, 0xd1, 0x82, 0xd0, 0xba, 0xd1, 0x80, 0xd1, 0x8b, 0xd1, + 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xb2, 0x20, 0xd0, 0xbe, 0xd0, 0xb1, 0xd0, + 0xbe, 0xd0, 0xb7, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb2, 0xd0, 0xb0, 0xd1, + 0x82, 0xd0, 0xb5, 0xd0, 0xbb, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0x51, 0x52, 0x2d, 0xd0, 0xba, 0xd0, 0xbe, 0xd0, 0xb4, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x97, 0xd0, 0xb0, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xbe, + 0xd1, 0x81, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xbf, 0xd0, + 0xbb, 0xd0, 0xb0, 0xd1, 0x82, 0xd1, 0x91, 0xd0, 0xb6, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, 0x65, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x94, 0xd0, 0xb0, 0xd1, 0x82, 0xd0, 0xb0, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd1, 0x82, 0xd0, 0xb0, 0xd1, 0x82, + 0xd1, 0x83, 0xd1, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd1, + 0x82, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb6, 0xd0, 0xb4, 0xd0, + 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, 0xd1, 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd1, 0x82, + 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x80, 0xd0, 0xb6, 0xd0, 0xb4, 0xd0, 0xb5, + 0xd0, 0xbd, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x70, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9e, 0xd0, 0xb6, 0xd0, 0xb8, 0xd0, 0xb4, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, + 0xb8, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, + 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, + 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xbb, 0xd0, 0xb5, 0xd0, + 0xbd, 0xd0, 0xbe, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, + 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0xbf, 0xd0, 0xbe, 0xd0, 0xbb, 0xd1, 0x83, 0xd1, 0x87, 0xd0, 0xb5, 0xd0, + 0xbd, 0xd0, 0xbe, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xb4, 0xd0, 0xbe, + 0xd0, 0xb1, 0xd1, 0x8b, 0xd1, 0x82, 0xd0, 0xbe, 0x22, 0x2c, 0x0a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0xa3, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xb2, 0xd0, 0xbb, 0xd0, + 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x20, 0xd0, 0xbc, 0xd0, 0xb0, + 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, 0xd0, 0xbe, + 0xd0, 0xbc, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, + 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x9d, 0xd0, 0xb0, 0xd1, 0x87, 0xd0, 0xb0, 0xd1, 0x82, + 0xd1, 0x8c, 0x20, 0xd0, 0xbc, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, + 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd1, 0x81, 0xd1, 0x82, 0xd0, 0xb0, + 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, + 0x20, 0xd0, 0xbc, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, + 0xbd, 0xd0, 0xb3, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, + 0xbe, 0xd0, 0xba, 0xd0, 0xb8, 0x20, 0xd0, 0xbc, 0xd0, 0xb0, 0xd0, 0xb9, + 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, 0xd0, 0xb0, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd1, 0x82, 0xd0, 0xb0, 0xd1, 0x82, 0xd0, + 0xb8, 0xd1, 0x81, 0xd1, 0x82, 0xd0, 0xb8, 0xd0, 0xba, 0xd0, 0xb0, 0x20, + 0xd0, 0xbc, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xbd, + 0xd0, 0xb3, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, + 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9b, 0xd0, 0xbe, 0xd0, 0xba, + 0xd0, 0xb0, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, + 0x20, 0xd1, 0x85, 0xd0, 0xb5, 0xd1, 0x88, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, + 0xb9, 0xd1, 0x82, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, + 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa5, 0xd0, 0xb5, 0xd1, + 0x88, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb9, 0xd1, 0x82, 0x20, 0xd1, 0x81, + 0xd0, 0xb5, 0xd1, 0x82, 0xd0, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xb6, + 0xd0, 0xbd, 0xd0, 0xbe, 0xd1, 0x81, 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, + 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd0, 0xb6, 0xd0, 0xb8, 0xd0, 0xb4, 0xd0, + 0xb0, 0xd0, 0xb5, 0xd0, 0xbc, 0xd0, 0xbe, 0xd0, 0xb5, 0x20, 0xd0, 0xb2, + 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xbc, 0xd1, 0x8f, 0x20, 0xd0, 0xb4, 0xd0, + 0xbe, 0x20, 0xd0, 0xb1, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb0, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, + 0x6e, 0x67, 0x5f, 0x6f, 0x66, 0x66, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9c, + 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, + 0x20, 0xd0, 0x92, 0xd0, 0xab, 0xd0, 0x9a, 0xd0, 0x9b, 0xd0, 0xae, 0xd0, + 0xa7, 0xd0, 0x95, 0xd0, 0x9d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, 0x6e, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x9c, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbd, 0xd0, 0xb8, + 0xd0, 0xbd, 0xd0, 0xb3, 0x20, 0xd0, 0x92, 0xd0, 0x9a, 0xd0, 0x9b, 0xd0, + 0xae, 0xd0, 0xa7, 0xd0, 0x81, 0xd0, 0x9d, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, + 0x87, 0xd1, 0x91, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb5, 0x20, + 0xd1, 0x83, 0xd0, 0xb7, 0xd0, 0xbb, 0xd1, 0x8b, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, + 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x97, 0xd0, 0xb0, + 0xd0, 0xb1, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb8, 0xd1, 0x80, + 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, + 0xd0, 0xb5, 0x20, 0xd1, 0x83, 0xd0, 0xb7, 0xd0, 0xbb, 0xd1, 0x8b, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x70, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x50, 0x2d, + 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd0, 0xb5, 0xd1, 0x80, 0xd1, + 0x81, 0xd0, 0xb8, 0xd1, 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x92, 0xd1, 0x8b, 0xd1, 0x81, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, 0xb0, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xb8, 0xd0, 0xbd, 0xd0, 0xb3, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x91, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb8, + 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd1, 0x82, 0xd1, 0x8c, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, 0x61, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa0, 0xd0, 0xb0, 0xd0, 0xb7, 0xd0, + 0xb1, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb8, 0xd1, 0x80, 0xd0, + 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, + 0x6c, 0x6c, 0x5f, 0x62, 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0xa1, 0xd0, 0xbd, 0xd1, 0x8f, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xb2, + 0xd1, 0x81, 0xd0, 0xb5, 0x20, 0xd0, 0xb1, 0xd0, 0xbb, 0xd0, 0xbe, 0xd0, + 0xba, 0xd0, 0xb8, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xba, 0xd0, + 0xb8, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72, + 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x72, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x93, 0xd1, 0x80, 0xd0, 0xb0, 0xd1, 0x84, 0xd0, 0xb8, 0xd0, + 0xba, 0x20, 0xd1, 0x86, 0xd0, 0xb5, 0xd0, 0xbd, 0xd1, 0x8b, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, + 0x74, 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0xa2, 0xd0, 0xb5, 0xd0, 0xba, 0xd1, 0x83, 0xd1, 0x89, 0xd0, 0xb0, 0xd1, + 0x8f, 0x20, 0xd1, 0x86, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb0, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, + 0x61, 0x6e, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x98, 0xd0, 0xb7, + 0xd0, 0xbc, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, + 0xd0, 0xb5, 0x20, 0xd0, 0xb7, 0xd0, 0xb0, 0x20, 0x32, 0x34, 0xd1, 0x87, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, + 0xd0, 0xb1, 0xd1, 0x8a, 0xd1, 0x91, 0xd0, 0xbc, 0x20, 0xd0, 0xb7, 0xd0, + 0xb0, 0x20, 0x32, 0x34, 0xd1, 0x87, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x5f, 0x63, 0x61, 0x70, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa0, 0xd1, 0x8b, 0xd0, 0xbd, 0xd0, 0xbe, + 0xd1, 0x87, 0xd0, 0xbd, 0xd0, 0xb0, 0xd1, 0x8f, 0x20, 0xd0, 0xba, 0xd0, + 0xb0, 0xd0, 0xbf, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, + 0xd0, 0x9e, 0xd1, 0x81, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xbd, + 0xd1, 0x8b, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9e, 0xd1, 0x82, 0xd0, 0xbe, 0xd0, 0xb1, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, + 0xb6, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd0, 0xb5, 0xd1, 0x82, 0xd1, 0x8c, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x68, 0x65, 0x6d, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa2, 0xd0, 0xb5, 0xd0, 0xbc, 0xd0, + 0xb0, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x61, 0x6e, + 0x67, 0x75, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xaf, 0xd0, + 0xb7, 0xd1, 0x8b, 0xd0, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x5f, 0x67, 0x72, 0x65, + 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, + 0x58, 0x20, 0x28, 0xd0, 0xb7, 0xd0, 0xb5, 0xd0, 0xbb, 0xd1, 0x91, 0xd0, + 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x29, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x61, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa2, + 0xd1, 0x91, 0xd0, 0xbc, 0xd0, 0xbd, 0xd0, 0xb0, 0xd1, 0x8f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x82, 0xd0, + 0xbb, 0xd0, 0xb0, 0xd1, 0x8f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, + 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa0, + 0xd0, 0xb0, 0xd0, 0xb7, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, 0x88, 0xd0, 0xb8, + 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xbf, 0xd0, 0xbe, 0xd0, 0xbb, 0xd1, + 0x8c, 0xd0, 0xb7, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, 0xd1, 0x82, 0xd0, + 0xb5, 0xd0, 0xbb, 0xd1, 0x8c, 0xd1, 0x81, 0xd0, 0xba, 0xd0, 0xb8, 0xd0, + 0xb5, 0x20, 0xd0, 0xba, 0xd0, 0xbe, 0xd0, 0xbc, 0xd0, 0xb8, 0xd1, 0x81, + 0xd1, 0x81, 0xd0, 0xb8, 0xd0, 0xb8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, + 0x65, 0x64, 0x5f, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x92, 0xd1, 0x81, 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, + 0xb5, 0xd0, 0xbd, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x20, 0x64, 0x72, + 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, + 0xd0, 0xbe, 0xd1, 0x85, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xb8, + 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x97, 0xd0, + 0xb0, 0xd0, 0xba, 0xd1, 0x80, 0xd1, 0x8b, 0xd1, 0x82, 0xd1, 0x8c, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa4, 0xd0, 0xb0, 0xd0, 0xb9, 0xd0, 0xbb, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x64, 0x69, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa0, 0xd0, 0xb5, 0xd0, 0xb4, 0xd0, 0xb0, + 0xd0, 0xba, 0xd1, 0x82, 0xd0, 0xb8, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, + 0xd0, 0xb0, 0xd1, 0x82, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, + 0xd0, 0xb8, 0xd0, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x68, 0x65, 0x6c, 0x70, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, + 0xd0, 0xbc, 0xd0, 0xbe, 0xd1, 0x89, 0xd1, 0x8c, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x70, + 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0x98, 0xd0, 0xbc, 0xd0, 0xbf, 0xd0, 0xbe, 0xd1, 0x80, + 0xd1, 0x82, 0x20, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, 0xb2, 0xd0, + 0xb0, 0xd1, 0x82, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xb3, 0xd0, 0xbe, 0x20, + 0xd0, 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, 0x87, 0xd0, 0xb0, 0x2e, 0x2e, + 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, + 0x6b, 0x75, 0x70, 0x5f, 0x77, 0x61, 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, + 0x20, 0x22, 0xd0, 0xa0, 0xd0, 0xb5, 0xd0, 0xb7, 0xd0, 0xb5, 0xd1, 0x80, + 0xd0, 0xb2, 0xd0, 0xbd, 0xd0, 0xbe, 0xd0, 0xb5, 0x20, 0xd0, 0xba, 0xd0, + 0xbe, 0xd0, 0xbf, 0xd0, 0xb8, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, + 0xb0, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x20, 0xd0, 0xba, 0xd0, 0xbe, + 0xd1, 0x88, 0xd0, 0xb5, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xba, 0xd0, 0xb0, + 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, + 0x78, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x92, 0xd1, 0x8b, 0xd1, + 0x85, 0xd0, 0xbe, 0xd0, 0xb4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x5f, 0x64, 0x72, 0x61, 0x67, 0x6f, + 0x6e, 0x78, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0x20, 0xd0, 0xbf, 0xd1, + 0x80, 0xd0, 0xbe, 0xd0, 0xb3, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbc, 0xd0, + 0xbc, 0xd0, 0xb5, 0x20, 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, 0x6e, + 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, 0x6f, + 0x77, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0xd0, 0xb1, 0xd0, 0xbd, 0xd0, + 0xbe, 0xd0, 0xb2, 0xd0, 0xb8, 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd1, 0x81, + 0xd0, 0xb5, 0xd0, 0xb9, 0xd1, 0x87, 0xd0, 0xb0, 0xd1, 0x81, 0x22, 0x2c, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9e, 0x20, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, + 0xbe, 0xd0, 0xb3, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbc, 0xd0, 0xbc, 0xd0, + 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x98, 0xd0, 0xbc, 0xd0, + 0xbf, 0xd0, 0xbe, 0xd1, 0x80, 0xd1, 0x82, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0xad, 0xd0, 0xba, 0xd1, 0x81, 0xd0, 0xbf, 0xd0, 0xbe, 0xd1, + 0x80, 0xd1, 0x82, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, 0x63, 0x6c, 0x69, 0x70, 0x62, + 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9a, 0xd0, 0xbe, + 0xd0, 0xbf, 0xd0, 0xb8, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb2, 0xd0, 0xb0, + 0xd1, 0x82, 0xd1, 0x8c, 0x20, 0xd0, 0xb2, 0x20, 0xd0, 0xb1, 0xd1, 0x83, + 0xd1, 0x84, 0xd0, 0xb5, 0xd1, 0x80, 0x20, 0xd0, 0xbe, 0xd0, 0xb1, 0xd0, + 0xbc, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb0, 0x22, 0x2c, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, + 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, 0x87, 0xd1, 0x91, 0xd0, 0xbd, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9e, 0xd1, 0x82, 0xd0, 0xba, 0xd0, 0xbb, 0xd1, 0x8e, 0xd1, 0x87, 0xd1, + 0x91, 0xd0, 0xbd, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9f, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xba, 0xd0, 0xbb, 0xd1, + 0x8e, 0xd1, 0x87, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x79, + 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd0, + 0xb8, 0xd0, 0xbd, 0xd1, 0x85, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xbd, 0xd0, + 0xb8, 0xd0, 0xb7, 0xd0, 0xb0, 0xd1, 0x86, 0xd0, 0xb8, 0xd1, 0x8f, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0x91, 0xd0, 0xbb, 0xd0, + 0xbe, 0xd0, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, + 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, + 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0xd0, 0x9d, 0xd0, 0xb5, 0xd1, 0x82, 0x20, 0xd0, 0xb4, 0xd0, 0xbe, + 0xd1, 0x81, 0xd1, 0x82, 0xd1, 0x83, 0xd0, 0xbf, 0xd0, 0xbd, 0xd1, 0x8b, + 0xd1, 0x85, 0x20, 0xd0, 0xb0, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd1, + 0x81, 0xd0, 0xbe, 0xd0, 0xb2, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xd0, + 0x9e, 0xd1, 0x88, 0xd0, 0xb8, 0xd0, 0xb1, 0xd0, 0xba, 0xd0, 0xb0, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x63, 0x63, 0x65, + 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa3, 0xd1, 0x81, 0xd0, 0xbf, + 0xd0, 0xb5, 0xd1, 0x88, 0xd0, 0xbd, 0xd0, 0xbe, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb4, 0xd1, + 0x83, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb6, 0xd0, 0xb4, 0xd0, + 0xb5, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xb5, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x65, 0x78, + 0x63, 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xd0, 0xa1, 0xd1, 0x83, 0xd0, 0xbc, 0xd0, + 0xbc, 0xd0, 0xb0, 0x20, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb2, + 0xd1, 0x8b, 0xd1, 0x88, 0xd0, 0xb0, 0xd0, 0xb5, 0xd1, 0x82, 0x20, 0xd0, + 0xb1, 0xd0, 0xb0, 0xd0, 0xbb, 0xd0, 0xb0, 0xd0, 0xbd, 0xd1, 0x81, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xd0, 0xa2, 0xd1, 0x80, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, + 0xb7, 0xd0, 0xb0, 0xd0, 0xba, 0xd1, 0x86, 0xd0, 0xb8, 0xd1, 0x8f, 0x20, + 0xd1, 0x83, 0xd1, 0x81, 0xd0, 0xbf, 0xd0, 0xb5, 0xd1, 0x88, 0xd0, 0xbd, + 0xd0, 0xbe, 0x20, 0xd0, 0xbe, 0xd1, 0x82, 0xd0, 0xbf, 0xd1, 0x80, 0xd0, + 0xb0, 0xd0, 0xb2, 0xd0, 0xbb, 0xd0, 0xb5, 0xd0, 0xbd, 0xd0, 0xb0, 0x22, + 0x0a, 0x7d, 0x0a +}; +unsigned int res_lang_ru_json_len = 5979; diff --git a/src/embedded/lang_zh.h b/src/embedded/lang_zh.h new file mode 100644 index 0000000..ecc2320 --- /dev/null +++ b/src/embedded/lang_zh.h @@ -0,0 +1,355 @@ +unsigned char res_lang_zh_json[] = { + 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6c, 0x61, 0x6e, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbd, 0x99, 0xe9, 0xa2, 0x9d, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8e, 0xa5, 0xe6, 0x94, 0xb6, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe4, + 0xba, 0xa4, 0xe6, 0x98, 0x93, 0xe8, 0xae, 0xb0, 0xe5, 0xbd, 0x95, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8c, 0x96, 0xe7, 0x9f, 0xbf, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, 0x65, 0x72, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xe8, 0x8a, 0x82, 0xe7, 0x82, 0xb9, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb8, 0x82, 0xe5, 0x9c, 0xba, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe8, 0xae, 0xbe, 0xe7, 0xbd, 0xae, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x75, 0x6d, + 0x6d, 0x61, 0x72, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xa6, 0x82, 0xe8, + 0xa7, 0x88, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x68, + 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x9a, + 0x90, 0xe7, 0xa7, 0x81, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, + 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x8f, + 0xe6, 0x98, 0x8e, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x22, 0x3a, + 0x20, 0x22, 0xe6, 0x80, 0xbb, 0xe8, 0xae, 0xa1, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x9c, 0xaa, 0xe7, 0xa1, + 0xae, 0xe8, 0xae, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x79, 0x6f, 0x75, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x82, 0xa8, 0xe7, 0x9a, 0x84, + 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x7a, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x5a, 0x2d, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, + 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0x54, 0x2d, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x9c, 0xaa, 0xe6, + 0x89, 0xbe, 0xe5, 0x88, 0xb0, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0xe3, + 0x80, 0x82, 0xe8, 0xaf, 0xb7, 0xe4, 0xbd, 0xbf, 0xe7, 0x94, 0xa8, 0xe4, + 0xb8, 0x8a, 0xe6, 0x96, 0xb9, 0xe6, 0x8c, 0x89, 0xe9, 0x92, 0xae, 0xe5, + 0x88, 0x9b, 0xe5, 0xbb, 0xba, 0xe3, 0x80, 0x82, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x7a, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, 0xb0, + 0xe5, 0xbb, 0xba, 0x20, 0x5a, 0x2d, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, + 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xe6, 0x96, 0xb0, 0xe5, 0xbb, 0xba, 0x20, 0x54, 0x2d, 0xe5, 0x9c, + 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xb1, 0xbb, 0xe5, + 0x9e, 0x8b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x9c, 0xb0, + 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, + 0x6f, 0x70, 0x79, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe5, 0xa4, 0x8d, 0xe5, 0x88, 0xb6, 0xe5, 0xae, 0x8c, + 0xe6, 0x95, 0xb4, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x72, + 0x6f, 0x6d, 0x5f, 0x74, 0x68, 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbb, 0x8e, 0xe6, 0xad, + 0xa4, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0xe5, 0x8f, 0x91, 0xe9, 0x80, + 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, + 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, + 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xaf, 0xbc, 0xe5, 0x87, + 0xba, 0xe7, 0xa7, 0x81, 0xe9, 0x92, 0xa5, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x69, + 0x65, 0x77, 0x69, 0x6e, 0x67, 0x5f, 0x6b, 0x65, 0x79, 0x22, 0x3a, 0x20, + 0x22, 0xe5, 0xaf, 0xbc, 0xe5, 0x87, 0xba, 0xe6, 0x9f, 0xa5, 0xe7, 0x9c, + 0x8b, 0xe5, 0xaf, 0x86, 0xe9, 0x92, 0xa5, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x68, 0x6f, 0x77, 0x5f, 0x71, 0x72, 0x5f, 0x63, + 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x98, 0xbe, 0xe7, 0xa4, + 0xba, 0xe4, 0xba, 0x8c, 0xe7, 0xbb, 0xb4, 0xe7, 0xa0, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x74, 0x5f, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe6, + 0x9c, 0xaa, 0xe8, 0xbf, 0x9e, 0xe6, 0x8e, 0xa5, 0xe5, 0x88, 0xb0, 0xe5, + 0xae, 0x88, 0xe6, 0x8a, 0xa4, 0xe8, 0xbf, 0x9b, 0xe7, 0xa8, 0x8b, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x61, 0x79, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, 0x22, 0xe4, + 0xbb, 0x98, 0xe6, 0xac, 0xbe, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x5f, + 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x94, 0xb6, 0xe6, 0xac, 0xbe, + 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0xe9, 0x87, 0x91, 0xe9, 0xa2, 0x9d, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xa4, + 0x87, 0xe6, 0xb3, 0xa8, 0xef, 0xbc, 0x88, 0xe5, 0x8f, 0xaf, 0xe9, 0x80, + 0x89, 0xef, 0xbc, 0x8c, 0xe5, 0xb7, 0xb2, 0xe5, 0x8a, 0xa0, 0xe5, 0xaf, + 0x86, 0xef, 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6d, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0xe7, 0x9f, 0xbf, 0xe5, 0xb7, 0xa5, 0xe6, 0x89, 0x8b, 0xe7, 0xbb, + 0xad, 0xe8, 0xb4, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x66, 0x65, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x89, 0x8b, 0xe7, 0xbb, + 0xad, 0xe8, 0xb4, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, + 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x91, 0xe9, + 0x80, 0x81, 0xe4, 0xba, 0xa4, 0xe6, 0x98, 0x93, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x22, 0x3a, 0x20, + 0x22, 0xe6, 0xb8, 0x85, 0xe9, 0x99, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x89, + 0xe6, 0x8b, 0xa9, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x2e, 0x2e, 0x2e, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x73, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xb2, 0x98, 0xe8, 0xb4, 0xb4, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x78, 0x22, 0x3a, + 0x20, 0x22, 0xe6, 0x9c, 0x80, 0xe5, 0xa4, 0xa7, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0xaf, 0xe7, 0x94, 0xa8, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, + 0x69, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3a, + 0x20, 0x22, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0xe6, 0xa0, 0xbc, 0xe5, + 0xbc, 0x8f, 0xe6, 0x97, 0xa0, 0xe6, 0x95, 0x88, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x6d, 0x6f, 0x5f, 0x7a, 0x5f, 0x6f, + 0x6e, 0x6c, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xb3, 0xa8, 0xe6, 0x84, + 0x8f, 0xef, 0xbc, 0x9a, 0xe5, 0xa4, 0x87, 0xe6, 0xb3, 0xa8, 0xe4, 0xbb, + 0x85, 0xe5, 0x9c, 0xa8, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, 0xe5, 0x88, + 0xb0, 0xe9, 0x9a, 0x90, 0xe7, 0xa7, 0x81, 0xef, 0xbc, 0x88, 0x7a, 0xef, + 0xbc, 0x89, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0xe6, 0x97, 0xb6, 0xe5, + 0x8f, 0xaf, 0xe7, 0x94, 0xa8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73, 0x22, + 0x3a, 0x20, 0x22, 0xe5, 0xad, 0x97, 0xe7, 0xac, 0xa6, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x72, 0x6f, 0x6d, 0x22, 0x3a, 0x20, + 0x22, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, 0xe6, 0x96, 0xb9, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x6f, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x8e, 0xa5, 0xe6, 0x94, 0xb6, 0xe6, 0x96, 0xb9, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xad, 0xa3, 0xe5, 0x9c, 0xa8, 0xe5, 0x8f, + 0x91, 0xe9, 0x80, 0x81, 0xe4, 0xba, 0xa4, 0xe6, 0x98, 0x93, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa1, + 0xae, 0xe8, 0xae, 0xa4, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa1, 0xae, 0xe8, 0xae, 0xa4, 0xe4, + 0xba, 0xa4, 0xe6, 0x98, 0x93, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x61, 0x6e, 0x64, + 0x5f, 0x73, 0x65, 0x6e, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xa1, 0xae, + 0xe8, 0xae, 0xa4, 0xe5, 0xb9, 0xb6, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x6e, 0x63, + 0x65, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8f, 0x96, 0xe6, 0xb6, 0x88, + 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, + 0x65, 0x69, 0x76, 0x69, 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x82, 0xa8, 0xe7, + 0x9a, 0x84, 0xe6, 0x8e, 0xa5, 0xe6, 0x94, 0xb6, 0xe5, 0x9c, 0xb0, 0xe5, + 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, + 0x77, 0x5f, 0x7a, 0x5f, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, + 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, 0xb0, 0xe5, 0xbb, 0xba, 0x20, 0x7a, + 0x2d, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0xef, 0xbc, 0x88, 0xe9, 0x9a, + 0x90, 0xe7, 0xa7, 0x81, 0xef, 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x5f, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x96, 0xb0, 0xe5, 0xbb, 0xba, 0x20, 0x74, 0x2d, 0xe5, 0x9c, 0xb0, + 0xe5, 0x9d, 0x80, 0xef, 0xbc, 0x88, 0xe9, 0x80, 0x8f, 0xe6, 0x98, 0x8e, + 0xef, 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x69, + 0x6c, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x9c, 0xb0, 0xe5, 0x9d, 0x80, + 0xe8, 0xaf, 0xa6, 0xe6, 0x83, 0x85, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x6f, 0x6e, 0x5f, 0x65, 0x78, + 0x70, 0x6c, 0x6f, 0x72, 0x65, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x9c, + 0xa8, 0xe6, 0xb5, 0x8f, 0xe8, 0xa7, 0x88, 0xe5, 0x99, 0xa8, 0xe6, 0x9f, + 0xa5, 0xe7, 0x9c, 0x8b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x71, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe4, + 0xba, 0x8c, 0xe7, 0xbb, 0xb4, 0xe7, 0xa0, 0x81, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe8, + 0xaf, 0xb7, 0xe6, 0xb1, 0x82, 0xe4, 0xbb, 0x98, 0xe6, 0xac, 0xbe, 0x22, + 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, 0x74, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x97, 0xa5, 0xe6, 0x9c, 0x9f, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xe7, 0x8a, 0xb6, 0xe6, 0x80, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, + 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe7, + 0xa1, 0xae, 0xe8, 0xae, 0xa4, 0xe6, 0x95, 0xb0, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x65, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb7, 0xb2, 0xe7, 0xa1, 0xae, 0xe8, + 0xae, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x65, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xbe, 0x85, + 0xe7, 0xa1, 0xae, 0xe8, 0xae, 0xa4, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb7, + 0xb2, 0xe5, 0x8f, 0x91, 0xe9, 0x80, 0x81, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0xe5, 0xb7, 0xb2, 0xe6, 0x8e, 0xa5, 0xe6, 0x94, 0xb6, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x65, + 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb7, 0xb2, 0xe6, 0x8c, 0x96, 0xe5, + 0x87, 0xba, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, + 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8c, 0x96, 0xe7, 0x9f, 0xbf, 0xe6, + 0x8e, 0xa7, 0xe5, 0x88, 0xb6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, + 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xbc, 0x80, 0xe5, 0xa7, 0x8b, 0xe6, + 0x8c, 0x96, 0xe7, 0x9f, 0xbf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x81, 0x9c, 0xe6, 0xad, 0xa2, 0xe6, 0x8c, + 0x96, 0xe7, 0x9f, 0xbf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, + 0x64, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8c, 0x96, 0xe7, 0x9f, 0xbf, + 0xe7, 0xba, 0xbf, 0xe7, 0xa8, 0x8b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, + 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, + 0x8c, 0x96, 0xe7, 0x9f, 0xbf, 0xe7, 0xbb, 0x9f, 0xe8, 0xae, 0xa1, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x6f, 0x63, 0x61, 0x6c, + 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0xe6, 0x9c, 0xac, 0xe5, 0x9c, 0xb0, 0xe7, 0xae, 0x97, 0xe5, 0x8a, + 0x9b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x65, 0x74, + 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x72, 0x61, 0x74, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x85, 0xa8, 0xe7, 0xbd, 0x91, 0xe7, + 0xae, 0x97, 0xe5, 0x8a, 0x9b, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x64, 0x69, 0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x79, 0x22, + 0x3a, 0x20, 0x22, 0xe9, 0x9a, 0xbe, 0xe5, 0xba, 0xa6, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x73, 0x74, 0x5f, 0x74, 0x69, 0x6d, + 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3a, + 0x20, 0x22, 0xe9, 0xa2, 0x84, 0xe8, 0xae, 0xa1, 0xe5, 0x87, 0xba, 0xe5, + 0x9d, 0x97, 0xe6, 0x97, 0xb6, 0xe9, 0x97, 0xb4, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x6f, + 0x66, 0x66, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8c, 0x96, 0xe7, 0x9f, 0xbf, + 0xe5, 0xb7, 0xb2, 0xe5, 0x85, 0xb3, 0xe9, 0x97, 0xad, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x5f, + 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x8c, 0x96, 0xe7, 0x9f, 0xbf, + 0xe5, 0xb7, 0xb2, 0xe5, 0xbc, 0x80, 0xe5, 0x90, 0xaf, 0x22, 0x2c, 0x0a, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x3a, 0x20, + 0x22, 0xe5, 0xb7, 0xb2, 0xe8, 0xbf, 0x9e, 0xe6, 0x8e, 0xa5, 0xe8, 0x8a, + 0x82, 0xe7, 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x62, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb7, 0xb2, 0xe5, 0xb0, 0x81, 0xe7, 0xa6, + 0x81, 0xe8, 0x8a, 0x82, 0xe7, 0x82, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x22, 0x3a, 0x20, 0x22, 0x49, 0x50, 0x20, 0xe5, 0x9c, 0xb0, 0xe5, + 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0x89, 0x88, + 0xe6, 0x9c, 0xac, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, + 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0xab, 0x98, + 0xe5, 0xba, 0xa6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xbb, 0xb6, 0xe8, 0xbf, + 0x9f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x61, 0x6e, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb0, 0x81, 0xe7, 0xa6, 0x81, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x75, 0x6e, 0x62, 0x61, 0x6e, 0x22, + 0x3a, 0x20, 0x22, 0xe8, 0xa7, 0xa3, 0xe5, 0xb0, 0x81, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6c, 0x65, 0x61, 0x72, 0x5f, 0x61, + 0x6c, 0x6c, 0x5f, 0x62, 0x61, 0x6e, 0x73, 0x22, 0x3a, 0x20, 0x22, 0xe6, + 0xb8, 0x85, 0xe9, 0x99, 0xa4, 0xe6, 0x89, 0x80, 0xe6, 0x9c, 0x89, 0xe5, + 0xb0, 0x81, 0xe7, 0xa6, 0x81, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x70, 0x72, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x72, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xbb, 0xb7, 0xe6, 0xa0, 0xbc, 0xe5, + 0x9b, 0xbe, 0xe8, 0xa1, 0xa8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x72, 0x69, + 0x63, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xbd, 0x93, 0xe5, 0x89, 0x8d, + 0xe4, 0xbb, 0xb7, 0xe6, 0xa0, 0xbc, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0xe5, 0xb0, 0x8f, 0xe6, 0x97, 0xb6, + 0xe6, 0xb6, 0xa8, 0xe8, 0xb7, 0x8c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x32, 0x34, 0x68, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x22, 0x3a, 0x20, 0x22, 0x32, 0x34, 0xe5, 0xb0, 0x8f, 0xe6, 0x97, 0xb6, + 0xe6, 0x88, 0x90, 0xe4, 0xba, 0xa4, 0xe9, 0x87, 0x8f, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x74, 0x5f, + 0x63, 0x61, 0x70, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb8, 0x82, 0xe5, 0x80, + 0xbc, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x67, 0x65, + 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x9a, + 0xe7, 0x94, 0xa8, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, + 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x98, + 0xbe, 0xe7, 0xa4, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xe7, + 0xbd, 0x91, 0xe7, 0xbb, 0x9c, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x74, 0x68, 0x65, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe4, 0xb8, + 0xbb, 0xe9, 0xa2, 0x98, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xe8, 0xaf, 0xad, 0xe8, 0xa8, 0x80, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x5f, 0x67, 0x72, + 0x65, 0x65, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x61, 0x67, 0x6f, + 0x6e, 0x58, 0xef, 0xbc, 0x88, 0xe7, 0xbb, 0xbf, 0xe8, 0x89, 0xb2, 0xef, + 0xbc, 0x89, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x61, + 0x72, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xb7, 0xb1, 0xe8, 0x89, 0xb2, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6c, 0x69, 0x67, 0x68, + 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0xb5, 0x85, 0xe8, 0x89, 0xb2, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x6c, 0x6c, 0x6f, 0x77, + 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x66, 0x65, 0x65, 0x73, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x85, 0x81, 0xe8, 0xae, 0xb8, 0xe8, 0x87, + 0xaa, 0xe5, 0xae, 0x9a, 0xe4, 0xb9, 0x89, 0xe6, 0x89, 0x8b, 0xe7, 0xbb, + 0xad, 0xe8, 0xb4, 0xb9, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, + 0x5f, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x22, 0x3a, 0x20, 0x22, 0xe4, + 0xbd, 0xbf, 0xe7, 0x94, 0xa8, 0xe5, 0x86, 0x85, 0xe7, 0xbd, 0xae, 0x20, + 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x64, 0x22, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x73, 0x61, 0x76, 0x65, 0x22, 0x3a, 0x20, 0x22, + 0xe4, 0xbf, 0x9d, 0xe5, 0xad, 0x98, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe5, + 0x85, 0xb3, 0xe9, 0x97, 0xad, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x96, + 0x87, 0xe4, 0xbb, 0xb6, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, + 0x65, 0x64, 0x69, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xbc, 0x96, 0xe8, + 0xbe, 0x91, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x76, 0x69, + 0x65, 0x77, 0x22, 0x3a, 0x20, 0x22, 0xe6, 0x9f, 0xa5, 0xe7, 0x9c, 0x8b, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x70, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xb8, 0xae, 0xe5, 0x8a, 0xa9, 0x22, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, + 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, + 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xaf, 0xbc, 0xe5, 0x85, 0xa5, 0xe7, 0xa7, + 0x81, 0xe9, 0x92, 0xa5, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x5f, 0x77, 0x61, + 0x6c, 0x6c, 0x65, 0x74, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0xa4, 0x87, 0xe4, + 0xbb, 0xbd, 0xe9, 0x92, 0xb1, 0xe5, 0x8c, 0x85, 0x2e, 0x2e, 0x2e, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x65, 0x78, 0x69, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xe9, 0x80, 0x80, 0xe5, 0x87, 0xba, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x5f, 0x64, + 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x78, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x85, + 0xb3, 0xe4, 0xba, 0x8e, 0x20, 0x4f, 0x62, 0x73, 0x69, 0x64, 0x69, 0x61, + 0x6e, 0x44, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x6e, + 0x6f, 0x77, 0x22, 0x3a, 0x20, 0x22, 0xe7, 0xab, 0x8b, 0xe5, 0x8d, 0xb3, + 0xe5, 0x88, 0xb7, 0xe6, 0x96, 0xb0, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0xe5, 0x85, 0xb3, 0xe4, 0xba, 0x8e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0xe5, 0xaf, 0xbc, 0xe5, 0x85, 0xa5, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x3a, 0x20, 0x22, + 0xe5, 0xaf, 0xbc, 0xe5, 0x87, 0xba, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x5f, 0x74, 0x6f, 0x5f, 0x63, 0x6c, + 0x69, 0x70, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x22, 0x3a, 0x20, 0x22, 0xe5, + 0xa4, 0x8d, 0xe5, 0x88, 0xb6, 0xe5, 0x88, 0xb0, 0xe5, 0x89, 0xaa, 0xe8, + 0xb4, 0xb4, 0xe6, 0x9d, 0xbf, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, + 0x3a, 0x20, 0x22, 0xe5, 0xb7, 0xb2, 0xe8, 0xbf, 0x9e, 0xe6, 0x8e, 0xa5, + 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x64, 0x69, 0x73, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x3a, 0x20, 0x22, + 0xe5, 0xb7, 0xb2, 0xe6, 0x96, 0xad, 0xe5, 0xbc, 0x80, 0x22, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, 0x22, 0xe8, 0xbf, 0x9e, 0xe6, 0x8e, + 0xa5, 0xe4, 0xb8, 0xad, 0x2e, 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0x3a, + 0x20, 0x22, 0xe5, 0x90, 0x8c, 0xe6, 0xad, 0xa5, 0xe4, 0xb8, 0xad, 0x2e, + 0x2e, 0x2e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x22, 0x3a, 0x20, 0x22, 0xe5, 0x8c, 0xba, 0xe5, 0x9d, + 0x97, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6e, 0x6f, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, 0x61, 0x76, + 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe6, + 0x9a, 0x82, 0xe6, 0x97, 0xa0, 0xe5, 0x8f, 0xaf, 0xe7, 0x94, 0xa8, 0xe5, + 0x9c, 0xb0, 0xe5, 0x9d, 0x80, 0x22, 0x2c, 0x0a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x22, 0xe9, + 0x94, 0x99, 0xe8, 0xaf, 0xaf, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x3a, 0x20, 0x22, + 0xe6, 0x88, 0x90, 0xe5, 0x8a, 0x9f, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x22, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x20, + 0x22, 0xe8, 0xad, 0xa6, 0xe5, 0x91, 0x8a, 0x22, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x22, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x65, 0x78, + 0x63, 0x65, 0x65, 0x64, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, + 0x65, 0x22, 0x3a, 0x20, 0x22, 0xe9, 0x87, 0x91, 0xe9, 0xa2, 0x9d, 0xe8, + 0xb6, 0x85, 0xe5, 0x87, 0xba, 0xe4, 0xbd, 0x99, 0xe9, 0xa2, 0x9d, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x74, 0x72, 0x61, 0x6e, 0x73, + 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x22, + 0x3a, 0x20, 0x22, 0xe4, 0xba, 0xa4, 0xe6, 0x98, 0x93, 0xe5, 0x8f, 0x91, + 0xe9, 0x80, 0x81, 0xe6, 0x88, 0x90, 0xe5, 0x8a, 0x9f, 0x22, 0x0a, 0x7d, + 0x0a +}; +unsigned int res_lang_zh_json_len = 4213; diff --git a/src/embedded/resources.h b/src/embedded/resources.h new file mode 100644 index 0000000..1016680 --- /dev/null +++ b/src/embedded/resources.h @@ -0,0 +1,65 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// Embedded Resources Header +// This provides access to resources embedded in the binary + +#pragma once +#include +#include +#include +#include + +namespace dragonx { +namespace embedded { + +// Forward declarations for embedded data (generated at build time) +struct EmbeddedResource { + const unsigned char* data; + size_t size; +}; + +// Resource registry +class Resources { +public: + static Resources& instance() { + static Resources inst; + return inst; + } + + // Get embedded resource by name + // Returns nullptr if not found + const EmbeddedResource* get(const std::string& name) const { + auto it = resources_.find(name); + if (it != resources_.end()) { + return &it->second; + } + return nullptr; + } + + // Check if resource exists + bool has(const std::string& name) const { + return resources_.find(name) != resources_.end(); + } + + // Register a resource (called during static init) + void registerResource(const std::string& name, const unsigned char* data, size_t size) { + resources_[name] = {data, size}; + } + +private: + Resources() = default; + std::unordered_map resources_; +}; + +// Helper macro for registering resources +#define REGISTER_EMBEDDED_RESOURCE(name, data, size) \ + static struct _EmbeddedResourceRegister_##name { \ + _EmbeddedResourceRegister_##name() { \ + dragonx::embedded::Resources::instance().registerResource(#name, data, size); \ + } \ + } _embedded_resource_register_##name + +} // namespace embedded +} // namespace dragonx diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..9e95555 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,1745 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "app.h" +#include "config/settings.h" +#include "config/version.h" +#include "rpc/rpc_worker.h" +#include "ui/schema/ui_schema.h" +#include "ui/effects/low_spec.h" +#include "ui/notifications.h" +#include "ui/theme.h" +#include "ui/material/color_theme.h" +#include "ui/material/typography.h" +#include "ui/material/draw_helpers.h" +#include "ui/layout.h" +#include "util/single_instance.h" +#include "util/payment_uri.h" +#include "util/perf_log.h" + +#include "imgui.h" +#include "imgui_internal.h" +#include "imgui_impl_sdl3.h" +#include "ui/effects/imgui_acrylic.h" +#include "ui/effects/theme_effects.h" +#include "util/texture_loader.h" +#include "util/platform.h" +#include "resources/embedded_resources.h" + +// Backend-specific headers +#ifdef DRAGONX_USE_DX11 + #include "imgui_impl_dx11.h" + #include "platform/dx11_context.h" +#else + #include "imgui_impl_opengl3.h" + #include + #ifdef DRAGONX_HAS_GLAD + #include + #endif +#endif + +#include +#include + +#ifdef _WIN32 +#include "platform/windows_backdrop.h" +#include +#include +// Not defined in older MinGW SDK headers +#ifndef WS_EX_NOREDIRECTIONBITMAP +#define WS_EX_NOREDIRECTIONBITMAP 0x00200000L +#endif +// Needed by the borderless WndProc for WM_NCHITTEST +#ifndef GET_X_LPARAM +#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp)) +#endif +#ifndef GET_Y_LPARAM +#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp)) +#endif +#endif + +#include +#include +#include +#include +#include +#include +#include "util/logger.h" + +#ifdef _WIN32 +// Windows crash handler — writes a minidump and log entry before exit +static LONG WINAPI CrashHandler(EXCEPTION_POINTERS* ep) +{ + // Write crash info to the debug log and a dedicated crash log + const char* crashMsg = "\n=== CRASH DETECTED ==="; + DEBUG_LOGF("%s", crashMsg); + DEBUG_LOGF("\nException code: 0x%08lX", ep->ExceptionRecord->ExceptionCode); + DEBUG_LOGF("\nException address: %p", ep->ExceptionRecord->ExceptionAddress); + if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + ep->ExceptionRecord->NumberParameters >= 2) { + DEBUG_LOGF("\nAccess type: %s, target address: %p", + ep->ExceptionRecord->ExceptionInformation[0] ? "WRITE" : "READ", + (void*)ep->ExceptionRecord->ExceptionInformation[1]); + } + DEBUG_LOGF("\n=== END CRASH INFO ===\n"); + fflush(stdout); + fflush(stderr); + + // Also write to a separate crash log file + try { + std::string crashPath = (std::filesystem::path( + dragonx::util::Platform::getObsidianDragonDir()) / "dragonx-crash.log").string(); + FILE* f = fopen(crashPath.c_str(), "a"); + if (f) { + fprintf(f, "\n=== CRASH at PID %lu ===", (unsigned long)GetCurrentProcessId()); + fprintf(f, "\nException code: 0x%08lX", ep->ExceptionRecord->ExceptionCode); + fprintf(f, "\nException address: %p", ep->ExceptionRecord->ExceptionAddress); + if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + ep->ExceptionRecord->NumberParameters >= 2) { + fprintf(f, "\nAccess type: %s, target address: %p", + ep->ExceptionRecord->ExceptionInformation[0] ? "WRITE" : "READ", + (void*)ep->ExceptionRecord->ExceptionInformation[1]); + } + fprintf(f, "\n=== END CRASH INFO ===\n"); + fclose(f); + } + } catch (...) {} + return EXCEPTION_EXECUTE_HANDLER; +} +#endif + +// --------------------------------------------------------------- +// Borderless window support (DX11 / Windows only) +// --------------------------------------------------------------- +#ifdef DRAGONX_USE_DX11 + +static WNDPROC g_sdlWndProc = nullptr; + +// Caption-zone state: updated every frame by renderBorderlessControls() +// so that WM_NCHITTEST can return HTCAPTION for window dragging. +static float g_captionHeight = 20.0f; // height of the title/menu bar (px) +static float g_captionBtnStartX = 0.0f; // left edge of the min/max/close buttons +static bool g_captionImGuiHover = false; // true when ImGui has a hovered/active item +static float g_borderlessDpi = 1.0f; // DPI scale, updated from SDL each frame + +// Custom WndProc that removes the native title bar by extending the +// client area to cover the entire window (WM_NCCALCSIZE) and provides +// resize borders + caption drag zone (WM_NCHITTEST). +static LRESULT CALLBACK BorderlessWndProc(HWND hwnd, UINT msg, + WPARAM wParam, LPARAM lParam) +{ + switch (msg) { + case WM_NCCALCSIZE: + if (wParam == TRUE) { + // Returning 0 makes the entire window rect into client area, + // which effectively removes the title bar. When maximized, + // constrain to the monitor work area so content isn't clipped + // behind the taskbar. + WINDOWPLACEMENT wp = {}; + wp.length = sizeof(wp); + GetWindowPlacement(hwnd, &wp); + if (wp.showCmd == SW_MAXIMIZE) { + auto* p = reinterpret_cast(lParam); + HMONITOR mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + MONITORINFO mi = {}; + mi.cbSize = sizeof(mi); + GetMonitorInfo(mon, &mi); + p->rgrc[0] = mi.rcWork; + } + return 0; + } + break; + + case WM_NCHITTEST: { + POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; + ScreenToClient(hwnd, &pt); + RECT rc; + GetClientRect(hwnd, &rc); + + // Resize borders (not when maximized). + WINDOWPLACEMENT wp = {}; + wp.length = sizeof(wp); + GetWindowPlacement(hwnd, &wp); + if (wp.showCmd != SW_MAXIMIZE) { + const int bdr = (int)(5.0f * g_borderlessDpi); + bool t = pt.y <= bdr, b = pt.y >= rc.bottom - bdr; + bool l = pt.x <= bdr, r = pt.x >= rc.right - bdr; + if (t && l) return HTTOPLEFT; + if (t && r) return HTTOPRIGHT; + if (b && l) return HTBOTTOMLEFT; + if (b && r) return HTBOTTOMRIGHT; + if (t) return HTTOP; + if (b) return HTBOTTOM; + if (l) return HTLEFT; + if (r) return HTRIGHT; + } + + // Caption zone: the top bar where the menu + window buttons live. + // Return HTCAPTION so Windows handles drag/move natively — but + // only when the cursor is NOT over the window-control buttons and + // NOT over an ImGui interactive item (e.g. a menu-bar entry). + if (pt.y < (int)g_captionHeight) { + // Window-control buttons (min/max/close) on the right + if (pt.x >= (int)g_captionBtnStartX) return HTCLIENT; + // ImGui menu item hovered — let ImGui handle the click + if (g_captionImGuiHover) return HTCLIENT; + return HTCAPTION; + } + + return HTCLIENT; + } + + case WM_SETCURSOR: + // Prevent DefWindowProc from resetting the cursor to the window- + // class cursor (IDC_ARROW) on every mouse move. Our render loop + // calls SDL_SetCursor() each frame based on ImGui's cursor state; + // without this, WM_SETCURSOR fires between frames and reverts the + // hand/resize cursor back to the arrow. + if (LOWORD(lParam) == HTCLIENT) + return TRUE; // "handled" — keep whatever cursor we last set + break; + + case WM_GETMINMAXINFO: { + auto* mmi = reinterpret_cast(lParam); + // Scale min window size by DPI so it matches the SDL-side minimum. + mmi->ptMinTrackSize.x = (LONG)(1024 * g_borderlessDpi); + mmi->ptMinTrackSize.y = (LONG)(720 * g_borderlessDpi); + return 0; + } + } + return CallWindowProcW(g_sdlWndProc, hwnd, msg, wParam, lParam); +} + +// Draw custom window-control buttons (minimize / maximize-restore / close) +// on the foreground draw list, and handle title-bar dragging. +static void renderBorderlessControls(SDL_Window* window, HWND /*hwnd*/, + dragonx::App& app) +{ + ImGuiIO& io = ImGui::GetIO(); + // Use the main viewport's foreground draw list so buttons always render + // on the primary window (not on a secondary viewport that has focus). + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImDrawList* fg = ImGui::GetForegroundDrawList(vp); + float captionH = ImGui::GetFrameHeight(); // same height as menu bar + float displayW = io.DisplaySize.x; + + // DPI scale factor for borderless controls + float dp = dragonx::ui::Layout::dpiScale(); + + // With multi-viewport, draw-list coordinates and io.MousePos are in + // OS screen-space. Offset all positions by the main viewport origin. + const float ox = vp->Pos.x; + const float oy = vp->Pos.y; + + const float btnW = 46.0f * dp; + const float btnH = captionH; + float closeX = ox + displayW - btnW; + float maxX = closeX - btnW; + float minX = maxX - btnW; + ImVec2 mp = io.MousePos; + bool click = ImGui::IsMouseClicked(ImGuiMouseButton_Left); + + const auto& themeS = dragonx::ui::schema::UI(); + ImU32 wcHover = themeS.resolveColor("var(--window-control-hover)", IM_COL32(255, 255, 255, 30)); + ImU32 wcIcon = themeS.resolveColor("var(--window-control)", IM_COL32(255, 255, 255, 200)); + ImU32 wcClose = themeS.resolveColor("var(--window-close-hover)", IM_COL32(232, 17, 35, 200)); + + // Icon glyph half-size and line thickness, scaled by DPI + const float iconHalf = 5.0f * dp; + const float lineThk = 1.0f * dp; + + // --- Minimize button --- + { + ImVec2 p0(minX, oy), p1(minX + btnW, oy + btnH); + bool hov = (mp.x >= p0.x && mp.x < p1.x && mp.y >= p0.y && mp.y < p1.y); + if (hov) fg->AddRectFilled(p0, p1, wcHover); + float cy = oy + btnH * 0.5f, lx = minX + btnW * 0.5f - iconHalf; + fg->AddLine(ImVec2(lx, cy), ImVec2(lx + iconHalf * 2.0f, cy), + wcIcon, lineThk); + if (hov && click) SDL_MinimizeWindow(window); + } + + // --- Maximize / Restore button --- + { + ImVec2 p0(maxX, oy), p1(maxX + btnW, oy + btnH); + bool hov = (mp.x >= p0.x && mp.x < p1.x && mp.y >= p0.y && mp.y < p1.y); + if (hov) fg->AddRectFilled(p0, p1, wcHover); + bool maximized = (SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) != 0; + float cx = maxX + btnW * 0.5f, cy = oy + btnH * 0.5f; + if (maximized) { + float s1 = 4.0f * dp, s2 = 3.0f * dp; + float s3 = 2.0f * dp, s4 = 5.0f * dp; + fg->AddRect(ImVec2(cx - s1, cy - s2), ImVec2(cx + s2, cy + s1), + wcIcon, 0, 0, lineThk); + fg->AddRect(ImVec2(cx - s3, cy - s4), ImVec2(cx + s4, cy + s3), + wcIcon, 0, 0, lineThk); + } else { + fg->AddRect(ImVec2(cx - iconHalf, cy - iconHalf + dp), + ImVec2(cx + iconHalf, cy + iconHalf - dp), + wcIcon, 0, 0, lineThk); + } + if (hov && click) { + if (maximized) SDL_RestoreWindow(window); + else SDL_MaximizeWindow(window); + } + } + + // --- Close button --- + { + ImVec2 p0(closeX, oy), p1(closeX + btnW, oy + btnH); + bool hov = (mp.x >= p0.x && mp.x < p1.x && mp.y >= p0.y && mp.y < p1.y); + if (hov) fg->AddRectFilled(p0, p1, wcClose); + float cx = closeX + btnW * 0.5f, cy = oy + btnH * 0.5f; + fg->AddLine(ImVec2(cx - iconHalf, cy - iconHalf), + ImVec2(cx + iconHalf, cy + iconHalf), + wcIcon, lineThk); + fg->AddLine(ImVec2(cx + iconHalf, cy - iconHalf), + ImVec2(cx - iconHalf, cy + iconHalf), + wcIcon, lineThk); + if (hov && click) app.beginShutdown(); + } + + // --- Update caption-zone state for WM_NCHITTEST --- + // WM_NCHITTEST uses client-local coordinates, so subtract viewport origin. + g_captionHeight = captionH; + g_captionBtnStartX = minX - ox; + g_captionImGuiHover = ImGui::IsAnyItemHovered() || ImGui::IsAnyItemActive(); + g_borderlessDpi = dp; +} + +#endif // DRAGONX_USE_DX11 + +// Forward declarations +static bool InitSDL(); +#ifdef DRAGONX_USE_DX11 +static bool InitImGui(SDL_Window* window, dragonx::platform::DX11Context& dx); +static void Shutdown(SDL_Window* window, dragonx::platform::DX11Context& dx); +#else +static bool InitImGui(SDL_Window* window, SDL_GLContext gl_context); +static void Shutdown(SDL_Window* window, SDL_GLContext gl_context); +#endif + +// Global single instance lock +static dragonx::util::SingleInstance g_single_instance("obsidiandragon"); + +// Check for payment URI in command line args +static std::string findPaymentURI(int argc, char* argv[]) +{ + for (int i = 1; i < argc; i++) { + if (dragonx::util::isPaymentURI(argv[i])) { + return argv[i]; + } + } + return ""; +} + +int main(int argc, char* argv[]) +{ + // Ensure ObsidianDragon config directory exists early (before any file I/O) + { + std::string odDir = dragonx::util::Platform::getObsidianDragonDir(); + std::error_code ec; + std::filesystem::create_directories(odDir, ec); + } + +#ifdef _WIN32 + // Redirect stdout/stderr to a log file so diagnostic output is visible + // even when built as a GUI app (WIN32_EXECUTABLE hides the console). + { + std::string logPath = (std::filesystem::path(dragonx::util::Platform::getObsidianDragonDir()) / "dragonx-debug.log").string(); + freopen(logPath.c_str(), "w", stdout); + freopen(logPath.c_str(), "a", stderr); + } + // Install crash handler for diagnostics + SetUnhandledExceptionFilter(CrashHandler); +#endif + + // Check for payment URI in command line + std::string pendingURI = findPaymentURI(argc, argv); + + DEBUG_LOGF("%s v%s\n", DRAGONX_APP_NAME, DRAGONX_VERSION); + DEBUG_LOGF("Built with Dear ImGui %s\n", IMGUI_VERSION); + fflush(stdout); + + // Check for existing instance + if (!g_single_instance.tryLock()) { + fprintf(stderr, "Another instance of ObsidianDragon is already running.\n"); + DEBUG_LOGF("Please close the existing instance first.\n"); + return 1; + } + + // Initialize SDL + if (!InitSDL()) { + fprintf(stderr, "Failed to initialize SDL!\n"); + return 1; + } + + // Load saved window size early (before window creation, before App exists). + // Settings are loaded again later in app.init(), this is just for the size. + int savedWinW = 1200, savedWinH = 720; + { + dragonx::config::Settings earlySettings; + if (earlySettings.load()) { + int sw = earlySettings.getWindowWidth(); + int sh = earlySettings.getWindowHeight(); + if (sw >= 1024 && sh >= 720) { + savedWinW = sw; + savedWinH = sh; + DEBUG_LOGF("Restored window size from settings: %dx%d\n", sw, sh); + } + } + } + + // --------------------------------------------------------------- + // Platform-specific window creation and graphics context + // --------------------------------------------------------------- +#ifdef DRAGONX_USE_DX11 + // DirectX 11 path (Windows) + // + // We create the native Win32 HWND ourselves so we can set + // WS_EX_NOREDIRECTIONBITMAP at creation time. This style MUST be + // present when the window is first created -- setting it later with + // SetWindowLongPtrW does NOT reliably release the opaque redirection + // surface that DWM allocates. Without it, the legacy redirection + // surface paints over our transparent DirectComposition visual. + // This is the same approach Windows Terminal uses. + + // Register a minimal window class + WNDCLASSEXW wc = {}; + wc.cbSize = sizeof(WNDCLASSEXW); + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = DefWindowProcW; + wc.hInstance = GetModuleHandleW(nullptr); + wc.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); // IDC_ARROW + // Load application icon from .exe resources (.rc embeds IDI_ICON1 = ordinal 1) + wc.hIcon = LoadIconW(wc.hInstance, MAKEINTRESOURCEW(1)); + wc.hIconSm = (HICON)LoadImageW(wc.hInstance, MAKEINTRESOURCEW(1), + IMAGE_ICON, + GetSystemMetrics(SM_CXSMICON), + GetSystemMetrics(SM_CYSMICON), + LR_DEFAULTCOLOR); + wc.lpszClassName = L"ObsidianDragon"; + RegisterClassExW(&wc); + + // Compute centered position including frame + // Use saved window size from settings if available, otherwise default + int winW = savedWinW, winH = savedWinH; + DWORD dwStyle = WS_OVERLAPPEDWINDOW; + DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_NOREDIRECTIONBITMAP; + RECT wr = {0, 0, winW, winH}; + AdjustWindowRectEx(&wr, dwStyle, FALSE, dwExStyle); + int adjW = wr.right - wr.left; + int adjH = wr.bottom - wr.top; + int posX = (GetSystemMetrics(SM_CXSCREEN) - adjW) / 2; + int posY = (GetSystemMetrics(SM_CYSCREEN) - adjH) / 2; + + HWND nativeHwnd = CreateWindowExW( + dwExStyle, L"ObsidianDragon", + L"ObsidianDragon", + dwStyle, + posX, posY, adjW, adjH, + nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); + if (!nativeHwnd) { + fprintf(stderr, "Failed to create native Win32 window (error %lu)\n", GetLastError()); + SDL_Quit(); + return 1; + } + DEBUG_LOGF("Native HWND created with WS_EX_NOREDIRECTIONBITMAP\n"); + // Don't show yet — wait until borderless subclass is installed + // so the window appears without a visible native title bar. + + // Explicitly set the window icon on the HWND for taskbar + Alt-Tab. + // The WNDCLASSEXW already sets hIcon/hIconSm, but WM_SETICON ensures + // the shell picks up the icon even for borderless windows. + { + HINSTANCE hInst = GetModuleHandleW(nullptr); + HICON bigIcon = LoadIconW(hInst, MAKEINTRESOURCEW(1)); + HICON smIcon = (HICON)LoadImageW(hInst, MAKEINTRESOURCEW(1), + IMAGE_ICON, + GetSystemMetrics(SM_CXSMICON), + GetSystemMetrics(SM_CYSMICON), + LR_DEFAULTCOLOR); + if (bigIcon) SendMessageW(nativeHwnd, WM_SETICON, ICON_BIG, (LPARAM)bigIcon); + if (smIcon) SendMessageW(nativeHwnd, WM_SETICON, ICON_SMALL, (LPARAM)smIcon); + DEBUG_LOGF("Taskbar icon set from .exe resource (big=%p small=%p)\n", + (void*)bigIcon, (void*)smIcon); + } + + // Wrap the native HWND with SDL for event handling + ImGui integration. + // SDL_WINDOW_TRANSPARENT triggers DwmEnableBlurBehindWindow internally, + // which is another signal to DWM to respect per-pixel alpha. + SDL_PropertiesID createProps = SDL_CreateProperties(); + SDL_SetPointerProperty(createProps, SDL_PROP_WINDOW_CREATE_WIN32_HWND_POINTER, (void*)nativeHwnd); + SDL_SetBooleanProperty(createProps, SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN, true); + SDL_SetBooleanProperty(createProps, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); + SDL_SetBooleanProperty(createProps, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true); + SDL_SetStringProperty(createProps, SDL_PROP_WINDOW_CREATE_TITLE_STRING, DRAGONX_APP_NAME); + SDL_SetNumberProperty(createProps, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, winW); + SDL_SetNumberProperty(createProps, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, winH); + SDL_Window* window = SDL_CreateWindowWithProperties(createProps); + SDL_DestroyProperties(createProps); + if (window == nullptr) { + fprintf(stderr, "Error: SDL_CreateWindowWithProperties(): %s\n", SDL_GetError()); + DestroyWindow(nativeHwnd); + SDL_Quit(); + return 1; + } + DEBUG_LOGF("SDL window wrapping native HWND (external)\n"); + + // Subclass for borderless window (removes native title bar). + // SDL has already installed its own WndProc; we save it and chain to it. + g_sdlWndProc = (WNDPROC)GetWindowLongPtrW(nativeHwnd, GWLP_WNDPROC); + SetWindowLongPtrW(nativeHwnd, GWLP_WNDPROC, (LONG_PTR)BorderlessWndProc); + // Resize to intended client dimensions (no frame/title-bar overhead) + // and trigger a frame recalculation so WM_NCCALCSIZE fires. + SetWindowPos(nativeHwnd, nullptr, 0, 0, winW, winH, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER); + ShowWindow(nativeHwnd, SW_SHOW); + UpdateWindow(nativeHwnd); + DEBUG_LOGF("Borderless window: native title bar removed\n"); + + // Initialize DirectX 11 context with DXGI alpha swap chain + dragonx::platform::DX11Context dx; + if (!dx.init(window)) { + fprintf(stderr, "Error: Failed to initialize DirectX 11 context\n"); + SDL_DestroyWindow(window); + SDL_Quit(); + return 1; + } + DEBUG_LOGF("DirectX 11 rendering backend initialized\n"); + fflush(stdout); + + bool backdrop_active = false; + +#ifdef _WIN32 + // Transparency pipeline: + // 1) WS_EX_NOREDIRECTIONBITMAP (set at HWND creation) + // 2) DirectComposition swap chain with DXGI_ALPHA_MODE_PREMULTIPLIED + // 3) DwmEnableBlurBehindWindow with full-window region for blur + // 4) On Win11 22H2+: Acrylic (DWMSBT_TRANSIENTWINDOW) for modern blur + // + // NOTE: Mica/MicaAlt (DWMSBT_MAINWINDOW / DWMSBT_TABBEDWINDOW) are + // opaque materials and must NOT be used — they fill the entire window + // with a wallpaper-derived color. Acrylic is the correct choice: it + // provides gaussian blur of the desktop behind the window. + if (dx.hasAlphaCompositing()) { + backdrop_active = true; + dragonx::ui::material::SetBackdropActive(true); + + HWND hwnd_blur = (HWND)SDL_GetPointerProperty( + SDL_GetWindowProperties(window), + SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); + if (hwnd_blur) { + // Override SDL's zero-area blur region with a full-window blur. + // This gives DWM the signal to blur everything behind our window. + HRGN blurRgn = CreateRectRgn(0, 0, -1, -1); // full window + DWM_BLURBEHIND bb = {}; + bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; + bb.fEnable = TRUE; + bb.hRgnBlur = blurRgn; + HRESULT hr_blur = DwmEnableBlurBehindWindow(hwnd_blur, &bb); + DeleteObject(blurRgn); + DEBUG_LOGF("DwmEnableBlurBehindWindow (full region): 0x%08lx\n", hr_blur); + + // On Windows 11 22H2+, also enable Acrylic for nicer modern blur + auto ver = dragonx::platform::getWindowsVersion(); + if (ver.build >= 22621) { + // Signal to DWM that we handle our own frame rendering. + // Use {0,0,1,0} (1 pixel top) instead of {-1,-1,-1,-1} + // because full-window margins cause DWM to render its own + // caption buttons (min/max/close) on top of ours. + // WM_NCCALCSIZE returning 0 already extends the client area + // to the full window, which satisfies the system backdrop + // requirement. The 1-pixel top margin is enough to keep + // DWM's shadow and rounded corners on Win11. + MARGINS margins = {0, 0, 1, 0}; + DwmExtendFrameIntoClientArea(hwnd_blur, &margins); + + // Acrylic = blurred, semi-transparent desktop view + // (NOT Mica which is opaque) + DWORD backdrop = 3; // DWMSBT_TRANSIENTWINDOW = Acrylic + HRESULT hr_acr = DwmSetWindowAttribute(hwnd_blur, 38, + &backdrop, sizeof(backdrop)); + DEBUG_LOGF("DWM Acrylic (DWMSBT_TRANSIENTWINDOW): 0x%08lx\n", hr_acr); + + BOOL useDarkMode = TRUE; + DwmSetWindowAttribute(hwnd_blur, 20, + &useDarkMode, sizeof(useDarkMode)); + } + } + DEBUG_LOGF("DX11: Alpha compositing active with blur\n"); + fflush(stdout); + } else { + DEBUG_LOGF("DX11: No alpha compositing - window is opaque\n"); + } +#endif + + // Initialize ImGui with DX11 backend + if (!InitImGui(window, dx)) { + fprintf(stderr, "Failed to initialize ImGui!\n"); + Shutdown(window, dx); + return 1; + } + + // Initialize acrylic effects system (DX11 backend) + if (dragonx::ui::effects::ImGuiAcrylic::Init()) { + DEBUG_LOGF("Acrylic effects initialized (DX11)\n"); + } else { + DEBUG_LOGF("Acrylic effects not available on DX11 (will use fallback colors)\n"); + } + +#else + // OpenGL path (Linux) + // GL 3.0 + GLSL 130 + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); + 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, 0); + + // Create window with graphics context + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); + + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_TRANSPARENT); + SDL_Window* window = SDL_CreateWindow( + DRAGONX_APP_NAME, + savedWinW, savedWinH, + window_flags + ); + + if (window == nullptr) { + // Retry without transparency if compositor doesn't support it + window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY); + window = SDL_CreateWindow( + DRAGONX_APP_NAME, + savedWinW, savedWinH, + window_flags + ); + } + + if (window == nullptr) { + fprintf(stderr, "Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return 1; + } + + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_SetWindowMinimumSize(window, 1024, 720); + SDL_GLContext gl_context = SDL_GL_CreateContext(window); + if (gl_context == nullptr) { + fprintf(stderr, "Error: SDL_GL_CreateContext(): %s\n", SDL_GetError()); + return 1; + } + + SDL_GL_MakeCurrent(window, gl_context); + SDL_GL_SetSwapInterval(1); // Enable vsync + + bool backdrop_active = false; + + // Check if the compositor granted window transparency + if (SDL_GetWindowFlags(window) & SDL_WINDOW_TRANSPARENT) { + backdrop_active = true; + dragonx::ui::material::SetBackdropActive(true); + DEBUG_LOGF("Window transparency enabled by compositor\n"); + } + +#ifdef DRAGONX_HAS_GLAD + // Initialize GLAD - load OpenGL function pointers + int glad_version = gladLoadGL((GLADloadfunc)SDL_GL_GetProcAddress); + if (!glad_version) { + fprintf(stderr, "Error: Failed to initialize GLAD (OpenGL loader)\n"); + return 1; + } + DEBUG_LOGF("GLAD initialized - OpenGL %d.%d loaded\n", GLAD_VERSION_MAJOR(glad_version), GLAD_VERSION_MINOR(glad_version)); + + // Initialize acrylic effects system + if (dragonx::ui::effects::ImGuiAcrylic::Init()) { + DEBUG_LOGF("Acrylic effects initialized\n"); + // Enable backdrop so glass panels use acrylic blur + if (!backdrop_active) { + backdrop_active = true; + dragonx::ui::material::SetBackdropActive(true); + DEBUG_LOGF("Backdrop activated for acrylic effects\n"); + } + } else { + DEBUG_LOGF("Acrylic effects not available (will use fallback colors)\n"); + } + +#endif + + // Initialize ImGui with OpenGL backend + if (!InitImGui(window, gl_context)) { + fprintf(stderr, "Failed to initialize ImGui!\n"); + Shutdown(window, gl_context); + return 1; + } +#endif // DRAGONX_USE_DX11 + + // Set window icon from logo_ObsidianDragon.png + { + std::string iconPath = dragonx::util::getExecutableDirectory() + "/res/img/logos/logo_ObsidianDragon.png"; + int iconW = 0, iconH = 0; + unsigned char* iconPixels = dragonx::util::LoadRawPixelsFromFile(iconPath.c_str(), &iconW, &iconH); + if (!iconPixels) { + // Try embedded resource fallback (Windows single-file distribution) + const auto* iconRes = dragonx::resources::getEmbeddedResource("logo_ObsidianDragon.png"); + if (iconRes && iconRes->data && iconRes->size > 0) { + iconPixels = dragonx::util::LoadRawPixelsFromMemory(iconRes->data, iconRes->size, &iconW, &iconH); + } + } + if (iconPixels) { + SDL_Surface* iconSurface = SDL_CreateSurfaceFrom(iconW, iconH, + SDL_PIXELFORMAT_RGBA32, iconPixels, iconW * 4); + if (iconSurface) { + SDL_SetWindowIcon(window, iconSurface); + SDL_DestroySurface(iconSurface); + DEBUG_LOGF("Window icon set (%dx%d)\n", iconW, iconH); + } + dragonx::util::FreeRawPixels(iconPixels); + } else { + DEBUG_LOGF("Warning: Could not load window icon from %s or embedded\n", iconPath.c_str()); + } + } + + // Apply DragonX Material Design theme + dragonx::ui::SetDragonXMaterialTheme(); + + // Scale ImGui style sizes (padding, rounding, scrollbar, etc.) by the + // display DPI factor. On Windows Per-Monitor DPI v2, SDL3 works in + // physical pixels and DisplayFramebufferScale is 1.0, so we must + // manually scale both fonts (done in Typography::load) and style. + // The window is also resized by dpiScale below so everything fits. + float currentDpiScale = dragonx::ui::material::Typography::instance().getDpiScale(); +#ifdef DRAGONX_USE_DX11 + g_borderlessDpi = currentDpiScale; +#endif + if (currentDpiScale > 1.01f) { + ImGui::GetStyle().ScaleAllSizes(currentDpiScale); + DEBUG_LOGF("Scaled ImGui style sizes by %.2f for DPI awareness\n", currentDpiScale); + } + + // If we're starting on a HiDPI display, scale the window so the UI + // appears the same physical size as on a 100% display. + if (currentDpiScale > 1.01f) { + int curW = 0, curH = 0; + SDL_GetWindowSize(window, &curW, &curH); + int newW = (int)(curW * currentDpiScale); + int newH = (int)(curH * currentDpiScale); + + // Clamp to the display's work area so the window fits on screen. + SDL_DisplayID did = SDL_GetDisplayForWindow(window); + if (did) { + SDL_Rect usable; + if (SDL_GetDisplayUsableBounds(did, &usable)) { + newW = std::min(newW, usable.w); + newH = std::min(newH, usable.h); + } + } + + SDL_SetWindowSize(window, newW, newH); + SDL_SetWindowMinimumSize(window, + (int)(1024 * currentDpiScale), + (int)(720 * currentDpiScale)); + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + DEBUG_LOGF("HiDPI startup: window resized %dx%d -> %dx%d (scale %.2f)\n", + curW, curH, newW, newH, currentDpiScale); + } + + // Create application instance + dragonx::App app; + if (!app.init()) { + fprintf(stderr, "Failed to initialize application!\n"); +#ifdef DRAGONX_USE_DX11 + Shutdown(window, dx); +#else + Shutdown(window, gl_context); +#endif + return 1; + } + + // Activate backdrop transparency if the skin system loaded a background + // image during app.init() → SkinManager::setActiveSkin(). + if (app.getGradientTexture() != 0 && !backdrop_active) { + backdrop_active = true; + dragonx::ui::material::SetBackdropActive(true); + // Re-apply TOML-based colors with the new backdrop alpha values. + // Must NOT call SetDragonXMaterialTheme() here — that would clobber + // the active TOML palette with hardcoded C++ DragonX colors, causing + // a visual shift when the user later cycles themes via Ctrl+Arrow. + dragonx::ui::schema::UISchema::instance().reapplyColorsToImGui(); + } + + // Initialize performance profiler — writes to /perf.log + { + std::string perfPath = (std::filesystem::path( + dragonx::util::Platform::getObsidianDragonDir()) / "perf.log").string(); + dragonx::util::PerfLog::instance().init(perfPath); + } + + // Handle pending payment URI from command line + if (!pendingURI.empty()) { + DEBUG_LOGF("Processing payment URI: %s\n", pendingURI.c_str()); + app.handlePaymentURI(pendingURI); + } + + // ================================================================ + // Live-resize support (Linux/X11) + // On X11, the window manager runs a modal loop during drag-resize, + // blocking SDL_PollEvent. We install an event watcher that fires + // immediately from the WM callback and performs a full render cycle + // so the UI redraws in real time while the window is being resized. + // ================================================================ + struct ResizeCtx { + SDL_Window* window; + dragonx::App* app; + bool backdrop_active; +#ifdef DRAGONX_USE_DX11 + dragonx::platform::DX11Context* dx; +#else + SDL_GLContext gl_context; +#endif + }; + ResizeCtx resizeCtx; + resizeCtx.window = window; + resizeCtx.app = &app; + resizeCtx.backdrop_active = backdrop_active; +#ifdef DRAGONX_USE_DX11 + resizeCtx.dx = &dx; +#else + resizeCtx.gl_context = gl_context; +#endif + + auto resizeWatcher = [](void* userdata, SDL_Event* event) -> bool { + if (event->type != SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED && + event->type != SDL_EVENT_WINDOW_RESIZED) + return true; + + auto* ctx = static_cast(userdata); + if (event->window.windowID != SDL_GetWindowID(ctx->window)) + return true; + + // Avoid re-entrancy + static bool in_resize_render = false; + if (in_resize_render) return true; + in_resize_render = true; + +#ifdef DRAGONX_USE_DX11 + ctx->dx->resize(event->window.data1, event->window.data2); + ImGui_ImplDX11_NewFrame(); +#else + SDL_GL_MakeCurrent(ctx->window, ctx->gl_context); + ImGui_ImplOpenGL3_NewFrame(); +#endif + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // Background gradient + { + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImDrawList* bgDL = ImGui::GetBackgroundDrawList(); + ImVec2 p0 = vp->Pos; + ImVec2 p1 = ImVec2(vp->Pos.x + vp->Size.x, vp->Pos.y + vp->Size.y); + ImTextureID curGradTex2 = ctx->app->getGradientTexture(); + float winOp2 = ctx->app->settings() ? ctx->app->settings()->getWindowOpacity() : 1.0f; + + // Scale only background layer alpha by window opacity so the + // desktop shows through while UI elements stay fully opaque. + auto scaleA2 = [&](ImU32 col) -> ImU32 { + uint8_t a = (col >> IM_COL32_A_SHIFT) & 0xFF; + a = (uint8_t)(a * winOp2); + return (col & ~(0xFFu << IM_COL32_A_SHIFT)) | ((ImU32)a << IM_COL32_A_SHIFT); + }; + + if (curGradTex2 != 0) { + const auto& S1 = dragonx::ui::schema::UI(); + ImU32 baseTop1 = S1.resolveColor(S1.drawElement("backdrop", "base-color-top").color, IM_COL32(18,28,65,200)); + ImU32 baseBottom1 = S1.resolveColor(S1.drawElement("backdrop", "base-color-bottom").color, IM_COL32(8,12,35,200)); + int tintAlpha1 = (int)S1.drawElement("backdrop", "texture-tint-alpha").size; + if (tintAlpha1 <= 0) tintAlpha1 = 140; + bgDL->AddRectFilledMultiColor(p0, p1, scaleA2(baseTop1), scaleA2(baseTop1), + scaleA2(baseBottom1), scaleA2(baseBottom1)); + int scaledTA1 = (int)(tintAlpha1 * winOp2); + ImU32 tintCol1 = IM_COL32(255, 255, 255, scaledTA1); + bgDL->AddImage(curGradTex2, p0, p1, ImVec2(0, 0), ImVec2(1, 1), tintCol1); + } else if (ctx->backdrop_active) { + const auto& S = dragonx::ui::schema::UI(); + auto bde = [&](const char* key, float fb) { + float v = S.drawElement("backdrop", key).size; + return v >= 0 ? v : fb; + }; + ImU32 colTop = IM_COL32((int)bde("gradient-top-r",8), (int)bde("gradient-top-g",12), + (int)bde("gradient-top-b",28), (int)(bde("gradient-top-a",80) * winOp2)); + ImU32 colBottom = IM_COL32((int)bde("gradient-bottom-r",6), (int)bde("gradient-bottom-g",8), + (int)bde("gradient-bottom-b",18), (int)(bde("gradient-bottom-a",60) * winOp2)); + bgDL->AddRectFilledMultiColor(p0, p1, colTop, colTop, colBottom, colBottom); + } + // Acrylic capture callback — must fire BEFORE the noise + // overlay so the noise grain is not captured and blurred + // into the glass cards. + auto captureCb2 = dragonx::ui::effects::ImGuiAcrylic::GetBackgroundCaptureCallback(); + if (captureCb2) { + bgDL->AddCallback(captureCb2, nullptr); + bgDL->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + } + + // WindowBg alpha stays at its base theme value — NOT scaled + // by window opacity. Only the background gradient/texture + // layers are scaled so the desktop shows through while UI + // elements (cards, text, buttons) remain fully readable. + if (ctx->backdrop_active || curGradTex2 != 0) { + const auto& S4 = dragonx::ui::schema::UI(); + float baseBgAlpha2 = S4.drawElement("backdrop", "background-alpha").sizeOr(0.40f); + ImGui::GetStyle().Colors[ImGuiCol_WindowBg].w = baseBgAlpha2; + } + + } + + ImGuiIO& io = ImGui::GetIO(); + dragonx::ui::effects::ImGuiAcrylic::BeginFrame( + (int)io.DisplaySize.x, (int)io.DisplaySize.y); + + ctx->app->update(); + ctx->app->render(); + + ImGui::Render(); +#ifdef DRAGONX_USE_DX11 + ctx->dx->ensureSize(); + ID3D11RenderTargetView* rtv = ctx->dx->renderTargetView(); + ctx->dx->deviceContext()->OMSetRenderTargets(1, &rtv, nullptr); + { + float wo = ctx->app->settings() ? ctx->app->settings()->getWindowOpacity() : 1.0f; + bool opq = dragonx::ui::effects::isLowSpecMode() || wo >= 0.99f; + bool eb = (ctx->backdrop_active || ctx->app->getGradientTexture() != 0) && !opq; + ctx->dx->clear(0.0f, 0.0f, 0.0f, eb ? 0.0f : 1.0f); + } + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + ctx->dx->present(0); // immediate present during resize +#else + glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); + { + float wo = ctx->app->settings() ? ctx->app->settings()->getWindowOpacity() : 1.0f; + bool opq = dragonx::ui::effects::isLowSpecMode() || wo >= 0.99f; + bool eb = (ctx->backdrop_active || ctx->app->getGradientTexture() != 0) && !opq; + glClearColor(0.0f, 0.0f, 0.0f, eb ? 0.0f : 1.0f); + } + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + SDL_GL_SwapWindow(ctx->window); +#endif + + in_resize_render = false; + return true; + }; + + SDL_AddEventWatch(resizeWatcher, &resizeCtx); + + // Main loop + bool running = true; + bool needsRedraw = true; // P6: Start with a full redraw + auto lastPeriodicFrame = std::chrono::steady_clock::now(); + + // Per-scale saved window sizes for DPI round-trips. + // Each entry maps scale-percentage (100, 125, 150, 200, …) to the + // physical pixel size the user had at that scale. When transitioning + // to a scale we've visited before the stored size is restored, so + // resizing on a 200% screen doesn't clobber the 100% size. + std::map> savedSizeForScale; + bool dpiResizePending = false; + // Track last known window size at the current DPI scale. + // Updated on user-initiated resizes (not DPI auto-resizes). + // When DISPLAY_SCALE_CHANGED fires, SDL_GetWindowSize() already + // returns the auto-resized value, so we use these instead. + int lastKnownW = 0, lastKnownH = 0; + // Deferred resize: SDL_SetWindowSize may not stick when the user + // is dragging the window between monitors (Windows modal drag loop + // overrides SetWindowPos). We retry for several frames. + int dpiTargetW = 0, dpiTargetH = 0; + int dpiResizeRetries = 0; + { + float s = dragonx::ui::material::Typography::instance().getDpiScale(); + int w = 0, h = 0; + SDL_GetWindowSize(window, &w, &h); + int pct = (int)lroundf(s * 100.0f); + savedSizeForScale[pct] = {w, h}; + lastKnownW = w; + lastKnownH = h; + } + + while (running) { + // Deferred DPI resize: if a previous DPI transition set a target + // size that SDL_SetWindowSize didn't achieve (e.g. because the + // window was being dragged), retry until it sticks. + if (dpiResizeRetries > 0) { + int curW = 0, curH = 0; + SDL_GetWindowSize(window, &curW, &curH); + if (curW != dpiTargetW || curH != dpiTargetH) { + dpiResizePending = true; + SDL_SetWindowSize(window, dpiTargetW, dpiTargetH); + DEBUG_LOGF(" Deferred resize retry %d: %dx%d -> %dx%d\n", + dpiResizeRetries, curW, curH, dpiTargetW, dpiTargetH); + } else { + // Size matches — done + dpiResizeRetries = 0; + } + --dpiResizeRetries; + needsRedraw = true; + } + + // P6: Idle rendering — sleep if nothing needs redrawing + if (!needsRedraw) { + // Wait up to 200ms for user input or wake event + SDL_Event waitEvent; + if (SDL_WaitEventTimeout(&waitEvent, 200)) { + ImGui_ImplSDL3_ProcessEvent(&waitEvent); + if (waitEvent.type == SDL_EVENT_QUIT) { + app.beginShutdown(); + } + if (waitEvent.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && + waitEvent.window.windowID == SDL_GetWindowID(window)) { + app.beginShutdown(); + } +#ifdef DRAGONX_USE_DX11 + if (waitEvent.type == SDL_EVENT_WINDOW_RESIZED && + waitEvent.window.windowID == SDL_GetWindowID(window)) { + dx.resize(waitEvent.window.data1, waitEvent.window.data2); + } +#endif + // Update saved size for current scale on user-initiated resize. + // DPI-related resizes (from WM_DPICHANGED or our own SDL_SetWindowSize) + // are skipped so they don't overwrite the saved size. + if (waitEvent.type == SDL_EVENT_WINDOW_RESIZED && + waitEvent.window.windowID == SDL_GetWindowID(window)) { + float actualScale = SDL_GetWindowDisplayScale(window); + float storedScale = dragonx::ui::material::Typography::instance().getDpiScale(); + bool isDpiResize = dpiResizePending || + std::abs(actualScale - storedScale) > 0.01f; + if (dpiResizePending) dpiResizePending = false; + if (!isDpiResize) { + int pct = (int)lroundf(storedScale * 100.0f); + savedSizeForScale[pct] = {waitEvent.window.data1, waitEvent.window.data2}; + lastKnownW = waitEvent.window.data1; + lastKnownH = waitEvent.window.data2; + } + } + // Handle DPI change that arrived while idle (same logic as poll loop) + if (waitEvent.type == SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED && + waitEvent.window.windowID == SDL_GetWindowID(window)) { + float newScale = SDL_GetWindowDisplayScale(window); + if (newScale <= 0.0f) newScale = 1.0f; + auto& typo = dragonx::ui::material::Typography::instance(); + float oldScale = typo.getDpiScale(); + if (std::abs(newScale - oldScale) > 0.01f) { + float ratio = newScale / oldScale; + DEBUG_LOGF("Display scale changed (idle): %.2f -> %.2f (ratio %.2f)\n", + oldScale, newScale, ratio); + ImGuiIO& io = ImGui::GetIO(); + +#ifdef DRAGONX_USE_DX11 + g_borderlessDpi = newScale; +#endif + + // Save the last known size (before auto-resize) under + // the OLD scale. We use lastKnownW/H instead of + // SDL_GetWindowSize() because by now WM_DPICHANGED + // may have already auto-resized the window. + { + int oldPct = (int)lroundf(oldScale * 100.0f); + savedSizeForScale[oldPct] = {lastKnownW, lastKnownH}; + DEBUG_LOGF(" Saved %dx%d for scale %d%%\n", + lastKnownW, lastKnownH, oldPct); + } + + // Compute new physical size: if we've been to this + // scale before, restore that exact size; otherwise + // proportionally scale from the current size. + int newPct = (int)lroundf(newScale * 100.0f); + int newW, newH; + auto it = savedSizeForScale.find(newPct); + if (it != savedSizeForScale.end()) { + newW = it->second.first; + newH = it->second.second; + } else { + // Use lastKnownW/H (pre-auto-resize) instead of + // SDL_GetWindowSize() which already reflects the + // WM_DPICHANGED auto-resize. + newW = (int)lroundf((float)lastKnownW * newScale / oldScale); + newH = (int)lroundf((float)lastKnownH * newScale / oldScale); + } + + // Clamp to the target display's work area so the + // window doesn't overflow a smaller/higher-density monitor. + SDL_DisplayID did = SDL_GetDisplayForWindow(window); + if (did) { + SDL_Rect usable; + if (SDL_GetDisplayUsableBounds(did, &usable)) { + newW = std::min(newW, usable.w); + newH = std::min(newH, usable.h); + } + } + + dpiResizePending = true; + SDL_SetWindowSize(window, newW, newH); + lastKnownW = newW; + lastKnownH = newH; + // Arm deferred retry — the SetWindowSize above may + // not stick if the user is mid-drag (modal loop). + dpiTargetW = newW; + dpiTargetH = newH; + dpiResizeRetries = 30; // retry for ~30 frames + SDL_SetWindowMinimumSize(window, + (int)(1024 * newScale), (int)(720 * newScale)); + + typo.reload(io, newScale); + ImGui::GetStyle() = ImGuiStyle(); + dragonx::ui::schema::UISchema::instance().reapplyColorsToImGui(); + if (newScale > 1.01f) { + ImGui::GetStyle().ScaleAllSizes(newScale); + } + } + } + needsRedraw = true; // Got an event — redraw + } + // Timeout expired: only redraw if there's actual work + if (!needsRedraw) { + auto now = std::chrono::steady_clock::now(); + auto sinceLast = std::chrono::duration_cast( + now - lastPeriodicFrame).count(); + + // Immediate triggers: async RPC results or visible notifications + bool hasImmediateWork = app.hasPendingRPCResults() + || dragonx::ui::Notifications::instance().hasActive(); + + // Periodic maintenance: fire refresh timers in app.update() + // Low-spec: every 5s; normal: every 2s + int periodMs = dragonx::ui::effects::isLowSpecMode() ? 5000 : 2000; + + if (hasImmediateWork || sinceLast >= periodMs) { + needsRedraw = true; + } else { + continue; // Nothing to do — go back to sleep + } + } + } + + // Poll remaining events + SDL_Event event; + while (SDL_PollEvent(&event)) { + ImGui_ImplSDL3_ProcessEvent(&event); + + if (event.type == SDL_EVENT_QUIT) { + app.beginShutdown(); + } + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && + event.window.windowID == SDL_GetWindowID(window)) { + app.beginShutdown(); + } +#ifdef DRAGONX_USE_DX11 + // Handle window resize for DX11 swap chain + if (event.type == SDL_EVENT_WINDOW_RESIZED && + event.window.windowID == SDL_GetWindowID(window)) { + dx.resize(event.window.data1, event.window.data2); + } +#endif + // Update saved size for current scale on user-initiated resize. + // DPI-related resizes (from WM_DPICHANGED or our own SDL_SetWindowSize) + // are skipped so they don't overwrite the saved size. + if (event.type == SDL_EVENT_WINDOW_RESIZED && + event.window.windowID == SDL_GetWindowID(window)) { + float actualScale = SDL_GetWindowDisplayScale(window); + float storedScale = dragonx::ui::material::Typography::instance().getDpiScale(); + bool isDpiResize = dpiResizePending || + std::abs(actualScale - storedScale) > 0.01f; + if (dpiResizePending) dpiResizePending = false; + if (!isDpiResize) { + int pct = (int)lroundf(storedScale * 100.0f); + savedSizeForScale[pct] = {event.window.data1, event.window.data2}; + lastKnownW = event.window.data1; + lastKnownH = event.window.data2; + } + } + // Handle DPI/display scale changes (e.g. window dragged to a + // different-DPI monitor, or user changes Windows scaling) + if (event.type == SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED && + event.window.windowID == SDL_GetWindowID(window)) { + float newScale = SDL_GetWindowDisplayScale(window); + if (newScale <= 0.0f) newScale = 1.0f; + auto& typo = dragonx::ui::material::Typography::instance(); + float oldScale = typo.getDpiScale(); + if (std::abs(newScale - oldScale) > 0.01f) { + float ratio = newScale / oldScale; + DEBUG_LOGF("Display scale changed: %.2f -> %.2f (ratio %.2f)\n", + oldScale, newScale, ratio); + ImGuiIO& io = ImGui::GetIO(); + +#ifdef DRAGONX_USE_DX11 + g_borderlessDpi = newScale; +#endif + + // Save the last known size (before auto-resize) under + // the OLD scale. We use lastKnownW/H instead of + // SDL_GetWindowSize() because by now WM_DPICHANGED + // may have already auto-resized the window. + { + int oldPct = (int)lroundf(oldScale * 100.0f); + savedSizeForScale[oldPct] = {lastKnownW, lastKnownH}; + DEBUG_LOGF(" Saved %dx%d for scale %d%%\n", + lastKnownW, lastKnownH, oldPct); + } + + // Compute new physical size: if we've been to this + // scale before, restore that exact size; otherwise + // proportionally scale from the current size. + int newPct = (int)lroundf(newScale * 100.0f); + int newW, newH; + auto it = savedSizeForScale.find(newPct); + if (it != savedSizeForScale.end()) { + newW = it->second.first; + newH = it->second.second; + } else { + // Use lastKnownW/H (pre-auto-resize) instead of + // SDL_GetWindowSize() which already reflects the + // WM_DPICHANGED auto-resize. + newW = (int)lroundf((float)lastKnownW * newScale / oldScale); + newH = (int)lroundf((float)lastKnownH * newScale / oldScale); + } + + // Clamp to the target display's work area so the + // window doesn't overflow a smaller/higher-density monitor. + SDL_DisplayID did = SDL_GetDisplayForWindow(window); + if (did) { + SDL_Rect usable; + if (SDL_GetDisplayUsableBounds(did, &usable)) { + newW = std::min(newW, usable.w); + newH = std::min(newH, usable.h); + } + } + + dpiResizePending = true; + SDL_SetWindowSize(window, newW, newH); + lastKnownW = newW; + lastKnownH = newH; + // Arm deferred retry — the SetWindowSize above may + // not stick if the user is mid-drag (modal loop). + dpiTargetW = newW; + dpiTargetH = newH; + dpiResizeRetries = 30; // retry for ~30 frames + SDL_SetWindowMinimumSize(window, + (int)(1024 * newScale), + (int)(720 * newScale)); + DEBUG_LOGF(" Window resized: %dx%d (scale %.2f, pct %d)\n", + newW, newH, newScale, newPct); + + // 2) Rebuild font atlas at the new DPI scale + typo.reload(io, newScale); + + // 3) Reset style → reapply base theme → scale by new DPI + ImGui::GetStyle() = ImGuiStyle(); + dragonx::ui::schema::UISchema::instance().reapplyColorsToImGui(); + if (newScale > 1.01f) { + ImGui::GetStyle().ScaleAllSizes(newScale); + } + + DEBUG_LOGF(" DPI transition complete\n"); + } + } + } + + // Check if window is minimized + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) { + // Still check shouldQuit while minimized to avoid hang + if (app.shouldQuit()) { + running = false; + } + SDL_Delay(10); + continue; + } + + // --- PerfLog: begin frame --- + dragonx::util::PerfLog::instance().beginFrame(); + + // Start the Dear ImGui frame + PERF_BEGIN(_perfNewFrame); +#ifdef DRAGONX_USE_DX11 + ImGui_ImplDX11_NewFrame(); +#else + ImGui_ImplOpenGL3_NewFrame(); +#endif + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + PERF_END("NewFrame", _perfNewFrame); + + PERF_BEGIN(_perfBackdrop); + // Draw background image overlay across the entire viewport. + // Uses theme-specified texture stretched to fill, with the + // programmatic gradient as fallback when texture isn't available. + { + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImDrawList* bgDL = ImGui::GetBackgroundDrawList(); + ImVec2 p0 = vp->Pos; + ImVec2 p1 = ImVec2(vp->Pos.x + vp->Size.x, vp->Pos.y + vp->Size.y); + + // Read the current gradient texture from the app each frame + // so hot-reloaded / skin-changed images are picked up immediately. + ImTextureID curGradTex = app.getGradientTexture(); + + // Window opacity: scale only background layer alpha so the + // desktop shows through while UI stays fully opaque. + float winOpacity = app.settings() ? app.settings()->getWindowOpacity() : 1.0f; + + bool lowSpec = dragonx::ui::effects::isLowSpecMode(); + + // Scale a single color's alpha channel by window opacity + auto scaleAlpha = [&](ImU32 col) -> ImU32 { + uint8_t a = (col >> IM_COL32_A_SHIFT) & 0xFF; + a = (uint8_t)(a * winOpacity); + return (col & ~(0xFFu << IM_COL32_A_SHIFT)) | ((ImU32)a << IM_COL32_A_SHIFT); + }; + + if (curGradTex != 0) { + // Base color gradient underneath the texture — read from ui.toml + const auto& S2 = dragonx::ui::schema::UI(); + ImU32 baseTop = S2.resolveColor(S2.drawElement("backdrop", "base-color-top").color, IM_COL32(18,28,65,200)); + ImU32 baseBottom = S2.resolveColor(S2.drawElement("backdrop", "base-color-bottom").color, IM_COL32(8,12,35,200)); + + if (lowSpec) { + // Low-spec: skip texture sampling — just draw the base gradient. + bgDL->AddRectFilledMultiColor(p0, p1, scaleAlpha(baseTop), scaleAlpha(baseTop), + scaleAlpha(baseBottom), scaleAlpha(baseBottom)); + } else { + int tintAlpha = (int)S2.drawElement("backdrop", "texture-tint-alpha").size; + if (tintAlpha <= 0) tintAlpha = 140; + + // Scale background gradient + texture tint alpha by + // window opacity — only affects the backdrop, not UI. + bgDL->AddRectFilledMultiColor(p0, p1, scaleAlpha(baseTop), scaleAlpha(baseTop), + scaleAlpha(baseBottom), scaleAlpha(baseBottom)); + int scaledTintAlpha = (int)(tintAlpha * winOpacity); + ImU32 tintCol = IM_COL32(255, 255, 255, scaledTintAlpha); + bgDL->AddImage(curGradTex, p0, p1, ImVec2(0, 0), ImVec2(1, 1), tintCol); + } + } else if (backdrop_active) { + // Programmatic gradient tint (fallback when texture unavailable) + const auto& S = dragonx::ui::schema::UI(); + auto bde = [&](const char* key, float fb) { + float v = S.drawElement("backdrop", key).size; + return v >= 0 ? v : fb; + }; + ImU32 colTop = IM_COL32((int)bde("gradient-top-r",8), (int)bde("gradient-top-g",12), + (int)bde("gradient-top-b",28), (int)(bde("gradient-top-a",80) * winOpacity)); + ImU32 colBottom = IM_COL32((int)bde("gradient-bottom-r",6), (int)bde("gradient-bottom-g",8), + (int)bde("gradient-bottom-b",18), (int)(bde("gradient-bottom-a",60) * winOpacity)); + bgDL->AddRectFilledMultiColor(p0, p1, colTop, colTop, colBottom, colBottom); + } + + // Insert acrylic capture callback BEFORE the noise overlay + // so the noise grain is not captured and blurred into the + // glass cards (the noise should only be a visual overlay). + // Skip in low-spec mode — acrylic is disabled so the FBO + // capture/blur callback is unnecessary GPU work. + if (!lowSpec) { + auto captureCb = dragonx::ui::effects::ImGuiAcrylic::GetBackgroundCaptureCallback(); + if (captureCb) { + bgDL->AddCallback(captureCb, nullptr); + bgDL->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + } + } + + // WindowBg alpha stays at its base theme value — NOT scaled + // by window opacity. Only the background gradient/texture + // layers fade so UI elements remain fully readable. + if (backdrop_active || curGradTex != 0) { + const auto& S3 = dragonx::ui::schema::UI(); + float baseBgAlpha = S3.drawElement("backdrop", "background-alpha").sizeOr(0.40f); + ImGui::GetStyle().Colors[ImGuiCol_WindowBg].w = baseBgAlpha; + } + + } + + PERF_END("Backdrop", _perfBackdrop); + + // Begin acrylic frame (update viewport dimensions) + // Skip in low-spec mode — acrylic is disabled, no need to track FBO sizes + ImGuiIO& io = ImGui::GetIO(); + if (!dragonx::ui::effects::isLowSpecMode()) { + dragonx::ui::effects::ImGuiAcrylic::BeginFrame( + (int)io.DisplaySize.x, (int)io.DisplaySize.y); + } + + // Update theme visual effects timing + dragonx::ui::effects::ThemeEffects::instance().beginFrame(); + // Propagate window opacity to theme effects so they fade with the + // backdrop while UI elements (cards, text, buttons) stay opaque. + { + float wo = app.settings() ? app.settings()->getWindowOpacity() : 1.0f; + dragonx::ui::effects::ThemeEffects::instance().setBackgroundOpacity(wo); + } + + // Reset smooth-scroll animation flag — ApplySmoothScroll() calls + // during this frame will set it back to true if still interpolating. + dragonx::ui::material::SmoothScrollAnimating() = false; + + // Always render normal UI + try { + PERF_BEGIN(_perfUpdate); + app.update(); + PERF_END("AppUpdate", _perfUpdate); + } catch (const std::exception& e) { + DEBUG_LOGF("[Main] app.update() threw: %s\n", e.what()); + } catch (...) { + DEBUG_LOGF("[Main] app.update() threw unknown exception\n"); + } + + // Background capture is now handled by the draw callback + // inserted into the BackgroundDrawList above. It fires + // during RenderDrawData() at exactly the right moment. + + try { + PERF_BEGIN(_perfRender); + app.render(); + PERF_END("AppRender", _perfRender); + } catch (const std::exception& e) { + DEBUG_LOGF("[Main] app.render() threw: %s\n", e.what()); + } catch (...) { + DEBUG_LOGF("[Main] app.render() threw unknown exception\n"); + } + + // Draw shutdown overlay on top of everything when shutting down + if (app.isShuttingDown()) { + app.renderShutdownScreen(); + } + +#ifdef DRAGONX_USE_DX11 + // Borderless title bar: window controls + drag handling + renderBorderlessControls(window, nativeHwnd, app); +#endif + + // Global cursor: show hand cursor when hovering any clickable widget + // (ImGui buttons don't change the cursor by default) + // Persist cursor for 2 extra frames to avoid flicker on Windows + // where g.HoveredId may clear briefly between frames. + { + ImGuiContext& g = *GImGui; + static ImGuiMouseCursor s_prevCursor = ImGuiMouseCursor_Arrow; + static int s_holdFrames = 0; + + bool isInputField = (g.InputTextState.ID != 0 && + g.InputTextState.ID == g.HoveredId); + if (g.MouseCursor == ImGuiMouseCursor_Arrow && g.HoveredId != 0 + && !(g.HoveredIdIsDisabled) && !isInputField) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + s_prevCursor = ImGuiMouseCursor_Hand; + s_holdFrames = 2; + } else if (s_holdFrames > 0 && g.MouseCursor == ImGuiMouseCursor_Arrow) { + // Hold previous cursor to avoid single-frame revert flicker + ImGui::SetMouseCursor(s_prevCursor); + s_holdFrames--; + } else { + s_prevCursor = g.MouseCursor; + s_holdFrames = 0; + } + } + + // Rendering + PERF_BEGIN(_perfImRender); + ImGui::Render(); + PERF_END("ImGui::Render", _perfImRender); + + // Apply cursor immediately via SDL so it takes effect this frame. + // ImGui_ImplSDL3_UpdateMouseCursor() runs at the START of the + // next frame, creating a 1-frame lag. By calling SDL_SetCursor() + // here we eliminate that delay and any flicker. + { + static SDL_Cursor* sdlCursors[ImGuiMouseCursor_COUNT] = {}; + static bool sdlCursorsInit = false; + if (!sdlCursorsInit) { + sdlCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + sdlCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT); + sdlCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE); + sdlCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE); + sdlCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE); + sdlCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); + sdlCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); + sdlCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); + sdlCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); + sdlCursorsInit = true; + } + ImGuiMouseCursor cur = ImGui::GetMouseCursor(); + if (cur >= 0 && cur < ImGuiMouseCursor_COUNT && sdlCursors[cur]) + SDL_SetCursor(sdlCursors[cur]); + } + PERF_BEGIN(_perfPresent); +#ifdef DRAGONX_USE_DX11 + // Ensure swap chain matches current window size. + // SDL_EVENT_WINDOW_RESIZED may be delayed during live resize + // (Windows runs a modal loop while the user drags the border). + dx.ensureSize(); + + // DX11: Set render target and clear with transparent black for DWM + ID3D11RenderTargetView* rtv = dx.renderTargetView(); + dx.deviceContext()->OMSetRenderTargets(1, &rtv, nullptr); + { + // When the background is fully opaque (low-spec mode or + // window_opacity >= 1.0), clear with alpha 1.0 so the + // compositor/DWM skips expensive blur compositing. + float wo = app.settings() ? app.settings()->getWindowOpacity() : 1.0f; + bool opaqueBackground = dragonx::ui::effects::isLowSpecMode() || wo >= 0.99f; + bool effectiveBackdrop = (backdrop_active || app.getGradientTexture() != 0) + && !opaqueBackground; + dx.clear(0.0f, 0.0f, 0.0f, effectiveBackdrop ? 0.0f : 1.0f); + } + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + // Update and Render additional Platform Windows (multi-viewport) + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + } + + dx.present(1); +#else + glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); + { + // When the background is fully opaque (low-spec mode or + // window_opacity >= 1.0), clear with alpha 1.0 so the + // compositor skips alpha blending against the desktop. + float wo = app.settings() ? app.settings()->getWindowOpacity() : 1.0f; + bool opaqueBackground = dragonx::ui::effects::isLowSpecMode() || wo >= 0.99f; + bool effectiveBackdrop = (backdrop_active || app.getGradientTexture() != 0) + && !opaqueBackground; + glClearColor(0.0f, 0.0f, 0.0f, effectiveBackdrop ? 0.0f : 1.0f); + } + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + + // Update and Render additional Platform Windows (multi-viewport) + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + SDL_Window* backup_current_window = SDL_GL_GetCurrentWindow(); + SDL_GLContext backup_current_context = SDL_GL_GetCurrentContext(); + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + SDL_GL_MakeCurrent(backup_current_window, backup_current_context); + } + + SDL_GL_SwapWindow(window); +#endif + PERF_END("Present", _perfPresent); + + // --- PerfLog: end frame --- + dragonx::util::PerfLog::instance().endFrame(); + + // Exit when shutdown is complete + if (app.shouldQuit()) { + running = false; + } + + // Periodic log flush so crash diagnostics are visible + { + static auto lastFlush = std::chrono::steady_clock::now(); + auto now = std::chrono::steady_clock::now(); + if (std::chrono::duration_cast(now - lastFlush).count() >= 5) { + fflush(stdout); + fflush(stderr); + lastFlush = now; + } + } + + // Track last render for idle periodic timer + lastPeriodicFrame = std::chrono::steady_clock::now(); + + // P6: Determine if next frame needs redraw or can idle + { + ImGuiContext& g = *GImGui; + + // Detect actual user interaction — NOT WantCaptureMouse/Keyboard + // which are just "ImGui has windows that accept input" (always true). + bool mouseMoving = g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f; + bool mouseClicked = false; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + mouseClicked |= g.IO.MouseDown[i]; + bool scrolling = g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f; + bool typing = g.IO.InputQueueCharacters.Size > 0; + bool widgetActive = g.ActiveId != 0 || g.MovingWindow != nullptr; + + bool uiActive = mouseMoving || mouseClicked || scrolling + || typing || widgetActive; + + // When the background is fully opaque, backdrop doesn't + // need continuous frames — let the app idle and save power. + float wo2 = app.settings() ? app.settings()->getWindowOpacity() : 1.0f; + bool opaqueBackground = dragonx::ui::effects::isLowSpecMode() || wo2 >= 0.99f; + bool backdropNeedsFrames = (backdrop_active || app.getGradientTexture() != 0) + && !opaqueBackground; + bool animating = app.isShuttingDown() + || backdropNeedsFrames + || dragonx::ui::effects::ThemeEffects::instance().hasActiveAnimation() + || dragonx::ui::Notifications::instance().hasActive() + || dragonx::ui::material::SmoothScrollAnimating(); + // If nothing is happening, allow the next iteration to idle + needsRedraw = uiActive || animating; + } + } + + // Remove resize event watcher + SDL_RemoveEventWatch(resizeWatcher, &resizeCtx); + + // Save window size to settings before shutdown + if (app.settings()) { + int curW = 0, curH = 0; + SDL_GetWindowSize(window, &curW, &curH); + float s = dragonx::ui::material::Typography::instance().getDpiScale(); + int logW = (int)lroundf((float)curW / s); + int logH = (int)lroundf((float)curH / s); + if (logW >= 1024 && logH >= 720) { + app.settings()->setWindowSize(logW, logH); + app.settings()->save(); + } + } + + // Final cleanup (daemon already stopped by beginShutdown) + app.shutdown(); +#ifdef DRAGONX_USE_DX11 + Shutdown(window, dx); +#else + Shutdown(window, gl_context); +#endif + + return 0; +} + +static bool InitSDL() +{ + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { + fprintf(stderr, "Error: SDL_Init(): %s\n", SDL_GetError()); + return false; + } + return true; +} + +// Persistent storage for IniFilename — must outlive ImGui context +static std::string s_iniPath; + +#ifdef DRAGONX_USE_DX11 + +static bool InitImGui(SDL_Window* window, dragonx::platform::DX11Context& dx) +{ + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + + // Save imgui.ini to ObsidianDragon config directory + s_iniPath = (std::filesystem::path(dragonx::util::Platform::getObsidianDragonDir()) / "imgui.ini").string(); + io.IniFilename = s_iniPath.c_str(); + + // Enable keyboard navigation + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; + // Enable gamepad navigation + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; + // Enable multi-viewport (windows can float outside main window) + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForD3D(window); + ImGui_ImplDX11_Init(dx.device(), dx.deviceContext()); + + // Query display DPI scale (e.g. 1.5 for 150% Windows scaling) + float dpiScale = SDL_GetWindowDisplayScale(window); + if (dpiScale <= 0.0f) dpiScale = 1.0f; + DEBUG_LOGF("Display scale: %.2f\n", dpiScale); + + // Load Material Design typography system with DPI awareness + if (!dragonx::ui::material::Typography::instance().load(io, dpiScale)) { + DEBUG_LOGF("Warning: Could not load typography system, using defaults\n"); + io.Fonts->AddFontDefault(); + } + + return true; +} + +static void Shutdown(SDL_Window* window, dragonx::platform::DX11Context& dx) +{ + ImGui_ImplDX11_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + dx.shutdown(); + + // Save native HWND before SDL releases its reference. + // SDL marks externally-provided HWNDs as SDL_WINDOW_EXTERNAL and + // does NOT call DestroyWindow -- we must do it ourselves. + HWND hwnd = nullptr; + if (window) { + hwnd = (HWND)SDL_GetPointerProperty( + SDL_GetWindowProperties(window), + SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); + SDL_DestroyWindow(window); + } + if (hwnd) { + DestroyWindow(hwnd); + } + SDL_Quit(); +} + +#else // OpenGL path + +static bool InitImGui(SDL_Window* window, SDL_GLContext gl_context) +{ + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + + // Save imgui.ini to ObsidianDragon config directory + s_iniPath = (std::filesystem::path(dragonx::util::Platform::getObsidianDragonDir()) / "imgui.ini").string(); + io.IniFilename = s_iniPath.c_str(); + + // Enable keyboard navigation + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; + // Enable gamepad navigation + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; + // Enable multi-viewport (windows can float outside main window) + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForOpenGL(window, gl_context); + ImGui_ImplOpenGL3_Init("#version 130"); + + // Query display DPI scale (e.g. 1.5 for 150% scaling) + float dpiScale = SDL_GetWindowDisplayScale(window); + if (dpiScale <= 0.0f) dpiScale = 1.0f; + DEBUG_LOGF("Display scale: %.2f\n", dpiScale); + + // Load Material Design typography system with DPI awareness + // This loads Ubuntu fonts in Light, Regular, and Medium weights + // at all sizes needed for the type scale (H1-H6, Body1-2, etc.) + if (!dragonx::ui::material::Typography::instance().load(io, dpiScale)) { + DEBUG_LOGF("Warning: Could not load typography system, using defaults\n"); + io.Fonts->AddFontDefault(); + } + + return true; +} + +static void Shutdown(SDL_Window* window, SDL_GLContext gl_context) +{ + // Shutdown acrylic effects before destroying GL context + dragonx::ui::effects::ImGuiAcrylic::Shutdown(); + + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + if (gl_context) { + SDL_GL_DestroyContext(gl_context); + } + if (window) { + SDL_DestroyWindow(window); + } + SDL_Quit(); +} + +#endif // DRAGONX_USE_DX11 diff --git a/src/platform/dx11_context.cpp b/src/platform/dx11_context.cpp new file mode 100644 index 0000000..68b4c01 --- /dev/null +++ b/src/platform/dx11_context.cpp @@ -0,0 +1,351 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "dx11_context.h" + +#ifdef _WIN32 + +#include +#include +#include "../util/logger.h" + +// Not defined in older MinGW SDK headers +#ifndef WS_EX_NOREDIRECTIONBITMAP +#define WS_EX_NOREDIRECTIONBITMAP 0x00200000L +#endif + +namespace dragonx { +namespace platform { + +// Helper to get HWND from SDL window +static HWND getHWND(SDL_Window* window) { + if (!window) return nullptr; + SDL_PropertiesID props = SDL_GetWindowProperties(window); + if (props == 0) return nullptr; + return (HWND)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); +} + +bool DX11Context::init(SDL_Window* window) +{ + HWND hwnd = getHWND(window); + if (!hwnd) { + DEBUG_LOGF("DX11: Failed to get HWND from SDL window\n"); + return false; + } + hwnd_ = hwnd; + + // Ensure WS_EX_NOREDIRECTIONBITMAP is set. The main code creates the + // HWND with this style, but if someone passes a different window we try + // to set it here as a fallback. We also call SetWindowPos with + // SWP_FRAMECHANGED so the DWM re-evaluates the extended style. + LONG_PTR exStyle = GetWindowLongPtrW(hwnd, GWL_EXSTYLE); + if (!(exStyle & WS_EX_NOREDIRECTIONBITMAP)) { + SetWindowLongPtrW(hwnd, GWL_EXSTYLE, exStyle | WS_EX_NOREDIRECTIONBITMAP); + SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); + LONG_PTR verify = GetWindowLongPtrW(hwnd, GWL_EXSTYLE); + if (verify & WS_EX_NOREDIRECTIONBITMAP) + DEBUG_LOGF("DX11: WS_EX_NOREDIRECTIONBITMAP set via fallback path\n"); + else + DEBUG_LOGF("DX11: WARNING - WS_EX_NOREDIRECTIONBITMAP could NOT be set!\n"); + } else { + DEBUG_LOGF("DX11: WS_EX_NOREDIRECTIONBITMAP already present (good)\n"); + } + fflush(stdout); + + // Create D3D11 device and context + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[] = { + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_0, + }; + + UINT createDeviceFlags = 0; +#ifdef DRAGONX_DEBUG + createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + + // Need BGRA support for DirectComposition + createDeviceFlags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT; + + HRESULT hr = D3D11CreateDevice( + nullptr, // Default adapter + D3D_DRIVER_TYPE_HARDWARE, // Hardware rendering + nullptr, // No software module + createDeviceFlags, + featureLevelArray, + 2, + D3D11_SDK_VERSION, + &device_, + &featureLevel, + &deviceContext_ + ); + + if (FAILED(hr)) { + DEBUG_LOGF("DX11: D3D11CreateDevice failed (HRESULT 0x%08lx)\n", hr); + return false; + } + + DEBUG_LOGF("DX11: Device created (feature level %d.%d)\n", + (featureLevel >> 12) & 0xF, (featureLevel >> 8) & 0xF); + + // Get DXGI device for factory access and DirectComposition + IDXGIDevice* dxgiDevice = nullptr; + hr = device_->QueryInterface(IID_PPV_ARGS(&dxgiDevice)); + if (FAILED(hr)) { + DEBUG_LOGF("DX11: QueryInterface IDXGIDevice failed\n"); + shutdown(); + return false; + } + + IDXGIAdapter* dxgiAdapter = nullptr; + hr = dxgiDevice->GetAdapter(&dxgiAdapter); + if (FAILED(hr)) { + dxgiDevice->Release(); + DEBUG_LOGF("DX11: GetAdapter failed\n"); + shutdown(); + return false; + } + + IDXGIFactory2* dxgiFactory = nullptr; + hr = dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory)); + dxgiAdapter->Release(); + if (FAILED(hr)) { + dxgiDevice->Release(); + DEBUG_LOGF("DX11: GetParent IDXGIFactory2 failed\n"); + shutdown(); + return false; + } + + // --------------------------------------------------------------- + // Strategy: CreateSwapChainForComposition + DirectComposition + // + // DXGI_ALPHA_MODE_PREMULTIPLIED only works with composition swap chains. + // CreateSwapChainForHwnd does NOT support premultiplied alpha. + // We must use DirectComposition to bind the composition swap chain + // to the window. This is how Windows Terminal achieves transparency. + // --------------------------------------------------------------- + + DXGI_SWAP_CHAIN_DESC1 sd = {}; + sd.Width = 0; // Auto-detect from HWND + sd.Height = 0; + sd.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + sd.Stereo = FALSE; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.BufferCount = 2; + sd.Scaling = DXGI_SCALING_STRETCH; + sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; + sd.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; + sd.Flags = 0; + + // CreateSwapChainForComposition needs explicit width/height + RECT clientRect; + GetClientRect(hwnd, &clientRect); + sd.Width = clientRect.right - clientRect.left; + sd.Height = clientRect.bottom - clientRect.top; + if (sd.Width == 0) sd.Width = 1400; + if (sd.Height == 0) sd.Height = 900; + + hr = dxgiFactory->CreateSwapChainForComposition( + device_, + &sd, + nullptr, + &swapChain_ + ); + + if (SUCCEEDED(hr)) { + DEBUG_LOGF("DX11: Composition swap chain created (%ux%u, PREMULTIPLIED alpha)\n", + sd.Width, sd.Height); + + // Create DirectComposition device and bind swap chain to HWND + hr = DCompositionCreateDevice(dxgiDevice, IID_PPV_ARGS(&dcompDevice_)); + if (SUCCEEDED(hr)) { + hr = dcompDevice_->CreateTargetForHwnd(hwnd, TRUE, &dcompTarget_); + } + if (SUCCEEDED(hr)) { + hr = dcompDevice_->CreateVisual(&dcompVisual_); + } + if (SUCCEEDED(hr)) { + hr = dcompVisual_->SetContent(swapChain_); + } + if (SUCCEEDED(hr)) { + hr = dcompTarget_->SetRoot(dcompVisual_); + } + if (SUCCEEDED(hr)) { + hr = dcompDevice_->Commit(); + } + + if (SUCCEEDED(hr)) { + hasAlpha_ = true; + DEBUG_LOGF("DX11: DirectComposition bound to HWND (alpha compositing active)\n"); + fflush(stdout); + } else { + DEBUG_LOGF("DX11: DirectComposition setup failed (0x%08lx), falling back\n", hr); + fflush(stderr); + // Clean up the composition objects and swap chain + if (dcompVisual_) { dcompVisual_->Release(); dcompVisual_ = nullptr; } + if (dcompTarget_) { dcompTarget_->Release(); dcompTarget_ = nullptr; } + if (dcompDevice_) { dcompDevice_->Release(); dcompDevice_ = nullptr; } + swapChain_->Release(); + swapChain_ = nullptr; + } + } else { + DEBUG_LOGF("DX11: CreateSwapChainForComposition failed (0x%08lx)\n", hr); + } + + // Fallback: standard HWND swap chain (no alpha transparency) + if (!swapChain_) { + sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; + sd.Width = 0; // Auto-detect + sd.Height = 0; + hr = dxgiFactory->CreateSwapChainForHwnd( + device_, + hwnd, + &sd, + nullptr, + nullptr, + &swapChain_ + ); + if (SUCCEEDED(hr)) { + DEBUG_LOGF("DX11: HWND swap chain created (opaque, no alpha)\n"); + } + } + + dxgiFactory->Release(); + dxgiDevice->Release(); + + if (FAILED(hr) || !swapChain_) { + DEBUG_LOGF("DX11: All swap chain creation paths failed\n"); + shutdown(); + return false; + } + + createRenderTarget(); + return true; +} + +void DX11Context::shutdown() +{ + cleanupRenderTarget(); + + // Release DirectComposition objects + if (dcompVisual_) { dcompVisual_->Release(); dcompVisual_ = nullptr; } + if (dcompTarget_) { dcompTarget_->Release(); dcompTarget_ = nullptr; } + if (dcompDevice_) { dcompDevice_->Release(); dcompDevice_ = nullptr; } + + if (swapChain_) { + swapChain_->Release(); + swapChain_ = nullptr; + } + if (deviceContext_) { + deviceContext_->Release(); + deviceContext_ = nullptr; + } + if (device_) { + device_->Release(); + device_ = nullptr; + } + hasAlpha_ = false; +} + +void DX11Context::resize(int width, int height) +{ + (void)width; + (void)height; + if (!swapChain_ || !deviceContext_) return; + + cleanupRenderTarget(); + + // Unbind the render target from the pipeline — ResizeBuffers requires + // ALL outstanding references to back-buffer resources to be released. + // Without this, ResizeBuffers fails with DXGI_ERROR_INVALID_CALL when + // growing the window (shrinking appears fine because the old larger + // buffer simply gets cropped by DWM). + deviceContext_->OMSetRenderTargets(0, nullptr, nullptr); + deviceContext_->Flush(); + + // For composition swap chains (CreateSwapChainForComposition), + // passing 0,0 means "keep current size" — NOT auto-detect from HWND. + // We must pass the actual pixel dimensions from GetClientRect. + UINT w = 0, h = 0; + if (hwnd_) { + RECT rc; + GetClientRect(hwnd_, &rc); + w = static_cast(rc.right - rc.left); + h = static_cast(rc.bottom - rc.top); + } + if (w == 0 || h == 0) return; + + HRESULT hr = swapChain_->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0); + if (FAILED(hr)) { + DEBUG_LOGF("DX11: ResizeBuffers(%u x %u) failed (0x%08lx)\n", w, h, hr); + } + createRenderTarget(); + + // Commit DirectComposition so it picks up the new buffer size + if (dcompDevice_) { + dcompDevice_->Commit(); + } +} + +void DX11Context::ensureSize() +{ + if (!swapChain_ || !hwnd_) return; + + // Query current swap chain buffer dimensions + DXGI_SWAP_CHAIN_DESC1 desc; + if (FAILED(swapChain_->GetDesc1(&desc))) return; + + // Query actual HWND client area + RECT rc; + GetClientRect(hwnd_, &rc); + UINT clientW = static_cast(rc.right - rc.left); + UINT clientH = static_cast(rc.bottom - rc.top); + + // Resize only when there's a mismatch + if (clientW > 0 && clientH > 0 && + (desc.Width != clientW || desc.Height != clientH)) { + resize(static_cast(clientW), static_cast(clientH)); + } +} + +void DX11Context::clear(float r, float g, float b, float a) +{ + if (!deviceContext_ || !renderTargetView_) return; + const float clearColor[4] = { r, g, b, a }; + deviceContext_->ClearRenderTargetView(renderTargetView_, clearColor); +} + +void DX11Context::present(int vsync) +{ + if (!swapChain_) return; + swapChain_->Present(vsync ? 1 : 0, 0); +} + +void DX11Context::createRenderTarget() +{ + if (!swapChain_ || !device_) return; + + ID3D11Texture2D* backBuffer = nullptr; + swapChain_->GetBuffer(0, IID_PPV_ARGS(&backBuffer)); + if (backBuffer) { + device_->CreateRenderTargetView(backBuffer, nullptr, &renderTargetView_); + backBuffer->Release(); + } +} + +void DX11Context::cleanupRenderTarget() +{ + if (renderTargetView_) { + renderTargetView_->Release(); + renderTargetView_ = nullptr; + } +} + +} // namespace platform +} // namespace dragonx + +#endif // _WIN32 diff --git a/src/platform/dx11_context.h b/src/platform/dx11_context.h new file mode 100644 index 0000000..e3084a7 --- /dev/null +++ b/src/platform/dx11_context.h @@ -0,0 +1,108 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// DirectX 11 Rendering Context for Windows +// Uses DXGI swap chain with premultiplied alpha + DirectComposition +// for true per-pixel transparency with DWM Mica/Acrylic backdrops. + +#pragma once + +#ifdef _WIN32 + +#include +#include +#include + +// Forward declarations - DirectComposition interfaces +struct IDCompositionDevice; +struct IDCompositionTarget; +struct IDCompositionVisual; + +struct SDL_Window; + +namespace dragonx { +namespace platform { + +class DX11Context { +public: + DX11Context() = default; + ~DX11Context() { shutdown(); } + + // Non-copyable + DX11Context(const DX11Context&) = delete; + DX11Context& operator=(const DX11Context&) = delete; + + /** + * @brief Initialize D3D11 device and DXGI swap chain with alpha support + * @param window SDL window to create the swap chain for + * @return true on success + */ + bool init(SDL_Window* window); + + /** + * @brief Shut down and release all D3D11/DXGI resources + */ + void shutdown(); + + /** + * @brief Resize the swap chain buffers (call on window resize) + * @param width New width (0 = auto-detect from swap chain) + * @param height New height (0 = auto-detect from swap chain) + */ + void resize(int width, int height); + + /** + * @brief Ensure swap chain matches the current HWND client size. + * Call once per frame to guarantee the buffers stay in sync. + * No-op if the sizes already match. + */ + void ensureSize(); + + /** + * @brief Clear the render target with a color + * @param r Red (0-1) + * @param g Green (0-1) + * @param b Blue (0-1) + * @param a Alpha (0-1), 0 = fully transparent for DWM + */ + void clear(float r, float g, float b, float a); + + /** + * @brief Present the frame (swap buffers) + * @param vsync 1 = vsync on, 0 = vsync off + */ + void present(int vsync = 1); + + /** @brief Whether premultiplied alpha compositing is active */ + bool hasAlphaCompositing() const { return hasAlpha_; } + + // Accessors + ID3D11Device* device() const { return device_; } + ID3D11DeviceContext* deviceContext() const { return deviceContext_; } + ID3D11RenderTargetView* renderTargetView() const { return renderTargetView_; } + IDXGISwapChain1* swapChain() const { return swapChain_; } + +private: + void createRenderTarget(); + void cleanupRenderTarget(); + + // D3D11 core + ID3D11Device* device_ = nullptr; + ID3D11DeviceContext* deviceContext_ = nullptr; + IDXGISwapChain1* swapChain_ = nullptr; + ID3D11RenderTargetView* renderTargetView_ = nullptr; + + // DirectComposition (for premultiplied alpha swap chain presentation) + IDCompositionDevice* dcompDevice_ = nullptr; + IDCompositionTarget* dcompTarget_ = nullptr; + IDCompositionVisual* dcompVisual_ = nullptr; + + bool hasAlpha_ = false; + HWND hwnd_ = nullptr; +}; + +} // namespace platform +} // namespace dragonx + +#endif // _WIN32 diff --git a/src/platform/windows_backdrop.cpp b/src/platform/windows_backdrop.cpp new file mode 100644 index 0000000..3cfdd02 --- /dev/null +++ b/src/platform/windows_backdrop.cpp @@ -0,0 +1,182 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "windows_backdrop.h" + +#ifdef _WIN32 + +#include +#include +#include +#include +#include "../util/logger.h" + +// Link with dwmapi.lib +#pragma comment(lib, "dwmapi.lib") + +// DWM attribute values not in older SDK headers +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +#ifndef DWMWA_SYSTEMBACKDROP_TYPE +#define DWMWA_SYSTEMBACKDROP_TYPE 38 +#endif + +#ifndef DWMWA_MICA_EFFECT +#define DWMWA_MICA_EFFECT 1029 +#endif + +// System backdrop types (Windows 11 22H2+) +typedef enum { + DWMSBT_AUTO = 0, + DWMSBT_NONE = 1, + DWMSBT_MAINWINDOW = 2, // Mica + DWMSBT_TRANSIENTWINDOW = 3, // Acrylic + DWMSBT_TABBEDWINDOW = 4 // Mica Alt +} DWM_SYSTEMBACKDROP_TYPE; + +namespace dragonx { +namespace platform { + +// Helper to get HWND from SDL window +static HWND getHWND(SDL_Window* window) { + if (!window) return nullptr; + + SDL_PropertiesID props = SDL_GetWindowProperties(window); + if (props == 0) return nullptr; + + return (HWND)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); +} + +WindowsVersionInfo getWindowsVersion() { + WindowsVersionInfo info = {}; + + // Use RtlGetVersion to get the real version (GetVersionEx is deprecated/lies) + typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); + + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + if (ntdll) { + RtlGetVersionPtr rtlGetVersion = (RtlGetVersionPtr)GetProcAddress(ntdll, "RtlGetVersion"); + if (rtlGetVersion) { + RTL_OSVERSIONINFOW osvi = {}; + osvi.dwOSVersionInfoSize = sizeof(osvi); + if (rtlGetVersion(&osvi) == 0) { + info.major = osvi.dwMajorVersion; + info.minor = osvi.dwMinorVersion; + info.build = osvi.dwBuildNumber; + } + } + } + + info.isWindows11 = (info.major >= 10 && info.build >= 22000); + info.isWindows10 = (info.major >= 10 && info.build >= 10240); + + return info; +} + +bool isWindowsBackdropAvailable() { + WindowsVersionInfo ver = getWindowsVersion(); + // Backdrop effects require at least Windows 10 + return ver.isWindows10; +} + +bool enableWindowsBackdrop(SDL_Window* window, WindowsBackdrop type) { + HWND hwnd = getHWND(window); + if (!hwnd) { + DEBUG_LOGF("WindowsBackdrop: Failed to get HWND\n"); + return false; + } + + WindowsVersionInfo ver = getWindowsVersion(); + DEBUG_LOGF("WindowsBackdrop: Windows %d.%d.%d detected\n", ver.major, ver.minor, ver.build); + + if (!ver.isWindows10) { + DEBUG_LOGF("WindowsBackdrop: Windows 10+ required\n"); + return false; + } + + // Enable dark mode for title bar (looks better with acrylic) + BOOL useDarkMode = TRUE; + DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &useDarkMode, sizeof(useDarkMode)); + + // Auto-detect best backdrop type + if (type == WindowsBackdrop::Auto) { + if (ver.isWindows11 && ver.build >= 22621) { + // Windows 11 22H2+ - use Mica Alt for dark themed apps + type = WindowsBackdrop::MicaAlt; + } else if (ver.isWindows11) { + // Windows 11 21H2 - use Mica + type = WindowsBackdrop::Mica; + } else { + // Windows 10 - use Acrylic + type = WindowsBackdrop::Acrylic; + } + } + + // Extend DWM frame into entire client area - required for all backdrop types + // This lets the DWM composition show through where we render with alpha = 0 + MARGINS margins = {-1, -1, -1, -1}; + DwmExtendFrameIntoClientArea(hwnd, &margins); + + HRESULT hr = S_OK; + + if (ver.build >= 22621) { + // Windows 11 22H2+ - use DWMWA_SYSTEMBACKDROP_TYPE + DWM_SYSTEMBACKDROP_TYPE backdrop; + switch (type) { + case WindowsBackdrop::Mica: + backdrop = DWMSBT_MAINWINDOW; + DEBUG_LOGF("WindowsBackdrop: Enabling Mica\n"); + break; + case WindowsBackdrop::MicaAlt: + backdrop = DWMSBT_TABBEDWINDOW; + DEBUG_LOGF("WindowsBackdrop: Enabling Mica Alt\n"); + break; + case WindowsBackdrop::Acrylic: + backdrop = DWMSBT_TRANSIENTWINDOW; + DEBUG_LOGF("WindowsBackdrop: Enabling Acrylic\n"); + break; + default: + backdrop = DWMSBT_NONE; + break; + } + hr = DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &backdrop, sizeof(backdrop)); + } + else if (ver.isWindows11) { + // Windows 11 21H2 - use legacy DWMWA_MICA_EFFECT + BOOL enableMica = (type == WindowsBackdrop::Mica || type == WindowsBackdrop::MicaAlt); + hr = DwmSetWindowAttribute(hwnd, DWMWA_MICA_EFFECT, &enableMica, sizeof(enableMica)); + DEBUG_LOGF("WindowsBackdrop: Enabling Mica (legacy API)\n"); + } + else { + // Windows 10 - frame already extended above, basic DWM transparency + // Note: Full acrylic on Win10 requires undocumented APIs + DEBUG_LOGF("WindowsBackdrop: Using extended frame (Win10)\n"); + } + + if (SUCCEEDED(hr)) { + DEBUG_LOGF("WindowsBackdrop: Successfully enabled\n"); + return true; + } else { + DEBUG_LOGF("WindowsBackdrop: DWM call failed with HRESULT 0x%08lx\n", hr); + return false; + } +} + +void disableWindowsBackdrop(SDL_Window* window) { + HWND hwnd = getHWND(window); + if (!hwnd) return; + + DWM_SYSTEMBACKDROP_TYPE backdrop = DWMSBT_NONE; + DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &backdrop, sizeof(backdrop)); + + MARGINS margins = {0, 0, 0, 0}; + DwmExtendFrameIntoClientArea(hwnd, &margins); +} + +} // namespace platform +} // namespace dragonx + +#endif // _WIN32 diff --git a/src/platform/windows_backdrop.h b/src/platform/windows_backdrop.h new file mode 100644 index 0000000..2330365 --- /dev/null +++ b/src/platform/windows_backdrop.h @@ -0,0 +1,68 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +// Windows-specific backdrop blur (Mica/Acrylic) support +// Uses DWM (Desktop Window Manager) APIs available on Windows 10/11 + +#ifdef _WIN32 + +#include + +namespace dragonx { +namespace platform { + +// Backdrop types available on Windows +enum class WindowsBackdrop { + None, // No system backdrop + Mica, // Windows 11 Mica material + MicaAlt, // Windows 11 Mica Alt (darker) + Acrylic, // Windows 10/11 Acrylic (transient) + Auto // Auto-detect best option +}; + +// Enable Windows system backdrop blur +// Returns true if successfully enabled +bool enableWindowsBackdrop(SDL_Window* window, WindowsBackdrop type = WindowsBackdrop::Auto); + +// Disable Windows system backdrop +void disableWindowsBackdrop(SDL_Window* window); + +// Check if system backdrop is available +bool isWindowsBackdropAvailable(); + +// Get Windows version info +struct WindowsVersionInfo { + int major; + int minor; + int build; + bool isWindows11; // Build >= 22000 + bool isWindows10; // Build >= 10240 +}; + +WindowsVersionInfo getWindowsVersion(); + +} // namespace platform +} // namespace dragonx + +#else // !_WIN32 + +// Stub for non-Windows platforms +namespace dragonx { +namespace platform { + +enum class WindowsBackdrop { None, Mica, MicaAlt, Acrylic, Auto }; + +inline bool enableWindowsBackdrop(SDL_Window*, WindowsBackdrop = WindowsBackdrop::Auto) { return false; } +inline void disableWindowsBackdrop(SDL_Window*) {} +inline bool isWindowsBackdropAvailable() { return false; } + +struct WindowsVersionInfo { int major = 0; int minor = 0; int build = 0; bool isWindows11 = false; bool isWindows10 = false; }; +inline WindowsVersionInfo getWindowsVersion() { return {}; } + +} // namespace platform +} // namespace dragonx + +#endif // _WIN32 diff --git a/src/resources/embedded_resources.cpp b/src/resources/embedded_resources.cpp new file mode 100644 index 0000000..94cd4bb --- /dev/null +++ b/src/resources/embedded_resources.cpp @@ -0,0 +1,564 @@ +#include "embedded_resources.h" +#include "../util/platform.h" +#include "../util/logger.h" +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#endif + +// Include generated resource data if available +#if __has_include("embedded_data.h") +#include "embedded_data.h" +#define HAS_EMBEDDED_RESOURCES 1 +#else +#define HAS_EMBEDDED_RESOURCES 0 +#endif + +namespace dragonx { +namespace resources { + +#if HAS_EMBEDDED_RESOURCES +// Resource table - populated by embedded_data.h (INCBIN symbols: g_NAME_data / g_NAME_size) +static const EmbeddedResource s_resources[] = { + { g_sapling_spend_params_data, g_sapling_spend_params_size, RESOURCE_SAPLING_SPEND }, + { g_sapling_output_params_data, g_sapling_output_params_size, RESOURCE_SAPLING_OUTPUT }, + { g_asmap_dat_data, g_asmap_dat_size, RESOURCE_ASMAP }, +#ifdef HAS_EMBEDDED_DAEMON + { g_hushd_exe_data, g_hushd_exe_size, RESOURCE_HUSHD }, + { g_hush_cli_exe_data, g_hush_cli_exe_size, RESOURCE_HUSH_CLI }, + { g_hush_tx_exe_data, g_hush_tx_exe_size, RESOURCE_HUSH_TX }, + { g_dragonxd_bat_data, g_dragonxd_bat_size, RESOURCE_DRAGONXD_BAT }, + { g_dragonx_cli_bat_data, g_dragonx_cli_bat_size, RESOURCE_DRAGONX_CLI_BAT }, +#endif +#ifdef HAS_EMBEDDED_XMRIG + { g_xmrig_exe_data, g_xmrig_exe_size, RESOURCE_XMRIG }, +#endif +#ifdef HAS_EMBEDDED_GRADIENT + { g_dark_gradient_png_data, g_dark_gradient_png_size, RESOURCE_DARK_GRADIENT }, +#endif +#ifdef HAS_EMBEDDED_LOGO + { g_logo_ObsidianDragon_dark_png_data, g_logo_ObsidianDragon_dark_png_size, RESOURCE_LOGO }, +#endif + { nullptr, 0, nullptr } // Sentinel +}; +// Embedded themes table is generated by s_embedded_themes[] in embedded_data.h +#else +static const EmbeddedResource s_resources[] = { + { nullptr, 0, nullptr } // No embedded resources +}; +// No embedded themes on non-Windows builds (themes live on disk) +struct EmbeddedThemeEntry { const uint8_t* data; unsigned int size; const char* filename; }; +static const EmbeddedThemeEntry s_embedded_themes[] = { + { nullptr, 0, nullptr } +}; +// No embedded images on non-Windows builds (images live on disk) +struct EmbeddedImageEntry { const uint8_t* data; unsigned int size; const char* filename; }; +static const EmbeddedImageEntry s_embedded_images[] = { + { nullptr, 0, nullptr } +}; +#endif + +bool hasEmbeddedResources() +{ +#if HAS_EMBEDDED_RESOURCES + return true; +#else + return false; +#endif +} + +const EmbeddedResource* getEmbeddedResource(const std::string& name) +{ + // Search static resource table (params, daemon binaries, etc.) + for (const auto* res = s_resources; res->data != nullptr; ++res) { + if (name == res->filename) { + return res; + } + } + // Search dynamically generated image table (backgrounds + logos) + // These are generated by build.sh from res/img/ contents. + for (const auto* img = s_embedded_images; img->data != nullptr; ++img) { + if (name == img->filename) { + static thread_local EmbeddedResource imageResult; + imageResult = { img->data, img->size, img->filename }; + return &imageResult; + } + } + return nullptr; +} + +const EmbeddedTheme* getEmbeddedThemes() +{ + // Map from generated table to public struct + // s_embedded_themes is generated by build.sh (or empty fallback) + static std::vector themes; + static bool init = false; + if (!init) { + for (const auto* t = s_embedded_themes; t->data != nullptr; ++t) { + themes.push_back({ t->data, t->size, t->filename }); + } + themes.push_back({ nullptr, 0, nullptr }); // Sentinel + init = true; + } + return themes.data(); +} + +int extractBundledThemes(const std::string& destDir) +{ + namespace fs = std::filesystem; + int count = 0; + + const auto* themes = getEmbeddedThemes(); + if (!themes || !themes->data) return 0; + + // Ensure destination exists + std::error_code ec; + fs::create_directories(destDir, ec); + if (ec) { + DEBUG_LOGF("[ERROR] EmbeddedResources: Failed to create theme dir: %s\n", destDir.c_str()); + return 0; + } + + for (const auto* t = themes; t->data != nullptr; ++t) { + fs::path dest = fs::path(destDir) / t->filename; + // Always overwrite — bundled themes should match the binary version + std::ofstream f(dest, std::ios::binary); + if (f.is_open()) { + f.write(reinterpret_cast(t->data), t->size); + f.close(); + DEBUG_LOGF("[INFO] EmbeddedResources: Extracted theme: %s (%zu bytes)\n", + t->filename, t->size); + count++; + } else { + DEBUG_LOGF("[ERROR] EmbeddedResources: Failed to write theme: %s\n", dest.string().c_str()); + } + } + return count; +} + +std::string getParamsDirectory() +{ +#ifdef _WIN32 + char appdata[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, appdata))) { + return std::string(appdata) + "\\ZcashParams"; + } + return ""; +#elif defined(__APPLE__) + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw ? pw->pw_dir : "/tmp"; + } + return std::string(home) + "/Library/Application Support/ZcashParams"; +#else + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw ? pw->pw_dir : "/tmp"; + } + return std::string(home) + "/.zcash-params"; +#endif +} + +bool needsParamsExtraction() +{ + if (!hasEmbeddedResources()) { + return false; + } + + // Check daemon directory (hush3/) — the only extraction target + std::string daemonDir = getDaemonDirectory(); + std::string spendPath = daemonDir + +#ifdef _WIN32 + "\\sapling-spend.params"; +#else + "/sapling-spend.params"; +#endif + std::string outputPath = daemonDir + +#ifdef _WIN32 + "\\sapling-output.params"; +#else + "/sapling-output.params"; +#endif + + // Check if both params exist in daemon directory + return !std::filesystem::exists(spendPath) || !std::filesystem::exists(outputPath); +} + +static bool extractResource(const EmbeddedResource* res, const std::string& destPath) +{ + if (!res || !res->data || res->size == 0) { + return false; + } + + // Create parent directories + std::filesystem::path path(destPath); + if (path.has_parent_path()) { + std::error_code ec; + std::filesystem::create_directories(path.parent_path(), ec); + if (ec) { + DEBUG_LOGF("[ERROR] Failed to create directory %s: %s\n", + path.parent_path().string().c_str(), ec.message().c_str()); + return false; + } + } + + // Write file + std::ofstream file(destPath, std::ios::binary); + if (!file) { + DEBUG_LOGF("[ERROR] Failed to open %s for writing\n", destPath.c_str()); + return false; + } + + file.write(reinterpret_cast(res->data), res->size); + if (!file) { + DEBUG_LOGF("[ERROR] Failed to write %zu bytes to %s\n", res->size, destPath.c_str()); + return false; + } + + DEBUG_LOGF("[INFO] Extracted %s (%zu bytes)\n", destPath.c_str(), res->size); + return true; +} + +bool extractEmbeddedResources() +{ + if (!hasEmbeddedResources()) { + DEBUG_LOGF("[ERROR] No embedded resources available\n"); + return false; + } + + bool success = true; + +#ifdef _WIN32 + const char pathSep = '\\'; +#else + const char pathSep = '/'; +#endif + + // All files go to /hush3/ + std::string daemonDir = getDaemonDirectory(); + + // Extract Sapling params to daemon directory alongside hushd + const EmbeddedResource* spendRes = getEmbeddedResource(RESOURCE_SAPLING_SPEND); + if (spendRes) { + std::string dest = daemonDir + pathSep + RESOURCE_SAPLING_SPEND; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting sapling-spend.params (%zu MB)...\n", spendRes->size / (1024*1024)); + if (!extractResource(spendRes, dest)) { + success = false; + } + } + } + + const EmbeddedResource* outputRes = getEmbeddedResource(RESOURCE_SAPLING_OUTPUT); + if (outputRes) { + std::string dest = daemonDir + pathSep + RESOURCE_SAPLING_OUTPUT; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting sapling-output.params (%zu MB)...\n", outputRes->size / (1024*1024)); + if (!extractResource(outputRes, dest)) { + success = false; + } + } + } + + // Extract asmap.dat to daemon directory + const EmbeddedResource* asmapRes = getEmbeddedResource(RESOURCE_ASMAP); + if (asmapRes) { + std::string dest = daemonDir + pathSep + RESOURCE_ASMAP; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting asmap.dat...\n"); + if (!extractResource(asmapRes, dest)) { + success = false; + } + } + } + + // Extract daemon binaries — NOT the data directory. + // Running hushd.exe from inside the data directory (where it writes blockchain + // data, debug.log, lock files, etc.) causes crashes on some Windows machines. +#ifdef HAS_EMBEDDED_DAEMON + DEBUG_LOGF("[INFO] Daemon extraction directory: %s\n", daemonDir.c_str()); + + const EmbeddedResource* hushdRes = getEmbeddedResource(RESOURCE_HUSHD); + if (hushdRes) { + std::string dest = daemonDir + pathSep + RESOURCE_HUSHD; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting hushd.exe (%zu MB)...\n", hushdRes->size / (1024*1024)); + if (!extractResource(hushdRes, dest)) { + success = false; + } + } + } + + const EmbeddedResource* cliRes = getEmbeddedResource(RESOURCE_HUSH_CLI); + if (cliRes) { + std::string dest = daemonDir + pathSep + RESOURCE_HUSH_CLI; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting hush-cli.exe (%zu MB)...\n", cliRes->size / (1024*1024)); + if (!extractResource(cliRes, dest)) { + success = false; + } + } + } + + const EmbeddedResource* batRes = getEmbeddedResource(RESOURCE_DRAGONXD_BAT); + if (batRes) { + std::string dest = daemonDir + pathSep + RESOURCE_DRAGONXD_BAT; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting dragonxd.bat...\n"); + if (!extractResource(batRes, dest)) { + success = false; + } + } + } + + const EmbeddedResource* txRes = getEmbeddedResource(RESOURCE_HUSH_TX); + if (txRes) { + std::string dest = daemonDir + pathSep + RESOURCE_HUSH_TX; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting hush-tx.exe (%zu MB)...\n", txRes->size / (1024*1024)); + if (!extractResource(txRes, dest)) { + success = false; + } + } + } + + const EmbeddedResource* cliBatRes = getEmbeddedResource(RESOURCE_DRAGONX_CLI_BAT); + if (cliBatRes) { + std::string dest = daemonDir + pathSep + RESOURCE_DRAGONX_CLI_BAT; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting dragonx-cli.bat...\n"); + if (!extractResource(cliBatRes, dest)) { + success = false; + } + } + } +#endif + +#ifdef HAS_EMBEDDED_XMRIG + const EmbeddedResource* xmrigRes = getEmbeddedResource(RESOURCE_XMRIG); + if (xmrigRes) { + std::string dest = daemonDir + pathSep + RESOURCE_XMRIG; + if (!std::filesystem::exists(dest)) { + DEBUG_LOGF("[INFO] Extracting xmrig.exe (%zu MB)...\n", xmrigRes->size / (1024*1024)); + if (!extractResource(xmrigRes, dest)) { + success = false; + } + } + } +#endif + + return success; +} + +std::string getDaemonDirectory() +{ + // Daemon binaries live in %APPDATA%/ObsidianDragon/hush3/ (Windows) or + // ~/.config/ObsidianDragon/hush3/ (Linux) — separate from the blockchain + // data directory to avoid lock-file conflicts. + std::string obsidianDir = util::Platform::getObsidianDragonDir(); +#ifdef _WIN32 + return obsidianDir + "\\hush3"; +#else + return obsidianDir + "/hush3"; +#endif +} + +bool needsDaemonExtraction() +{ +#ifdef HAS_EMBEDDED_DAEMON + std::string daemonDir = getDaemonDirectory(); +#ifdef _WIN32 + std::string hushdPath = daemonDir + "\\hushd.exe"; +#else + std::string hushdPath = daemonDir + "/hushd"; +#endif + return !std::filesystem::exists(hushdPath); +#else + return false; +#endif +} + +bool hasDaemonAvailable() +{ +#ifdef HAS_EMBEDDED_DAEMON + return true; +#else + // Check if daemon exists alongside the executable +#ifdef _WIN32 + return std::filesystem::exists("hushd.exe") || std::filesystem::exists("dragonxd.bat"); +#else + return std::filesystem::exists("hushd") || std::filesystem::exists("dragonxd"); +#endif +#endif +} + +std::string getDaemonPath() +{ + std::string daemonDir = getDaemonDirectory(); +#ifdef _WIN32 + const char pathSep = '\\'; + const char* daemonName = "hushd.exe"; +#else + const char pathSep = '/'; + const char* daemonName = "hushd"; +#endif + + DEBUG_LOGF("[DEBUG] getDaemonPath: daemonDir=%s\n", daemonDir.c_str()); + +#ifdef HAS_EMBEDDED_DAEMON + // Extract if needed + std::string embeddedPath = daemonDir + pathSep + daemonName; + DEBUG_LOGF("[DEBUG] getDaemonPath: checking embedded path %s\n", embeddedPath.c_str()); + if (!std::filesystem::exists(embeddedPath)) { + DEBUG_LOGF("[INFO] getDaemonPath: daemon not found, extracting embedded resources...\n"); + extractEmbeddedResources(); + } + if (std::filesystem::exists(embeddedPath)) { + DEBUG_LOGF("[INFO] getDaemonPath: found at %s\n", embeddedPath.c_str()); + return embeddedPath; + } +#endif + + // Check local directory + if (std::filesystem::exists(daemonName)) { + DEBUG_LOGF("[INFO] getDaemonPath: found in local directory\n"); + return daemonName; + } + + DEBUG_LOGF("[ERROR] getDaemonPath: daemon binary not found anywhere\n"); + return ""; +} + +bool needsXmrigExtraction() +{ +#ifdef HAS_EMBEDDED_XMRIG + std::string daemonDir = getDaemonDirectory(); +#ifdef _WIN32 + std::string xmrigPath = daemonDir + "\\xmrig.exe"; +#else + std::string xmrigPath = daemonDir + "/xmrig"; +#endif + return !std::filesystem::exists(xmrigPath); +#else + return false; +#endif +} + +bool hasXmrigAvailable() +{ +#ifdef HAS_EMBEDDED_XMRIG + return true; +#else + // Check if xmrig exists alongside the executable +#ifdef _WIN32 + return std::filesystem::exists("xmrig.exe"); +#else + return std::filesystem::exists("xmrig"); +#endif +#endif +} + +bool forceExtractXmrig() +{ +#ifdef HAS_EMBEDDED_XMRIG + std::string daemonDir = getDaemonDirectory(); +#ifdef _WIN32 + std::string dest = daemonDir + "\\" + RESOURCE_XMRIG; +#else + std::string dest = daemonDir + "/" + RESOURCE_XMRIG; +#endif + const EmbeddedResource* xmrigRes = getEmbeddedResource(RESOURCE_XMRIG); + if (!xmrigRes) { + DEBUG_LOGF("[ERROR] forceExtractXmrig: no embedded xmrig resource\n"); + return false; + } + DEBUG_LOGF("[INFO] forceExtractXmrig: extracting xmrig (%zu MB) to %s\n", + xmrigRes->size / (1024*1024), dest.c_str()); + if (!extractResource(xmrigRes, dest)) { + DEBUG_LOGF("[ERROR] forceExtractXmrig: extraction failed\n"); + return false; + } +#ifndef _WIN32 + // Set executable permission on Linux + chmod(dest.c_str(), 0755); +#endif + return true; +#else + return false; +#endif +} + +std::string getXmrigPath() +{ + std::string daemonDir = getDaemonDirectory(); +#ifdef _WIN32 + const char pathSep = '\\'; + const char* xmrigName = "xmrig.exe"; +#else + const char pathSep = '/'; + const char* xmrigName = "xmrig"; +#endif + + DEBUG_LOGF("[DEBUG] getXmrigPath: daemonDir=%s\n", daemonDir.c_str()); + +#ifdef HAS_EMBEDDED_XMRIG + // Extract if needed — force re-extract in case Defender deleted it + std::string embeddedPath = daemonDir + pathSep + xmrigName; + DEBUG_LOGF("[DEBUG] getXmrigPath: checking embedded path %s\n", embeddedPath.c_str()); + if (!std::filesystem::exists(embeddedPath)) { + DEBUG_LOGF("[DEBUG] getXmrigPath: not found, force re-extracting xmrig\n"); + forceExtractXmrig(); + } + if (std::filesystem::exists(embeddedPath)) { + DEBUG_LOGF("[INFO] getXmrigPath: found at %s\n", embeddedPath.c_str()); + return embeddedPath; + } +#endif + + // Check local directory + if (std::filesystem::exists(xmrigName)) { + DEBUG_LOGF("[INFO] getXmrigPath: found in local directory\n"); + return xmrigName; + } + + // Check development paths +#ifdef _WIN32 + // Not applicable for cross-compiled Windows builds +#else + // Linux development build — resolve relative to executable directory + // (build/bin/), not CWD which may differ at runtime + std::string exeDir = util::Platform::getExecutableDirectory(); + std::vector devPaths = { + exeDir + "/../../external/xmrig-HAC/xmrig/build/xmrig", // from build/linux/bin/ + exeDir + "/../external/xmrig-HAC/xmrig/build/xmrig", // from build/linux/ + "../external/xmrig-HAC/xmrig/build/xmrig", // CWD = build/linux/ + "../../external/xmrig-HAC/xmrig/build/xmrig", // CWD = build/linux/bin/ + "external/xmrig-HAC/xmrig/build/xmrig", // CWD = project root + }; + for (const auto& dp : devPaths) { + if (std::filesystem::exists(dp)) { + std::string resolved = std::filesystem::canonical(dp).string(); + DEBUG_LOGF("[INFO] getXmrigPath: found dev binary at %s\n", resolved.c_str()); + return resolved; + } + } +#endif + + DEBUG_LOGF("[ERROR] getXmrigPath: xmrig binary not found anywhere\n"); + return ""; +} + +} // namespace resources +} // namespace dragonx diff --git a/src/resources/embedded_resources.h b/src/resources/embedded_resources.h new file mode 100644 index 0000000..1ddef9a --- /dev/null +++ b/src/resources/embedded_resources.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include + +namespace dragonx { +namespace resources { + +// Embedded resource data (generated at build time) +struct EmbeddedResource { + const uint8_t* data; + size_t size; + const char* filename; +}; + +// Check if embedded resources are available +bool hasEmbeddedResources(); + +// Get embedded resource by name +// Returns nullptr if not found or not embedded +const EmbeddedResource* getEmbeddedResource(const std::string& name); + +// Extract all embedded resources to appropriate locations +// Returns true if all resources extracted successfully +bool extractEmbeddedResources(); + +// Check if params need to be extracted (not already present) +bool needsParamsExtraction(); + +// Get the params directory path +std::string getParamsDirectory(); + +// Resource names +constexpr const char* RESOURCE_SAPLING_SPEND = "sapling-spend.params"; +constexpr const char* RESOURCE_SAPLING_OUTPUT = "sapling-output.params"; +constexpr const char* RESOURCE_ASMAP = "asmap.dat"; +constexpr const char* RESOURCE_HUSHD = "hushd.exe"; +constexpr const char* RESOURCE_HUSH_CLI = "hush-cli.exe"; +constexpr const char* RESOURCE_HUSH_TX = "hush-tx.exe"; +constexpr const char* RESOURCE_DRAGONXD_BAT = "dragonxd.bat"; +constexpr const char* RESOURCE_DRAGONX_CLI_BAT = "dragonx-cli.bat"; +constexpr const char* RESOURCE_XMRIG = "xmrig.exe"; +constexpr const char* RESOURCE_DARK_GRADIENT = "dark_gradient.png"; +constexpr const char* RESOURCE_LOGO = "logo_ObsidianDragon_dark.png"; + +// Embedded theme overlay info (for iterating bundled themes) +struct EmbeddedTheme { + const uint8_t* data; + size_t size; + const char* filename; // e.g. "dark.toml" +}; + +// Get array of embedded overlay themes (nullptr-terminated) +const EmbeddedTheme* getEmbeddedThemes(); + +// Extract bundled overlay themes to the given directory +// Returns number of themes extracted +int extractBundledThemes(const std::string& destDir); + +// Check if daemon needs to be extracted +bool needsDaemonExtraction(); + +// Get daemon binary directory (/hush3/) +std::string getDaemonDirectory(); + +// Check if daemon is available (embedded or in app directory) +bool hasDaemonAvailable(); + +// Get daemon executable path (extracts if needed) +std::string getDaemonPath(); + +// Check if xmrig needs to be extracted +bool needsXmrigExtraction(); + +// Check if xmrig is available (embedded or in app directory) +bool hasXmrigAvailable(); + +// Force re-extract xmrig binary from embedded resources +// (bypasses exists-check; use when Defender deletes the file) +bool forceExtractXmrig(); + +// Get xmrig executable path (extracts if needed) +std::string getXmrigPath(); + +} // namespace resources +} // namespace dragonx diff --git a/src/rpc/connection.cpp b/src/rpc/connection.cpp new file mode 100644 index 0000000..2cc4681 --- /dev/null +++ b/src/rpc/connection.cpp @@ -0,0 +1,224 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "connection.h" +#include "../config/version.h" +#include "../resources/embedded_resources.h" + +#include +#include +#include +#include +#include + +#include "../util/logger.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +namespace fs = std::filesystem; + +namespace dragonx { +namespace rpc { + +Connection::Connection() = default; +Connection::~Connection() = default; + +std::string Connection::getDefaultDataDir() +{ +#ifdef _WIN32 + char path[MAX_PATH]; + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, path))) { + return std::string(path) + "\\Hush\\DRAGONX"; + } + return ""; +#elif defined(__APPLE__) + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + // Match SilentDragonX path: Library/Application Support/Hush/DRAGONX + return std::string(home) + "/Library/Application Support/Hush/DRAGONX"; +#else + const char* home = getenv("HOME"); + if (!home) { + struct passwd* pw = getpwuid(getuid()); + home = pw->pw_dir; + } + return std::string(home) + "/.hush/DRAGONX"; +#endif +} + +std::string Connection::getDefaultConfPath() +{ + return getDefaultDataDir() + "/" + DRAGONX_CONF_FILENAME; +} + +std::string Connection::getSaplingParamsDir() +{ + // Sapling params are now extracted alongside the daemon binaries + // in /hush3/ — no longer in the legacy ZcashParams dir. + return resources::getDaemonDirectory(); +} + +bool Connection::verifySaplingParams() +{ + std::string params_dir = getSaplingParamsDir(); + if (params_dir.empty()) { + DEBUG_LOGF("verifySaplingParams: params dir is empty\n"); + return false; + } + +#ifdef _WIN32 + std::string spend_path = params_dir + "\\sapling-spend.params"; + std::string output_path = params_dir + "\\sapling-output.params"; +#else + std::string spend_path = params_dir + "/sapling-spend.params"; + std::string output_path = params_dir + "/sapling-output.params"; +#endif + + bool spend_exists = fs::exists(spend_path); + bool output_exists = fs::exists(output_path); + + DEBUG_LOGF("verifySaplingParams: dir=%s\n", params_dir.c_str()); + DEBUG_LOGF(" spend: %s -> %s\n", spend_path.c_str(), spend_exists ? "found" : "MISSING"); + DEBUG_LOGF(" output: %s -> %s\n", output_path.c_str(), output_exists ? "found" : "MISSING"); + + return spend_exists && output_exists; +} + +ConnectionConfig Connection::parseConfFile(const std::string& path) +{ + ConnectionConfig config; + + std::ifstream file(path); + if (!file.is_open()) { + return config; + } + + std::string line; + while (std::getline(file, line)) { + // Skip empty lines and comments + if (line.empty() || line[0] == '#') { + continue; + } + + // Parse key=value + size_t eq_pos = line.find('='); + if (eq_pos == std::string::npos) { + continue; + } + + std::string key = line.substr(0, eq_pos); + std::string value = line.substr(eq_pos + 1); + + // Trim whitespace + while (!key.empty() && (key.back() == ' ' || key.back() == '\t')) { + key.pop_back(); + } + while (!value.empty() && (value[0] == ' ' || value[0] == '\t')) { + value.erase(0, 1); + } + + // Map to config + if (key == "rpcuser") { + config.rpcuser = value; + } else if (key == "rpcpassword") { + config.rpcpassword = value; + } else if (key == "rpcport") { + config.port = value; + } else if (key == "rpchost" || key == "rpcconnect") { + config.host = value; + } else if (key == "proxy") { + config.proxy = value; + } + } + + return config; +} + +ConnectionConfig Connection::autoDetectConfig() +{ + ConnectionConfig config; + + // Ensure data directory exists + std::string data_dir = getDefaultDataDir(); + if (!fs::exists(data_dir)) { + DEBUG_LOGF("Creating data directory: %s\n", data_dir.c_str()); + fs::create_directories(data_dir); + } + + // Try to find DRAGONX.conf + std::string conf_path = getDefaultConfPath(); + + if (fs::exists(conf_path)) { + config = parseConfFile(conf_path); + config.hush_dir = data_dir; + } else { + // Create a default config file + if (createDefaultConfig(conf_path)) { + config = parseConfFile(conf_path); + config.hush_dir = data_dir; + } + } + + // Set defaults for missing values + if (config.host.empty()) { + config.host = DRAGONX_DEFAULT_RPC_HOST; + } + if (config.port.empty()) { + config.port = DRAGONX_DEFAULT_RPC_PORT; + } + + return config; +} + +bool Connection::createDefaultConfig(const std::string& path) +{ + // Generate random rpcuser/rpcpassword + auto generateRandomString = [](int length) -> std::string { + const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + std::string result; + result.reserve(length); + + std::srand(static_cast(std::time(nullptr))); + for (int i = 0; i < length; i++) { + result += charset[std::rand() % (sizeof(charset) - 1)]; + } + return result; + }; + + std::string rpcuser = generateRandomString(16); + std::string rpcpassword = generateRandomString(32); + + std::ofstream file(path); + if (!file.is_open()) { + DEBUG_LOGF("Failed to create config file: %s\n", path.c_str()); + return false; + } + + file << "# DragonX configuration file\n"; + file << "# Auto-generated by DragonX Wallet\n"; + file << "\n"; + file << "rpcuser=" << rpcuser << "\n"; + file << "rpcpassword=" << rpcpassword << "\n"; + file << "rpcport=" << DRAGONX_DEFAULT_RPC_PORT << "\n"; + file << "server=1\n"; + file << "txindex=1\n"; + file << "addnode=195.201.20.230\n"; + file << "addnode=195.201.137.219\n"; + + file.close(); + + DEBUG_LOGF("Created default config file: %s\n", path.c_str()); + return true; +} + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/connection.h b/src/rpc/connection.h new file mode 100644 index 0000000..2bde8ff --- /dev/null +++ b/src/rpc/connection.h @@ -0,0 +1,80 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +namespace rpc { + +/** + * @brief Connection configuration + */ +struct ConnectionConfig { + std::string host = "127.0.0.1"; + std::string port = "21769"; + std::string rpcuser; + std::string rpcpassword; + std::string hush_dir; + std::string proxy; // SOCKS5 proxy for Tor + bool use_embedded = true; +}; + +/** + * @brief Manages connection to dragonxd + * + * Handles auto-detection of DRAGONX.conf, starting embedded daemon, + * and connection lifecycle. + */ +class Connection { +public: + Connection(); + ~Connection(); + + /** + * @brief Auto-detect and load connection config + * @return Config from DRAGONX.conf or defaults + */ + static ConnectionConfig autoDetectConfig(); + + /** + * @brief Get the default DRAGONX.conf location + */ + static std::string getDefaultConfPath(); + + /** + * @brief Get the default DragonX data directory + */ + static std::string getDefaultDataDir(); + + /** + * @brief Parse a DRAGONX.conf file + * @param path Path to conf file + * @return Parsed configuration + */ + static ConnectionConfig parseConfFile(const std::string& path); + + /** + * @brief Check if Sapling params exist + */ + static bool verifySaplingParams(); + + /** + * @brief Get the Sapling params directory + */ + static std::string getSaplingParamsDir(); + + /** + * @brief Create a default DRAGONX.conf file + * @param path Path to create the file + * @return true if created successfully + */ + static bool createDefaultConfig(const std::string& path); + +private: +}; + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/rpc_client.cpp b/src/rpc/rpc_client.cpp new file mode 100644 index 0000000..c7be81f --- /dev/null +++ b/src/rpc/rpc_client.cpp @@ -0,0 +1,599 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "rpc_client.h" +#include "../config/version.h" +#include "../util/base64.h" + +#include +#include +#include +#include "../util/logger.h" + +namespace dragonx { +namespace rpc { + +// Callback for libcurl to write response data +static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { + size_t totalSize = size * nmemb; + userp->append((char*)contents, totalSize); + return totalSize; +} + +// Private implementation using libcurl +class RPCClient::Impl { +public: + CURL* curl = nullptr; + struct curl_slist* headers = nullptr; + std::string url; + + ~Impl() { + if (headers) { + curl_slist_free_all(headers); + } + if (curl) { + curl_easy_cleanup(curl); + } + } +}; + +// Initialize curl globally (once) +static bool initCurl() { + static bool initialized = false; + if (!initialized) { + curl_global_init(CURL_GLOBAL_DEFAULT); + initialized = true; + } + return true; +} +static bool curl_init = initCurl(); + +RPCClient::RPCClient() : impl_(std::make_unique()) +{ +} + +RPCClient::~RPCClient() = default; + +bool RPCClient::connect(const std::string& host, const std::string& port, + const std::string& user, const std::string& password) +{ + std::lock_guard lk(curl_mutex_); + host_ = host; + port_ = port; + + // Create Basic auth header with proper base64 encoding + std::string credentials = user + ":" + password; + auth_ = util::base64_encode(credentials); + + // Build URL - use HTTP for localhost RPC (TLS not always enabled) + impl_->url = "http://" + host + ":" + port + "/"; + DEBUG_LOGF("Connecting to dragonxd at %s\n", impl_->url.c_str()); + + // Initialize curl handle + impl_->curl = curl_easy_init(); + if (!impl_->curl) { + DEBUG_LOGF("Failed to initialize curl\n"); + return false; + } + + // Set up headers - daemon expects text/plain, not application/json + impl_->headers = curl_slist_append(impl_->headers, "Content-Type: text/plain"); + std::string auth_header = "Authorization: Basic " + auth_; + impl_->headers = curl_slist_append(impl_->headers, auth_header.c_str()); + + // Configure curl + curl_easy_setopt(impl_->curl, CURLOPT_URL, impl_->url.c_str()); + curl_easy_setopt(impl_->curl, CURLOPT_HTTPHEADER, impl_->headers); + curl_easy_setopt(impl_->curl, CURLOPT_WRITEFUNCTION, WriteCallback); + curl_easy_setopt(impl_->curl, CURLOPT_TIMEOUT, 30L); + curl_easy_setopt(impl_->curl, CURLOPT_CONNECTTIMEOUT, 3L); + + // Test connection with getinfo + try { + json result = call("getinfo"); + if (result.contains("version")) { + connected_ = true; + DEBUG_LOGF("Connected to dragonxd v%d\n", result["version"].get()); + return true; + } + } catch (const std::exception& e) { + DEBUG_LOGF("Connection failed: %s\n", e.what()); + } + + connected_ = false; + return false; +} + +void RPCClient::disconnect() +{ + std::lock_guard lk(curl_mutex_); + connected_ = false; + if (impl_->curl) { + curl_easy_cleanup(impl_->curl); + impl_->curl = nullptr; + } + if (impl_->headers) { + curl_slist_free_all(impl_->headers); + impl_->headers = nullptr; + } +} + +json RPCClient::makePayload(const std::string& method, const json& params) +{ + return { + {"jsonrpc", "1.0"}, + {"id", "ObsidianDragon"}, + {"method", method}, + {"params", params} + }; +} + +json RPCClient::call(const std::string& method, const json& params) +{ + std::lock_guard lk(curl_mutex_); + if (!impl_->curl) { + throw std::runtime_error("Not connected"); + } + + json payload = makePayload(method, params); + std::string body = payload.dump(); + std::string response_data; + + // Set POST data + curl_easy_setopt(impl_->curl, CURLOPT_POSTFIELDS, body.c_str()); + curl_easy_setopt(impl_->curl, CURLOPT_POSTFIELDSIZE, (long)body.size()); + curl_easy_setopt(impl_->curl, CURLOPT_WRITEDATA, &response_data); + + // Perform request + CURLcode res = curl_easy_perform(impl_->curl); + + if (res != CURLE_OK) { + throw std::runtime_error("RPC request failed: " + std::string(curl_easy_strerror(res))); + } + + // Check HTTP response code + long http_code = 0; + curl_easy_getinfo(impl_->curl, CURLINFO_RESPONSE_CODE, &http_code); + + // Bitcoin/Hush RPC returns HTTP 500 for application-level errors + // (insufficient funds, bad params, etc.) with a valid JSON body. + // Parse the body first to extract the real error message. + if (http_code != 200) { + try { + json response = json::parse(response_data); + if (response.contains("error") && !response["error"].is_null()) { + std::string err_msg = response["error"]["message"].get(); + throw std::runtime_error(err_msg); + } + } catch (const json::exception&) { + // Body wasn't valid JSON — fall through to generic HTTP error + } + throw std::runtime_error("RPC error: HTTP " + std::to_string(http_code)); + } + + json response = json::parse(response_data); + + if (response.contains("error") && !response["error"].is_null()) { + std::string err_msg = response["error"]["message"].get(); + throw std::runtime_error("RPC error: " + err_msg); + } + + return response["result"]; +} + +std::string RPCClient::callRaw(const std::string& method, const json& params) +{ + std::lock_guard lk(curl_mutex_); + if (!impl_->curl) { + throw std::runtime_error("Not connected"); + } + + json payload = makePayload(method, params); + std::string body = payload.dump(); + std::string response_data; + + curl_easy_setopt(impl_->curl, CURLOPT_POSTFIELDS, body.c_str()); + curl_easy_setopt(impl_->curl, CURLOPT_POSTFIELDSIZE, (long)body.size()); + curl_easy_setopt(impl_->curl, CURLOPT_WRITEDATA, &response_data); + + CURLcode res = curl_easy_perform(impl_->curl); + if (res != CURLE_OK) { + throw std::runtime_error("RPC request failed: " + std::string(curl_easy_strerror(res))); + } + + long http_code = 0; + curl_easy_getinfo(impl_->curl, CURLINFO_RESPONSE_CODE, &http_code); + + if (http_code != 200) { + try { + json response = json::parse(response_data); + if (response.contains("error") && !response["error"].is_null()) { + std::string err_msg = response["error"]["message"].get(); + throw std::runtime_error(err_msg); + } + } catch (const json::exception&) {} + throw std::runtime_error("RPC error: HTTP " + std::to_string(http_code)); + } + + // Parse with ordered_json to preserve the daemon's original key order + nlohmann::ordered_json oj = nlohmann::ordered_json::parse(response_data); + if (oj.contains("error") && !oj["error"].is_null()) { + std::string err_msg = oj["error"]["message"].get(); + throw std::runtime_error("RPC error: " + err_msg); + } + + auto& result = oj["result"]; + if (result.is_null()) { + return "null"; + } else if (result.is_string()) { + // Return the raw string (not JSON-encoded) — caller wraps as needed + return result.get(); + } else { + return result.dump(4); + } +} + +void RPCClient::doRPC(const std::string& method, const json& params, Callback cb, ErrorCallback err) +{ + try { + json result = call(method, params); + if (cb) cb(result); + } catch (const std::exception& e) { + if (err) { + err(e.what()); + } else { + DEBUG_LOGF("RPC error (%s): %s\n", method.c_str(), e.what()); + } + } +} + +// High-level API implementations + +void RPCClient::getInfo(Callback cb, ErrorCallback err) +{ + doRPC("getinfo", {}, cb, err); +} + +void RPCClient::getBlockchainInfo(Callback cb, ErrorCallback err) +{ + doRPC("getblockchaininfo", {}, cb, err); +} + +void RPCClient::getMiningInfo(Callback cb, ErrorCallback err) +{ + doRPC("getmininginfo", {}, cb, err); +} + +void RPCClient::getBalance(Callback cb, ErrorCallback err) +{ + doRPC("getbalance", {}, cb, err); +} + +void RPCClient::z_getTotalBalance(Callback cb, ErrorCallback err) +{ + doRPC("z_gettotalbalance", {}, cb, err); +} + +void RPCClient::listUnspent(Callback cb, ErrorCallback err) +{ + doRPC("listunspent", {0}, cb, err); +} + +void RPCClient::z_listUnspent(Callback cb, ErrorCallback err) +{ + doRPC("z_listunspent", {0}, cb, err); +} + +void RPCClient::getAddressesByAccount(Callback cb, ErrorCallback err) +{ + doRPC("getaddressesbyaccount", {""}, cb, err); +} + +void RPCClient::z_listAddresses(Callback cb, ErrorCallback err) +{ + doRPC("z_listaddresses", {}, cb, err); +} + +void RPCClient::getNewAddress(Callback cb, ErrorCallback err) +{ + doRPC("getnewaddress", {}, cb, err); +} + +void RPCClient::z_getNewAddress(Callback cb, ErrorCallback err) +{ + doRPC("z_getnewaddress", {}, cb, err); +} + +void RPCClient::listTransactions(int count, Callback cb, ErrorCallback err) +{ + doRPC("listtransactions", {"", count}, cb, err); +} + +void RPCClient::z_viewTransaction(const std::string& txid, Callback cb, ErrorCallback err) +{ + doRPC("z_viewtransaction", {txid}, cb, err); +} + +void RPCClient::getRawTransaction(const std::string& txid, Callback cb, ErrorCallback err) +{ + doRPC("getrawtransaction", {txid, 1}, cb, err); +} + +void RPCClient::sendToAddress(const std::string& address, double amount, Callback cb, ErrorCallback err) +{ + doRPC("sendtoaddress", {address, amount}, cb, err); +} + +void RPCClient::z_sendMany(const std::string& from, const json& recipients, Callback cb, ErrorCallback err) +{ + doRPC("z_sendmany", {from, recipients}, cb, err); +} + +void RPCClient::setGenerate(bool generate, int threads, Callback cb, ErrorCallback err) +{ + doRPC("setgenerate", {generate, threads}, cb, err); +} + +void RPCClient::getNetworkHashPS(Callback cb, ErrorCallback err) +{ + doRPC("getnetworkhashps", {}, cb, err); +} + +void RPCClient::getLocalHashrate(Callback cb, ErrorCallback err) +{ + // RPC name is "getlocalsolps" (inherited from HUSH/Zcash daemon API) + // but DragonX uses RandomX, so the value is H/s not Sol/s + doRPC("getlocalsolps", {}, cb, err); +} + +void RPCClient::getPeerInfo(Callback cb, ErrorCallback err) +{ + doRPC("getpeerinfo", {}, cb, err); +} + +void RPCClient::listBanned(Callback cb, ErrorCallback err) +{ + doRPC("listbanned", {}, cb, err); +} + +void RPCClient::setBan(const std::string& ip, const std::string& command, Callback cb, ErrorCallback err, int bantime) +{ + // setban "ip" "add|remove" [bantime] [absolute] + doRPC("setban", {ip, command, bantime}, cb, err); +} + +void RPCClient::clearBanned(Callback cb, ErrorCallback err) +{ + doRPC("clearbanned", {}, cb, err); +} + +void RPCClient::dumpPrivKey(const std::string& address, Callback cb, ErrorCallback err) +{ + doRPC("dumpprivkey", {address}, cb, err); +} + +void RPCClient::z_exportKey(const std::string& address, Callback cb, ErrorCallback err) +{ + doRPC("z_exportkey", {address}, cb, err); +} + +void RPCClient::z_exportViewingKey(const std::string& address, Callback cb, ErrorCallback err) +{ + doRPC("z_exportviewingkey", {address}, cb, err); +} + +void RPCClient::importPrivKey(const std::string& key, bool rescan, Callback cb, ErrorCallback err) +{ + doRPC("importprivkey", {key, "", rescan}, cb, err); +} + +void RPCClient::z_importKey(const std::string& key, bool rescan, Callback cb, ErrorCallback err) +{ + doRPC("z_importkey", {key, rescan ? "yes" : "no"}, cb, err); +} + +void RPCClient::validateAddress(const std::string& address, Callback cb, ErrorCallback err) +{ + doRPC("validateaddress", {address}, cb, err); +} + +void RPCClient::getBlock(const std::string& hash_or_height, Callback cb, ErrorCallback err) +{ + doRPC("getblock", {hash_or_height}, cb, err); +} + +void RPCClient::stop(Callback cb, ErrorCallback err) +{ + doRPC("stop", {}, cb, err); +} + +void RPCClient::rescanBlockchain(int startHeight, Callback cb, ErrorCallback err) +{ + doRPC("rescanblockchain", {startHeight}, cb, err); +} + +void RPCClient::z_validateAddress(const std::string& address, Callback cb, ErrorCallback err) +{ + doRPC("z_validateaddress", {address}, cb, err); +} + +void RPCClient::getBlockHash(int height, Callback cb, ErrorCallback err) +{ + doRPC("getblockhash", {height}, cb, err); +} + +void RPCClient::getTransaction(const std::string& txid, Callback cb, ErrorCallback err) +{ + doRPC("gettransaction", {txid}, cb, err); +} + +void RPCClient::getWalletInfo(Callback cb, ErrorCallback err) +{ + doRPC("getwalletinfo", {}, cb, err); +} + +void RPCClient::encryptWallet(const std::string& passphrase, Callback cb, ErrorCallback err) +{ + doRPC("encryptwallet", {passphrase}, cb, err); +} + +void RPCClient::walletPassphrase(const std::string& passphrase, int timeout, Callback cb, ErrorCallback err) +{ + doRPC("walletpassphrase", {passphrase, timeout}, cb, err); +} + +void RPCClient::walletLock(Callback cb, ErrorCallback err) +{ + doRPC("walletlock", {}, cb, err); +} + +void RPCClient::walletPassphraseChange(const std::string& oldPass, const std::string& newPass, + Callback cb, ErrorCallback err) +{ + doRPC("walletpassphrasechange", {oldPass, newPass}, cb, err); +} + +void RPCClient::z_exportWallet(const std::string& filename, Callback cb, ErrorCallback err) +{ + doRPC("z_exportwallet", {filename}, cb, err); +} + +void RPCClient::z_importWallet(const std::string& filename, Callback cb, ErrorCallback err) +{ + doRPC("z_importwallet", {filename}, cb, err); +} + +void RPCClient::z_shieldCoinbase(const std::string& fromAddr, const std::string& toAddr, + double fee, int limit, Callback cb, ErrorCallback err) +{ + doRPC("z_shieldcoinbase", {fromAddr, toAddr, fee, limit}, cb, err); +} + +void RPCClient::z_mergeToAddress(const std::vector& fromAddrs, const std::string& toAddr, + double fee, int limit, Callback cb, ErrorCallback err) +{ + json addrs = json::array(); + for (const auto& addr : fromAddrs) { + addrs.push_back(addr); + } + doRPC("z_mergetoaddress", {addrs, toAddr, fee, 0, limit}, cb, err); +} + +void RPCClient::z_getOperationStatus(const std::vector& opids, Callback cb, ErrorCallback err) +{ + json ids = json::array(); + for (const auto& id : opids) { + ids.push_back(id); + } + doRPC("z_getoperationstatus", {ids}, cb, err); +} + +void RPCClient::z_getOperationResult(const std::vector& opids, Callback cb, ErrorCallback err) +{ + json ids = json::array(); + for (const auto& id : opids) { + ids.push_back(id); + } + doRPC("z_getoperationresult", {ids}, cb, err); +} + +void RPCClient::z_listReceivedByAddress(const std::string& address, int minconf, Callback cb, ErrorCallback err) +{ + doRPC("z_listreceivedbyaddress", {address, minconf}, cb, err); +} + +// Unified callback versions +void RPCClient::getInfo(UnifiedCallback cb) +{ + doRPC("getinfo", {}, + [cb](const json& result) { + if (cb) cb(result, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +void RPCClient::rescanBlockchain(int startHeight, UnifiedCallback cb) +{ + doRPC("rescanblockchain", {startHeight}, + [cb](const json& result) { + if (cb) cb(result, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +void RPCClient::z_shieldCoinbase(const std::string& fromAddr, const std::string& toAddr, + double fee, int limit, UnifiedCallback cb) +{ + doRPC("z_shieldcoinbase", {fromAddr, toAddr, fee, limit}, + [cb](const json& result) { + if (cb) cb(result, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +void RPCClient::z_mergeToAddress(const std::vector& fromAddrs, const std::string& toAddr, + double fee, int limit, UnifiedCallback cb) +{ + json addrs = json::array(); + for (const auto& addr : fromAddrs) { + addrs.push_back(addr); + } + doRPC("z_mergetoaddress", {addrs, toAddr, fee, 0, limit}, + [cb](const json& result) { + if (cb) cb(result, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +void RPCClient::z_getOperationStatus(const std::vector& opids, UnifiedCallback cb) +{ + json ids = json::array(); + for (const auto& id : opids) { + ids.push_back(id); + } + doRPC("z_getoperationstatus", {ids}, + [cb](const json& result) { + if (cb) cb(result, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +void RPCClient::getBlock(int height, UnifiedCallback cb) +{ + // First get block hash, then get block + getBlockHash(height, + [this, cb](const json& hashResult) { + std::string hash = hashResult.get(); + getBlock(hash, + [cb](const json& blockResult) { + if (cb) cb(blockResult, ""); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); + }, + [cb](const std::string& error) { + if (cb) cb(json{}, error); + } + ); +} + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/rpc_client.h b/src/rpc/rpc_client.h new file mode 100644 index 0000000..6a899e2 --- /dev/null +++ b/src/rpc/rpc_client.h @@ -0,0 +1,179 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "types.h" +#include +#include +#include +#include +#include + +namespace dragonx { +namespace rpc { + +using json = nlohmann::json; +using Callback = std::function; +using ErrorCallback = std::function; + +/** + * @brief JSON-RPC client for dragonxd + * + * Handles all communication with the dragonxd daemon via JSON-RPC. + */ +class RPCClient { +public: + RPCClient(); + ~RPCClient(); + + // Non-copyable + RPCClient(const RPCClient&) = delete; + RPCClient& operator=(const RPCClient&) = delete; + + /** + * @brief Connect to dragonxd + * @param host RPC host (default: 127.0.0.1) + * @param port RPC port (default: 18031) + * @param user RPC username + * @param password RPC password + * @return true if connection successful + */ + bool connect(const std::string& host, const std::string& port, + const std::string& user, const std::string& password); + + /** + * @brief Disconnect from dragonxd + */ + void disconnect(); + + /** + * @brief Check if connected + */ + bool isConnected() const { return connected_; } + + /** + * @brief Make a raw RPC call + * @param method RPC method name + * @param params Method parameters (optional) + * @return JSON response or null on error + */ + json call(const std::string& method, const json& params = json::array()); + + /** + * @brief Make a raw RPC call and return the result field as a string + * @param method RPC method name + * @param params Method parameters (optional) + * @return Raw JSON string of the "result" field (preserves key order) + */ + std::string callRaw(const std::string& method, const json& params = json::array()); + + // High-level API methods - mirror the Qt version + + // Info methods + void getInfo(Callback cb, ErrorCallback err = nullptr); + void getBlockchainInfo(Callback cb, ErrorCallback err = nullptr); + void getMiningInfo(Callback cb, ErrorCallback err = nullptr); + + // Balance methods + void getBalance(Callback cb, ErrorCallback err = nullptr); + void z_getTotalBalance(Callback cb, ErrorCallback err = nullptr); + void listUnspent(Callback cb, ErrorCallback err = nullptr); + void z_listUnspent(Callback cb, ErrorCallback err = nullptr); + + // Address methods + void getAddressesByAccount(Callback cb, ErrorCallback err = nullptr); + void z_listAddresses(Callback cb, ErrorCallback err = nullptr); + void getNewAddress(Callback cb, ErrorCallback err = nullptr); + void z_getNewAddress(Callback cb, ErrorCallback err = nullptr); + + // Transaction methods + void listTransactions(int count, Callback cb, ErrorCallback err = nullptr); + void z_viewTransaction(const std::string& txid, Callback cb, ErrorCallback err = nullptr); + void getRawTransaction(const std::string& txid, Callback cb, ErrorCallback err = nullptr); + void sendToAddress(const std::string& address, double amount, Callback cb, ErrorCallback err = nullptr); + void z_sendMany(const std::string& from, const json& recipients, Callback cb, ErrorCallback err = nullptr); + + // Mining methods + void setGenerate(bool generate, int threads, Callback cb, ErrorCallback err = nullptr); + void getNetworkHashPS(Callback cb, ErrorCallback err = nullptr); + void getLocalHashrate(Callback cb, ErrorCallback err = nullptr); + + // Peer methods + void getPeerInfo(Callback cb, ErrorCallback err = nullptr); + void listBanned(Callback cb, ErrorCallback err = nullptr); + void setBan(const std::string& ip, const std::string& command, Callback cb, ErrorCallback err = nullptr, int bantime = 86400); + void clearBanned(Callback cb, ErrorCallback err = nullptr); + + // Key management + void dumpPrivKey(const std::string& address, Callback cb, ErrorCallback err = nullptr); + void z_exportKey(const std::string& address, Callback cb, ErrorCallback err = nullptr); + void z_exportViewingKey(const std::string& address, Callback cb, ErrorCallback err = nullptr); + void importPrivKey(const std::string& key, bool rescan, Callback cb, ErrorCallback err = nullptr); + void z_importKey(const std::string& key, bool rescan, Callback cb, ErrorCallback err = nullptr); + + // Utility + void validateAddress(const std::string& address, Callback cb, ErrorCallback err = nullptr); + void z_validateAddress(const std::string& address, Callback cb, ErrorCallback err = nullptr); + void getBlock(const std::string& hash_or_height, Callback cb, ErrorCallback err = nullptr); + void getBlockHash(int height, Callback cb, ErrorCallback err = nullptr); + void getTransaction(const std::string& txid, Callback cb, ErrorCallback err = nullptr); + void getWalletInfo(Callback cb, ErrorCallback err = nullptr); + void stop(Callback cb, ErrorCallback err = nullptr); + + // Wallet maintenance + void rescanBlockchain(int startHeight, Callback cb, ErrorCallback err = nullptr); + + // Wallet encryption & locking + void encryptWallet(const std::string& passphrase, Callback cb, ErrorCallback err = nullptr); + void walletPassphrase(const std::string& passphrase, int timeout, Callback cb, ErrorCallback err = nullptr); + void walletLock(Callback cb, ErrorCallback err = nullptr); + void walletPassphraseChange(const std::string& oldPass, const std::string& newPass, + Callback cb, ErrorCallback err = nullptr); + + // Wallet export/import (for decrypt flow) + void z_exportWallet(const std::string& filename, Callback cb, ErrorCallback err = nullptr); + void z_importWallet(const std::string& filename, Callback cb, ErrorCallback err = nullptr); + + // Shielding operations + void z_shieldCoinbase(const std::string& fromAddr, const std::string& toAddr, + double fee, int limit, Callback cb, ErrorCallback err = nullptr); + void z_mergeToAddress(const std::vector& fromAddrs, const std::string& toAddr, + double fee, int limit, Callback cb, ErrorCallback err = nullptr); + + // Operation status monitoring + void z_getOperationStatus(const std::vector& opids, Callback cb, ErrorCallback err = nullptr); + void z_getOperationResult(const std::vector& opids, Callback cb, ErrorCallback err = nullptr); + + // Received transactions + void z_listReceivedByAddress(const std::string& address, int minconf, Callback cb, ErrorCallback err = nullptr); + + // Unified callback versions (result + error) + using UnifiedCallback = std::function; + void getInfo(UnifiedCallback cb); + void rescanBlockchain(int startHeight, UnifiedCallback cb); + void z_shieldCoinbase(const std::string& fromAddr, const std::string& toAddr, + double fee, int limit, UnifiedCallback cb); + void z_mergeToAddress(const std::vector& fromAddrs, const std::string& toAddr, + double fee, int limit, UnifiedCallback cb); + void z_getOperationStatus(const std::vector& opids, UnifiedCallback cb); + void getBlock(int height, UnifiedCallback cb); + +private: + json makePayload(const std::string& method, const json& params = json::array()); + void doRPC(const std::string& method, const json& params, Callback cb, ErrorCallback err); + + std::string host_; + std::string port_; + std::string auth_; // Base64 encoded "user:password" + bool connected_ = false; + mutable std::recursive_mutex curl_mutex_; // serializes all curl handle access + + // HTTP client (implementation hidden) + class Impl; + std::unique_ptr impl_; +}; + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/rpc_worker.cpp b/src/rpc/rpc_worker.cpp new file mode 100644 index 0000000..33455ec --- /dev/null +++ b/src/rpc/rpc_worker.cpp @@ -0,0 +1,135 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "rpc_worker.h" +#include +#include "../util/logger.h" + +namespace dragonx { +namespace rpc { + +RPCWorker::RPCWorker() = default; + +RPCWorker::~RPCWorker() +{ + stop(); +} + +void RPCWorker::start() +{ + if (running_.load(std::memory_order_relaxed)) return; + + running_.store(true, std::memory_order_release); + thread_ = std::thread(&RPCWorker::run, this); +} + +void RPCWorker::stop() +{ + if (!running_.load(std::memory_order_relaxed) && !thread_.joinable()) return; + + // Signal stop if not already signaled + requestStop(); + + if (thread_.joinable()) { + thread_.join(); + } + + // Discard pending tasks + { + std::lock_guard lk(taskMtx_); + tasks_.clear(); + } +} + +void RPCWorker::requestStop() +{ + if (!running_.load(std::memory_order_relaxed)) return; + + { + std::lock_guard lk(taskMtx_); + running_.store(false, std::memory_order_release); + } + taskCv_.notify_one(); +} + +void RPCWorker::post(WorkFn work) +{ + { + std::lock_guard lk(taskMtx_); + tasks_.push_back(std::move(work)); + } + taskCv_.notify_one(); +} + +int RPCWorker::drainResults() +{ + // Swap the result queue under the lock, then execute outside the lock + // to minimise contention with the worker thread. + std::deque batch; + { + std::lock_guard lk(resultMtx_); + batch.swap(results_); + } + + int count = 0; + for (auto& cb : batch) { + if (cb) { + try { + cb(); + } catch (const std::exception& e) { + DEBUG_LOGF("[RPCWorker] Main-thread callback threw: %s\n", e.what()); + } catch (...) { + DEBUG_LOGF("[RPCWorker] Main-thread callback threw unknown exception\n"); + } + ++count; + } + } + return count; +} + +bool RPCWorker::hasPendingResults() const +{ + std::lock_guard lk(resultMtx_); + return !results_.empty(); +} + +void RPCWorker::run() +{ + while (true) { + WorkFn task; + + // Wait for a task or stop signal + { + std::unique_lock lk(taskMtx_); + taskCv_.wait(lk, [this] { + return !tasks_.empty() || !running_.load(std::memory_order_acquire); + }); + + if (!running_.load(std::memory_order_acquire) && tasks_.empty()) { + break; + } + + if (!tasks_.empty()) { + task = std::move(tasks_.front()); + tasks_.pop_front(); + } + } + + if (!task) continue; + + // Execute the work function (blocking I/O happens here) + try { + MainCb result = task(); + if (result) { + std::lock_guard lk(resultMtx_); + results_.push_back(std::move(result)); + } + } catch (const std::exception& e) { + DEBUG_LOGF("[RPCWorker] Task threw: %s\n", e.what()); + } + } +} + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/rpc_worker.h b/src/rpc/rpc_worker.h new file mode 100644 index 0000000..7891bfb --- /dev/null +++ b/src/rpc/rpc_worker.h @@ -0,0 +1,93 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dragonx { +namespace rpc { + +/** + * @brief Background worker thread for RPC calls + * + * Provides a single-threaded task queue so that all RPC/HTTP work happens + * off the UI thread. The caller submits a *work function* that runs on the + * worker thread and returns a *result callback* that is queued for execution + * on the main (UI) thread during drainResults(). + * + * Usage from the main thread: + * + * worker.post([&rpc]() -> RPCWorker::MainCb { + * json r = rpc.call("getinfo"); // runs on worker thread + * return [r]() { applyToState(r); }; // runs on main thread + * }); + * + * // Each frame: + * worker.drainResults(); + */ +class RPCWorker { +public: + /// Callback executed on the main thread after work completes. + using MainCb = std::function; + + /// Work function executed on the background thread. + /// Must return a MainCb (may return nullptr to skip main-thread step). + using WorkFn = std::function; + + RPCWorker(); + ~RPCWorker(); + + // Non-copyable + RPCWorker(const RPCWorker&) = delete; + RPCWorker& operator=(const RPCWorker&) = delete; + + /// Start the worker thread. Safe to call if already running. + void start(); + + /// Stop the worker thread and join. Pending tasks are discarded. + void stop(); + + /// Signal the worker thread to stop (non-blocking, no join). + /// Call stop() later to join the thread. + void requestStop(); + + /// Submit work to run on the background thread. + /// @param work Function that performs blocking I/O and returns a MainCb. + void post(WorkFn work); + + /// Drain completed result callbacks on the main thread. + /// Call once per frame from update(). + /// @return Number of callbacks executed. + int drainResults(); + + /// True when there are completed results waiting for the main thread. + bool hasPendingResults() const; + + /// True when the worker thread is running. + bool isRunning() const { return running_.load(std::memory_order_relaxed); } + +private: + void run(); // worker thread entry point + + std::thread thread_; + std::atomic running_{false}; + + // ---- Task queue (produced by main thread, consumed by worker) ---- + std::mutex taskMtx_; + std::condition_variable taskCv_; + std::deque tasks_; + + // ---- Result queue (produced by worker, consumed by main thread) ---- + mutable std::mutex resultMtx_; + std::deque results_; +}; + +} // namespace rpc +} // namespace dragonx diff --git a/src/rpc/types.h b/src/rpc/types.h new file mode 100644 index 0000000..f1017e3 --- /dev/null +++ b/src/rpc/types.h @@ -0,0 +1,95 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include + +namespace dragonx { +namespace rpc { + +// Transaction types +enum class TxType { + Sent, + Received, + Mined, + Unknown +}; + +// Transaction info +struct Transaction { + std::string txid; + TxType type = TxType::Unknown; + int64_t timestamp = 0; + std::string address; + double amount = 0.0; + int confirmations = 0; + std::string memo; + std::string from_address; +}; + +// Peer info +struct Peer { + int64_t id = 0; + std::string address; + std::string tls_cipher; + bool tls_verified = false; + int64_t conntime = 0; + int banscore = 0; + int protocol_version = 0; + std::string subver; + int64_t bytes_sent = 0; + int64_t bytes_received = 0; + double pingtime = 0.0; +}; + +// Banned peer info +struct BannedPeer { + std::string address; + std::string subnet; + int64_t banned_until = 0; + int64_t asn = 0; +}; + +// Unspent output (UTXO) +struct UnspentOutput { + std::string address; + std::string txid; + int vout = 0; + double amount = 0.0; + int confirmations = 0; + bool spendable = true; +}; + +// Address balance +struct AddressBalance { + std::string address; + double balance = 0.0; + bool is_shielded = false; +}; + +// Blockchain info +struct BlockchainInfo { + int blocks = 0; + int headers = 0; + std::string bestblockhash; + double difficulty = 0.0; + double verificationprogress = 0.0; + bool syncing = false; +}; + +// Mining info +struct MiningInfo { + int blocks = 0; + double difficulty = 0.0; + double networkhashps = 0.0; + double localhashps = 0.0; + int genproclimit = 0; + bool generate = false; +}; + +} // namespace rpc +} // namespace dragonx diff --git a/src/ui/effects/acrylic.cpp b/src/ui/effects/acrylic.cpp new file mode 100644 index 0000000..543d17b --- /dev/null +++ b/src/ui/effects/acrylic.cpp @@ -0,0 +1,1695 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "acrylic.h" +#include "../schema/ui_schema.h" +#include "../../util/noise_texture.h" +#include "../../util/logger.h" + +#ifdef DRAGONX_HAS_GLAD +#include + +// GL constants that may be missing from minimal GLAD builds +#ifndef GL_VERSION +#define GL_VERSION 0x1F02 +#endif +#ifndef GL_RENDERER +#define GL_RENDERER 0x1F01 +#endif +#ifndef GL_MAX_TEXTURE_SIZE +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#endif +#ifndef GL_SCISSOR_TEST +#define GL_SCISSOR_TEST 0x0C11 +#endif + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// Composite Shader Source (GLEW Available) +// ============================================================================ + +namespace { + +const char* COMPOSITE_VERTEX = R"glsl( +#version 330 core + +layout (location = 0) in vec2 aPos; +layout (location = 1) in vec2 aTexCoord; + +out vec2 vTexCoord; +out vec2 vNoiseCoord; + +uniform vec2 uTexScale; // For noise tiling + +void main() +{ + gl_Position = vec4(aPos, 0.0, 1.0); + vTexCoord = aTexCoord; + vNoiseCoord = aTexCoord * uTexScale; // Tile noise +} +)glsl"; + +const char* COMPOSITE_FRAGMENT = R"glsl( +#version 330 core + +in vec2 vTexCoord; +in vec2 vNoiseCoord; + +out vec4 FragColor; + +uniform sampler2D uBlurTex; +uniform sampler2D uNoiseTex; + +uniform vec4 uTintColor; +uniform float uTintOpacity; +uniform float uLuminosity; +uniform float uNoiseOpacity; + +void main() +{ + // Sample blurred background + vec3 blur = texture(uBlurTex, vTexCoord).rgb; + + // Apply luminosity (desaturation effect) + float lum = dot(blur, vec3(0.299, 0.587, 0.114)); + blur = mix(vec3(lum), blur, uLuminosity); + + // Apply tint color + vec3 tinted = mix(blur, uTintColor.rgb, uTintOpacity); + + // Sample and apply noise + float noise = texture(uNoiseTex, vNoiseCoord).r; + // Noise is centered at 0.5, so we subtract 0.5 and scale + float noiseOffset = (noise - 0.5) * 2.0 * uNoiseOpacity; + tinted += vec3(noiseOffset); + + // Output with slight transparency + FragColor = vec4(tinted, uTintColor.a); +} +)glsl"; + +bool compileShader(GLuint shader, const char* source) +{ + glShaderSource(shader, 1, &source, nullptr); + glCompileShader(shader); + + GLint success; + glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + + if (!success) { + GLint logLength; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); + std::vector log(logLength + 1); + glGetShaderInfoLog(shader, logLength, nullptr, log.data()); + DEBUG_LOGF("Shader compile error:\n%s\n", log.data()); + return false; + } + return true; +} + +bool linkProgram(GLuint program) +{ + glLinkProgram(program); + + GLint success; + glGetProgramiv(program, GL_LINK_STATUS, &success); + + if (!success) { + GLint logLength; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); + std::vector log(logLength + 1); + glGetProgramInfoLog(program, logLength, nullptr, log.data()); + DEBUG_LOGF("Program link error:\n%s\n", log.data()); + return false; + } + return true; +} + +} // anonymous namespace + +// ============================================================================ +// AcrylicMaterial Implementation (GLEW Available) +// ============================================================================ + +AcrylicMaterial::AcrylicMaterial() = default; + +AcrylicMaterial::~AcrylicMaterial() +{ + shutdown(); +} + +bool AcrylicMaterial::init() +{ + if (initialized_) return true; + + DEBUG_LOGF("AcrylicMaterial: Initializing...\n"); + + // Initialize blur shader + if (!blurShader_.init()) { + DEBUG_LOGF("AcrylicMaterial: Failed to init blur shader\n"); + return false; + } + + // Initialize fullscreen quad + if (!quad_.init()) { + DEBUG_LOGF("AcrylicMaterial: Failed to init fullscreen quad\n"); + return false; + } + + // Generate noise texture (texture size is a fixed default; + // noise-tile-scale is read per-frame once schema is loaded) + if (!noiseTexture_.generate(noiseTextureSize_, 0.5f)) { + DEBUG_LOGF("AcrylicMaterial: Failed to generate noise texture\n"); + return false; + } + + // Create composite shader + GLuint vs = glCreateShader(GL_VERTEX_SHADER); + GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); + + if (!compileShader(vs, COMPOSITE_VERTEX)) { + glDeleteShader(vs); + glDeleteShader(fs); + return false; + } + + if (!compileShader(fs, COMPOSITE_FRAGMENT)) { + glDeleteShader(vs); + glDeleteShader(fs); + return false; + } + + compositeShader_ = glCreateProgram(); + glAttachShader(compositeShader_, vs); + glAttachShader(compositeShader_, fs); + + if (!linkProgram(compositeShader_)) { + glDeleteProgram(compositeShader_); + glDeleteShader(vs); + glDeleteShader(fs); + compositeShader_ = 0; + return false; + } + + glDeleteShader(vs); + glDeleteShader(fs); + + // Get uniform locations + uCompositeTintColor_ = glGetUniformLocation(compositeShader_, "uTintColor"); + uCompositeTintOpacity_ = glGetUniformLocation(compositeShader_, "uTintOpacity"); + uCompositeLuminosity_ = glGetUniformLocation(compositeShader_, "uLuminosity"); + uCompositeNoiseOpacity_ = glGetUniformLocation(compositeShader_, "uNoiseOpacity"); + uCompositeBlurTex_ = glGetUniformLocation(compositeShader_, "uBlurTex"); + uCompositeNoiseTex_ = glGetUniformLocation(compositeShader_, "uNoiseTex"); + uCompositeTexScale_ = glGetUniformLocation(compositeShader_, "uTexScale"); + + DEBUG_LOGF("AcrylicMaterial: Composite shader uniforms:\n"); + DEBUG_LOGF(" uTintColor=%d, uTintOpacity=%d, uLuminosity=%d\n", + uCompositeTintColor_, uCompositeTintOpacity_, uCompositeLuminosity_); + DEBUG_LOGF(" uNoiseOpacity=%d, uBlurTex=%d, uNoiseTex=%d, uTexScale=%d\n", + uCompositeNoiseOpacity_, uCompositeBlurTex_, uCompositeNoiseTex_, uCompositeTexScale_); + + // Detect system capabilities + refreshCapabilities(); + currentFallback_ = detectFallback(); + + initialized_ = true; + DEBUG_LOGF("AcrylicMaterial: Initialized successfully (fallback mode: %d)\n", + static_cast(currentFallback_)); + + return true; +} + +void AcrylicMaterial::shutdown() +{ + if (!initialized_) return; + + captureBuffer_.destroy(); + blurBuffers_.destroy(); + blurShader_.destroy(); + quad_.destroy(); + noiseTexture_.destroy(); + + if (compositeShader_) { + glDeleteProgram(compositeShader_); + compositeShader_ = 0; + } + + initialized_ = false; + viewportWidth_ = 0; + viewportHeight_ = 0; + + DEBUG_LOGF("AcrylicMaterial: Shutdown complete\n"); +} + +void AcrylicMaterial::resize(int width, int height) +{ + if (width == viewportWidth_ && height == viewportHeight_) { + return; // No change + } + + viewportWidth_ = width; + viewportHeight_ = height; + blurCacheValid_ = false; // Invalidate cache on resize + + // Determine blur buffer size based on quality + int blurWidth = width; + int blurHeight = height; + + switch (settings_.quality) { + case AcrylicQuality::Low: + blurWidth /= 4; + blurHeight /= 4; + break; + case AcrylicQuality::Medium: + blurWidth /= 2; + blurHeight /= 2; + break; + case AcrylicQuality::High: + // Full resolution + break; + case AcrylicQuality::Off: + // No blur buffers needed + return; + } + + // Ensure minimum size + blurWidth = std::max(64, blurWidth); + blurHeight = std::max(64, blurHeight); + + // Initialize/resize buffers + if (!captureBuffer_.isValid()) { + captureBuffer_.init(width, height); + } else { + captureBuffer_.resize(width, height); + } + + if (!blurBuffers_.isValid()) { + blurBuffers_.init(blurWidth, blurHeight, true); // float16 to avoid banding + } else { + blurBuffers_.resize(blurWidth, blurHeight); + } + + DEBUG_LOGF("AcrylicMaterial: Resized to %dx%d (blur: %dx%d)\n", + width, height, blurWidth, blurHeight); + dirtyFrames_ = 2; // recapture after resize +} + +void AcrylicMaterial::captureBackground() +{ + if (!initialized_ || shouldSkipEffect()) { + return; + } + + if (viewportWidth_ <= 0 || viewportHeight_ <= 0) { + return; + } + + // P7: Only recapture when the background has been marked dirty + if (dirtyFrames_ <= 0) { + return; + } + --dirtyFrames_; + + // Capture current screen content + captureBuffer_.captureScreen(viewportWidth_, viewportHeight_); + hasValidCapture_ = true; + blurCacheValid_ = false; // New capture invalidates blur cache +} + +void AcrylicMaterial::captureBackgroundDirect() +{ + if (!initialized_ || shouldSkipEffect()) { + return; + } + + if (viewportWidth_ <= 0 || viewportHeight_ <= 0) { + return; + } + + // Only recapture when dirty (resize, theme change, first frame). + if (dirtyFrames_ <= 0) { + return; + } + --dirtyFrames_; + + // At this point during RenderDrawData(), only the background draw + // list has been rasterized to framebuffer 0 — the UI windows have + // not been drawn yet. blit from FB 0 into our capture buffer. + // Disable scissor test: glBlitFramebuffer applies scissor to the + // draw framebuffer, and ImGui has scissor enabled during rendering. + // The subsequent ImDrawCallback_ResetRenderState re-enables it. + glDisable(GL_SCISSOR_TEST); + captureBuffer_.captureScreen(viewportWidth_, viewportHeight_); + + hasValidCapture_ = true; + blurCacheValid_ = false; // force re-blur with fresh capture +} + +bool AcrylicMaterial::shouldSkipEffect() const +{ + return !settings_.enabled || + settings_.reducedTransparency || + settings_.quality == AcrylicQuality::Off; +} + +void AcrylicMaterial::setQuality(AcrylicQuality quality) +{ + if (settings_.quality != quality) { + settings_.quality = quality; + blurCacheValid_ = false; // Quality change invalidates cache + // Trigger resize to adjust buffer sizes + int w = viewportWidth_, h = viewportHeight_; + viewportWidth_ = viewportHeight_ = 0; + resize(w, h); + } +} + +void AcrylicMaterial::applyBlur(float radius) +{ + if (!blurBuffers_.isValid() || !blurShader_.isValid()) { + return; + } + + // Apply blur radius multiplier from settings + float scaledRadius = radius * settings_.blurRadiusMultiplier; + + // Skip blur entirely when multiplier is at or near zero — show sharp background + if (scaledRadius < 0.5f) { + // Still blit capture to blur source so getBlurredTexture() returns + // the un-blurred captured background + int blurW = blurBuffers_.getSource().getWidth(); + int blurH = blurBuffers_.getSource().getHeight(); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + GLuint srcFbo = captureBuffer_.getFbo(); + GLuint dstFbo = blurBuffers_.getSource().getFbo(); + glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFbo); + glBlitFramebuffer(0, 0, viewportWidth_, viewportHeight_, + 0, 0, blurW, blurH, + GL_COLOR_BUFFER_BIT, GL_LINEAR); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + lastBlurRadius_ = scaledRadius; + blurCacheValid_ = true; + return; + } + + // Check cache - skip blur if same radius and cache is valid + if (blurCacheValid_ && std::abs(scaledRadius - lastBlurRadius_) < 0.1f) { + return; // Use cached blur result + } + + int blurWidth = blurBuffers_.getSource().getWidth(); + int blurHeight = blurBuffers_.getSource().getHeight(); + + // Determine number of passes based on quality + int passes = 1; + float effectiveRadius = scaledRadius; + + switch (settings_.quality) { + case AcrylicQuality::Low: + passes = 1; + effectiveRadius = scaledRadius * 0.5f; + break; + case AcrylicQuality::Medium: + passes = 2; + break; + case AcrylicQuality::High: + passes = 3; + break; + default: + return; + } + + // Copy captured content into the first blur buffer, scaling down + // from full viewport resolution to the blur buffer resolution. + // Disable scissor/depth/blend BEFORE the blit — glBlitFramebuffer + // applies scissor to the draw FBO, and a stale rect would clip it. + glDisable(GL_SCISSOR_TEST); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + { + GLuint srcFbo = captureBuffer_.getFbo(); + GLuint dstFbo = blurBuffers_.getSource().getFbo(); + glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFbo); + glBlitFramebuffer( + 0, 0, viewportWidth_, viewportHeight_, // src rect (full res) + 0, 0, blurWidth, blurHeight, // dst rect (blur res) + GL_COLOR_BUFFER_BIT, GL_LINEAR); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } + + blurShader_.bind(); + blurShader_.setResolution(blurWidth, blurHeight); + blurShader_.setTexture(0); + + for (int pass = 0; pass < passes; pass++) { + float passRadius = effectiveRadius / passes; + blurShader_.setRadius(passRadius); + + // Horizontal pass + blurBuffers_.getDest().bind(); + blurShader_.setDirection(true); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, blurBuffers_.getSourceTexture()); + quad_.draw(); + blurBuffers_.swap(); + + // Vertical pass + blurBuffers_.getDest().bind(); + blurShader_.setDirection(false); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, blurBuffers_.getSourceTexture()); + quad_.draw(); + blurBuffers_.swap(); + } + + blurShader_.unbind(); + blurBuffers_.getDest().unbind(); + + // Restore viewport + glViewport(0, 0, viewportWidth_, viewportHeight_); + + static bool s_blurRunTraced = false; + if (!s_blurRunTraced) { + s_blurRunTraced = true; + DEBUG_LOGF("[Acrylic] applyBlur: %d passes, radius=%.1f, blurSize=%dx%d " + "srcFBO=%u dstTex=%u\n", + passes, effectiveRadius, blurWidth, blurHeight, + captureBuffer_.getFbo(), blurBuffers_.getSourceTexture()); + } + + // Update cache state + lastBlurRadius_ = scaledRadius; + blurCacheValid_ = true; +} + +ImTextureID AcrylicMaterial::getBlurredTexture() const +{ + return (ImTextureID)(intptr_t)blurBuffers_.getSourceTexture(); +} + +ImTextureID AcrylicMaterial::getNoiseTexture() const +{ + return (ImTextureID)(intptr_t)noiseTexture_.getTexture(); +} + +void AcrylicMaterial::drawRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding) +{ + if (!initialized_) return; + + // Update fallback mode (could change based on settings) + currentFallback_ = detectFallback(); + + + // Fallback solid fill — scaled by UI opacity for card transparency + auto scaledFallback = [&]() { + ImVec4 c = params.fallbackColor; + c.w *= settings_.uiOpacity; + return ImGui::ColorConvertFloat4ToU32(c); + }; + + // If acrylic is disabled in params, always use solid fallback + if (!params.enabled) { + drawList->AddRectFilled(pMin, pMax, scaledFallback(), rounding); + return; + } + + // Handle fallback modes + switch (currentFallback_) { + case AcrylicFallback::Solid: + drawList->AddRectFilled(pMin, pMax, scaledFallback(), rounding); + return; + + case AcrylicFallback::TintedOnly: + drawTintedRect(drawList, pMin, pMax, params, rounding); + return; + + case AcrylicFallback::None: + default: + // Continue with full acrylic rendering + break; + } + + // No valid background capture yet (first frame before the + // BackgroundDrawList callback has fired). Fall back to tinted. + if (!hasValidCapture_) { + drawTintedRect(drawList, pMin, pMax, params, rounding); + return; + } + + // Apply blur to captured background + applyBlur(params.blurRadius); + + // Calculate UV coordinates for sampling the blur FBO texture. + // With multi-viewport enabled, ImGui draw coordinates are in + // absolute OS screen space. The FBO capture covers only the main + // window, so we must subtract the main viewport's screen position + // to get window-local coordinates before dividing by viewport size. + // OpenGL FBO textures have V=0 at the bottom and V=1 at the top. + // ImGui screen coordinates have Y=0 at the top and Y=H at bottom. + // So texture V for screen Y is: V = 1.0 - localY/H + ImGuiViewport* mainVp = ImGui::GetMainViewport(); + float localX0 = pMin.x - mainVp->Pos.x; + float localY0 = pMin.y - mainVp->Pos.y; + float localX1 = pMax.x - mainVp->Pos.x; + float localY1 = pMax.y - mainVp->Pos.y; + float u0 = localX0 / viewportWidth_; + float v0 = 1.0f - localY0 / viewportHeight_; // V at top-left (high) + float u1 = localX1 / viewportWidth_; + float v1 = 1.0f - localY1 / viewportHeight_; // V at bottom-right (low) + + // Draw the blurred background. The glass opacity comes from + // fallbackColor.w — blur always renders at full strength. + // UI opacity is handled separately by card surface alpha. + ImTextureID blurTex = getBlurredTexture(); + uint8_t glassAlpha = static_cast( + std::min(255.0f, std::max(0.0f, params.fallbackColor.w * 255.0f))); + + if (blurTex) { + drawList->AddImageRounded( + blurTex, + pMin, pMax, + ImVec2(u0, v0), ImVec2(u1, v1), + IM_COL32(255, 255, 255, glassAlpha), + rounding + ); + } + + // Noise grain overlay — single draw call via pre-tiled texture + if (params.noiseOpacity > 0.0f && settings_.noiseOpacityMultiplier > 0.0f) { + float maxAlpha = schema::UI().drawElement("backdrop", "noise-max-alpha").sizeOr(6.0f); + float scaledNoise = params.noiseOpacity * settings_.noiseOpacityMultiplier; + uint8_t alpha = static_cast(std::min(255.0f, maxAlpha * scaledNoise * 50.0f)); + ImU32 col = IM_COL32(255, 255, 255, alpha); + drawList->PushClipRect(pMin, pMax, true); + dragonx::util::DrawTiledNoiseRect(drawList, pMin, pMax, col); + drawList->PopClipRect(); + } +} + +// ============================================================================ +// Preset Parameters +// ============================================================================ + +AcrylicParams AcrylicMaterial::getDarkPreset() +{ + AcrylicParams params; + params.tintColor = ImVec4(0.1f, 0.1f, 0.12f, 0.95f); + params.tintOpacity = 0.75f; + params.luminosityOpacity = 0.6f; + params.blurRadius = 30.0f; + params.noiseOpacity = 0.02f; + params.fallbackColor = ImVec4(0.12f, 0.12f, 0.14f, 0.82f); + return params; +} + +AcrylicParams AcrylicMaterial::getLightPreset() +{ + AcrylicParams params; + params.tintColor = ImVec4(0.95f, 0.95f, 0.97f, 0.95f); + params.tintOpacity = 0.80f; + params.luminosityOpacity = 0.7f; + params.blurRadius = 25.0f; + params.noiseOpacity = 0.02f; + params.fallbackColor = ImVec4(0.96f, 0.96f, 0.98f, 0.82f); + return params; +} + +AcrylicParams AcrylicMaterial::getDragonXPreset() +{ + AcrylicParams params; + // Deep dragon red tint + params.tintColor = ImVec4(0.6f, 0.15f, 0.1f, 0.95f); // #993319 + params.tintOpacity = 0.85f; + params.luminosityOpacity = 0.3f; // More desaturated for dramatic effect + params.blurRadius = 40.0f; + params.noiseOpacity = 0.025f; + params.fallbackColor = ImVec4(0.5f, 0.12f, 0.08f, 0.82f); + return params; +} + +AcrylicParams AcrylicMaterial::getPopupPreset() +{ + AcrylicParams params; + params.tintColor = ImVec4(0.15f, 0.15f, 0.18f, 0.95f); + params.tintOpacity = 0.70f; + params.luminosityOpacity = 0.5f; + params.blurRadius = 30.0f; + params.noiseOpacity = 0.02f; + params.fallbackColor = ImVec4(0.18f, 0.18f, 0.2f, 0.88f); + return params; +} + +AcrylicParams AcrylicMaterial::getSidebarPreset() +{ + AcrylicParams params; + params.tintColor = ImVec4(0.08f, 0.08f, 0.1f, 0.95f); + params.tintOpacity = 0.80f; + params.luminosityOpacity = 0.4f; + params.blurRadius = 35.0f; + params.noiseOpacity = 0.02f; + params.fallbackColor = ImVec4(0.1f, 0.1f, 0.12f, 0.85f); + return params; +} + +// ============================================================================ +// Fallback System +// ============================================================================ + +void AcrylicMaterial::refreshCapabilities() +{ + // Get OpenGL info + const char* version = reinterpret_cast(glGetString(GL_VERSION)); + const char* renderer = reinterpret_cast(glGetString(GL_RENDERER)); + + capabilities_.glVersion = version ? version : "Unknown"; + capabilities_.glRenderer = renderer ? renderer : "Unknown"; + + // Get max texture size + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &capabilities_.maxTextureSize); + + // Check for required features + capabilities_.hasFramebufferSupport = (glGenFramebuffers != nullptr && + glBindFramebuffer != nullptr); + capabilities_.hasShaderSupport = (glCreateShader != nullptr && + glCreateProgram != nullptr); + capabilities_.hasTextureSupport = (capabilities_.maxTextureSize >= 1024); + + // Detect low-end GPU based on renderer string + std::string rendererLower = capabilities_.glRenderer; + std::transform(rendererLower.begin(), rendererLower.end(), + rendererLower.begin(), ::tolower); + + capabilities_.isLowEndGPU = + (rendererLower.find("intel") != std::string::npos && + rendererLower.find("hd") != std::string::npos) || + (rendererLower.find("mesa") != std::string::npos && + rendererLower.find("llvmpipe") != std::string::npos) || + (rendererLower.find("software") != std::string::npos) || + (rendererLower.find("swrast") != std::string::npos); + + // Check battery status on Linux + capabilities_.isOnBattery = false; +#ifdef __linux__ + // Check /sys/class/power_supply/*/status + FILE* f = fopen("/sys/class/power_supply/BAT0/status", "r"); + if (f) { + char status[32] = {0}; + if (fgets(status, sizeof(status), f)) { + capabilities_.isOnBattery = (strncmp(status, "Discharging", 11) == 0); + } + fclose(f); + } +#endif + + DEBUG_LOGF("AcrylicMaterial: Capabilities detected:\n"); + DEBUG_LOGF(" GL Version: %s\n", capabilities_.glVersion.c_str()); + DEBUG_LOGF(" GL Renderer: %s\n", capabilities_.glRenderer.c_str()); + DEBUG_LOGF(" Max Texture Size: %d\n", capabilities_.maxTextureSize); + DEBUG_LOGF(" Framebuffer Support: %s\n", capabilities_.hasFramebufferSupport ? "Yes" : "No"); + DEBUG_LOGF(" Shader Support: %s\n", capabilities_.hasShaderSupport ? "Yes" : "No"); + DEBUG_LOGF(" Low-End GPU: %s\n", capabilities_.isLowEndGPU ? "Yes" : "No"); + DEBUG_LOGF(" On Battery: %s\n", capabilities_.isOnBattery ? "Yes" : "No"); +} + +AcrylicFallback AcrylicMaterial::detectFallback() const +{ + // Check if forced fallback is set + if (hasForcedFallback_) { + return forcedFallback_; + } + + // User preference: reduced transparency + if (settings_.reducedTransparency) { + return AcrylicFallback::Solid; + } + + // Check OpenGL capabilities + if (!capabilities_.hasFramebufferSupport || !capabilities_.hasShaderSupport) { + return AcrylicFallback::Solid; + } + + // Texture size too small + if (capabilities_.maxTextureSize < 1024) { + return AcrylicFallback::Solid; + } + + // Quality set to Off + if (settings_.quality == AcrylicQuality::Off) { + return AcrylicFallback::TintedOnly; + } + + // Low-end GPU detection + if (capabilities_.isLowEndGPU && settings_.quality == AcrylicQuality::High) { + return AcrylicFallback::TintedOnly; + } + + // Battery mode (if user enabled) + if (settings_.disableOnBattery && capabilities_.isOnBattery) { + return AcrylicFallback::TintedOnly; + } + + // Global disable + if (!settings_.enabled) { + return AcrylicFallback::TintedOnly; + } + + return AcrylicFallback::None; +} + +void AcrylicMaterial::drawTintedRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding) +{ + // Draw semi-transparent tint without blur + // This is the "Tinted Only" fallback mode (not affected by UI opacity) + ImU32 tintCol = ImGui::ColorConvertFloat4ToU32( + ImVec4(params.tintColor.x, params.tintColor.y, params.tintColor.z, + params.tintColor.w * params.tintOpacity * 0.9f) + ); + drawList->AddRectFilled(pMin, pMax, tintCol, rounding); + + // Still add noise overlay for visual interest (W11-style) + ImTextureID noiseTex = getNoiseTexture(); + if (noiseTex && params.noiseOpacity > 0.0f && settings_.noiseOpacityMultiplier > 0.0f) { + float maxAlpha = schema::UI().drawElement("backdrop", "noise-max-alpha").sizeOr(6.0f); + float scaledNoise = params.noiseOpacity * settings_.noiseOpacityMultiplier; + uint8_t alpha = static_cast(std::min(255.0f, maxAlpha * scaledNoise * 50.0f)); + float tilePx = static_cast(noiseTextureSize_); + float uvScale = 1.0f / tilePx; + ImVec2 uv0(pMin.x * uvScale, pMin.y * uvScale); + ImVec2 uv1(pMax.x * uvScale, pMax.y * uvScale); + + drawList->AddImageRounded( + noiseTex, + pMin, pMax, + uv0, uv1, + IM_COL32(255, 255, 255, alpha), + rounding + ); + } +} + +// ============================================================================ +// Global Instance +// ============================================================================ + +AcrylicMaterial& getAcrylicMaterial() +{ + static AcrylicMaterial instance; + return instance; +} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // !DRAGONX_HAS_GLAD + +// ============================================================================ +// DX11 Implementation (Windows) +// ============================================================================ + +#ifdef DRAGONX_USE_DX11 + +#include +#include +#include +#include +#include +#include +#include + +// Get D3D11 device from ImGui backend (same pattern as texture_loader.cpp) +static ID3D11Device* GetImGuiD3D11Device() +{ + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return nullptr; + return *reinterpret_cast(io.BackendRendererUserData); +} + +static ID3D11DeviceContext* GetImGuiD3D11DeviceContext() +{ + ID3D11Device* dev = GetImGuiD3D11Device(); + if (!dev) return nullptr; + ID3D11DeviceContext* ctx = nullptr; + dev->GetImmediateContext(&ctx); + // GetImmediateContext adds a ref, release the extra ref. + if (ctx) ctx->Release(); + return ctx; +} + +namespace dragonx { +namespace ui { +namespace effects { + +// ---- HLSL shader source (compiled at runtime via D3DCompile) ---- + +static const char* DX_BLUR_VS = R"hlsl( +struct VS_IN { float2 pos : POSITION; float2 uv : TEXCOORD0; }; +struct VS_OUT { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; }; +VS_OUT main(VS_IN i) { + VS_OUT o; + o.pos = float4(i.pos, 0.0, 1.0); + o.uv = i.uv; + return o; +} +)hlsl"; + +static const char* DX_BLUR_PS = R"hlsl( +cbuffer BlurCB : register(b0) { + float2 direction; + float2 resolution; + float radius; // Gaussian sigma in texels + float3 _pad; +}; +Texture2D tex : register(t0); +SamplerState smp : register(s0); + +// Screen-space hash for dithering (returns 0..1) +float hash12(float2 p) { + float3 p3 = frac(float3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return frac((p3.x + p3.y) * p3.z); +} + +float4 main(float4 svpos : SV_POSITION, float2 uv : TEXCOORD0) : SV_TARGET { + float2 texelSize = 1.0 / resolution; + float2 step = direction * texelSize; + + // Dynamic Gaussian kernel: radius = sigma, extend to ~2.5 sigma + float sigma = max(radius, 0.5); + int iRadius = clamp(int(sigma * 2.5 + 0.5), 1, 40); + float inv2sigma2 = 1.0 / (2.0 * sigma * sigma); + + float3 sum = float3(0, 0, 0); + float wSum = 0; + + [loop] for (int i = -iRadius; i <= iRadius; i++) { + float w = exp(-float(i * i) * inv2sigma2); + sum += tex.Sample(smp, uv + step * float(i)).rgb * w; + wSum += w; + } + + float3 color = sum / wSum; + + // Triangular-PDF dithering to break up 8-bit quantization banding. + // Two uniform hashes combined give a triangular distribution (-1..+1). + float d = hash12(svpos.xy) + hash12(svpos.xy + 71.37) - 1.0; + color += d / 255.0; + + return float4(color, 1.0); +} +)hlsl"; + +// ---- Constant buffer layout (must be 16-byte aligned) ---- +struct BlurCB { + float dirX, dirY; + float resX, resY; + float radius; + float _pad[3]; +}; + +// ---------------------------------------------------------------- +// Helper: create a 2-D render-target + SRV pair +// ---------------------------------------------------------------- +void AcrylicMaterial::dx_createRenderTarget( + ID3D11Texture2D*& tex, + ID3D11ShaderResourceView*& srv, + ID3D11RenderTargetView*& rtv, + int w, int h, + DXGI_FORMAT format) +{ + D3D11_TEXTURE2D_DESC td = {}; + td.Width = w; + td.Height = h; + td.MipLevels = 1; + td.ArraySize = 1; + td.Format = format; + td.SampleDesc.Count = 1; + td.Usage = D3D11_USAGE_DEFAULT; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; + + HRESULT hr = dx_device_->CreateTexture2D(&td, nullptr, &tex); + if (FAILED(hr)) { DEBUG_LOGF("[Acrylic DX11] CreateTexture2D failed 0x%08lx\n", hr); return; } + + dx_device_->CreateShaderResourceView(tex, nullptr, &srv); + dx_device_->CreateRenderTargetView(tex, nullptr, &rtv); +} + +void AcrylicMaterial::dx_releaseRenderTarget( + ID3D11Texture2D*& tex, + ID3D11ShaderResourceView*& srv, + ID3D11RenderTargetView*& rtv) +{ + if (srv) { srv->Release(); srv = nullptr; } + if (rtv) { rtv->Release(); rtv = nullptr; } + if (tex) { tex->Release(); tex = nullptr; } +} + +// ---------------------------------------------------------------- +// Compile shaders, create pipeline objects +// ---------------------------------------------------------------- +bool AcrylicMaterial::dx_initPipeline() +{ + HRESULT hr; + + // ---- Compile vertex shader ---- + ID3DBlob* vsBlob = nullptr; + ID3DBlob* errBlob = nullptr; + hr = D3DCompile(DX_BLUR_VS, strlen(DX_BLUR_VS), "blur_vs", + nullptr, nullptr, "main", "vs_4_0", + D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, + &vsBlob, &errBlob); + if (FAILED(hr)) { + if (errBlob) { DEBUG_LOGF("[Acrylic DX11] VS compile: %s\n", (char*)errBlob->GetBufferPointer()); errBlob->Release(); } + return false; + } + hr = dx_device_->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &dx_blurVS_); + if (FAILED(hr)) { vsBlob->Release(); return false; } + + // ---- Input layout ---- + D3D11_INPUT_ELEMENT_DESC layout[] = { + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + hr = dx_device_->CreateInputLayout(layout, 2, vsBlob->GetBufferPointer(), + vsBlob->GetBufferSize(), &dx_inputLayout_); + vsBlob->Release(); + if (FAILED(hr)) return false; + + // ---- Compile pixel shader ---- + ID3DBlob* psBlob = nullptr; + hr = D3DCompile(DX_BLUR_PS, strlen(DX_BLUR_PS), "blur_ps", + nullptr, nullptr, "main", "ps_4_0", + D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, + &psBlob, &errBlob); + if (FAILED(hr)) { + if (errBlob) { DEBUG_LOGF("[Acrylic DX11] PS compile: %s\n", (char*)errBlob->GetBufferPointer()); errBlob->Release(); } + return false; + } + hr = dx_device_->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &dx_blurPS_); + psBlob->Release(); + if (FAILED(hr)) return false; + + // ---- Constant buffer ---- + D3D11_BUFFER_DESC cbd = {}; + cbd.ByteWidth = sizeof(BlurCB); + cbd.Usage = D3D11_USAGE_DYNAMIC; + cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + hr = dx_device_->CreateBuffer(&cbd, nullptr, &dx_blurCB_); + if (FAILED(hr)) return false; + + // ---- Fullscreen quad vertex buffer ---- + struct Vert { float x, y, u, v; }; + Vert verts[] = { + {-1, 1, 0, 0}, {-1,-1, 0, 1}, { 1,-1, 1, 1}, + {-1, 1, 0, 0}, { 1,-1, 1, 1}, { 1, 1, 1, 0}, + }; + D3D11_BUFFER_DESC vbd = {}; + vbd.ByteWidth = sizeof(verts); + vbd.Usage = D3D11_USAGE_IMMUTABLE; + vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; + D3D11_SUBRESOURCE_DATA vi = {}; + vi.pSysMem = verts; + hr = dx_device_->CreateBuffer(&vbd, &vi, &dx_vertexBuf_); + if (FAILED(hr)) return false; + + // ---- Linear clamp sampler ---- + D3D11_SAMPLER_DESC sd = {}; + sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + sd.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; + sd.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; + sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + hr = dx_device_->CreateSamplerState(&sd, &dx_sampler_); + if (FAILED(hr)) return false; + + // ---- Rasterizer state: scissor OFF, no culling, solid fill ---- + D3D11_RASTERIZER_DESC rd = {}; + rd.FillMode = D3D11_FILL_SOLID; + rd.CullMode = D3D11_CULL_NONE; + rd.ScissorEnable = FALSE; + rd.DepthClipEnable = TRUE; + hr = dx_device_->CreateRasterizerState(&rd, &dx_blurRS_); + if (FAILED(hr)) return false; + + // ---- Blend state: opaque overwrite (no alpha blending) ---- + D3D11_BLEND_DESC bd = {}; + bd.RenderTarget[0].BlendEnable = FALSE; + bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + hr = dx_device_->CreateBlendState(&bd, &dx_blurBS_); + if (FAILED(hr)) return false; + + // ---- Depth-stencil state: depth test OFF ---- + D3D11_DEPTH_STENCIL_DESC dsd = {}; + dsd.DepthEnable = FALSE; + dsd.StencilEnable = FALSE; + hr = dx_device_->CreateDepthStencilState(&dsd, &dx_blurDSS_); + if (FAILED(hr)) return false; + + DEBUG_LOGF("[Acrylic DX11] Pipeline created successfully\n"); + return true; +} + +void AcrylicMaterial::dx_releasePipeline() +{ + if (dx_blurVS_) { dx_blurVS_->Release(); dx_blurVS_ = nullptr; } + if (dx_blurPS_) { dx_blurPS_->Release(); dx_blurPS_ = nullptr; } + if (dx_inputLayout_) { dx_inputLayout_->Release(); dx_inputLayout_ = nullptr; } + if (dx_blurCB_) { dx_blurCB_->Release(); dx_blurCB_ = nullptr; } + if (dx_vertexBuf_) { dx_vertexBuf_->Release(); dx_vertexBuf_ = nullptr; } + if (dx_sampler_) { dx_sampler_->Release(); dx_sampler_ = nullptr; } + if (dx_blurRS_) { dx_blurRS_->Release(); dx_blurRS_ = nullptr; } + if (dx_blurBS_) { dx_blurBS_->Release(); dx_blurBS_ = nullptr; } + if (dx_blurDSS_) { dx_blurDSS_->Release(); dx_blurDSS_ = nullptr; } + dx_releaseRenderTarget(dx_captureTex_, dx_captureSRV_, dx_captureRTV_); + for (int i = 0; i < 2; ++i) + dx_releaseRenderTarget(dx_blurTex_[i], dx_blurSRV_[i], dx_blurRTV_[i]); + if (dx_noiseSRV_) { dx_noiseSRV_->Release(); dx_noiseSRV_ = nullptr; } + if (dx_noiseTex_) { dx_noiseTex_->Release(); dx_noiseTex_ = nullptr; } +} + +// ============================================================================ +// AcrylicMaterial — DX11 implementations of the public API +// ============================================================================ + +AcrylicMaterial::AcrylicMaterial() = default; + +AcrylicMaterial::~AcrylicMaterial() +{ + shutdown(); +} + +bool AcrylicMaterial::init() +{ + if (initialized_) return true; + + dx_device_ = GetImGuiD3D11Device(); + dx_context_ = GetImGuiD3D11DeviceContext(); + if (!dx_device_ || !dx_context_) { + DEBUG_LOGF("[Acrylic DX11] No D3D11 device available\n"); + return false; + } + + if (!dx_initPipeline()) { + DEBUG_LOGF("[Acrylic DX11] Pipeline init failed\n"); + dx_releasePipeline(); + return false; + } + + // Generate noise texture (CPU-side, then upload) + // Pure white noise — no coherent patterns, perfectly seamless tiling + { + const int SZ = noiseTextureSize_; + std::vector data(SZ * SZ * 4); + uint32_t seed = 12345; + auto rng = [&]() -> float { + seed ^= seed << 13; seed ^= seed >> 17; seed ^= seed << 5; + return float(seed) / float(0xFFFFFFFF); + }; + for (int y = 0; y < SZ; ++y) + for (int x = 0; x < SZ; ++x) { + float v = 0.5f + (rng() - 0.5f) * 0.5f; + v = std::max(0.f, std::min(1.f, v)); + uint8_t g = uint8_t(v * 255.f); + int i = (y * SZ + x) * 4; + data[i] = g; data[i+1] = g; data[i+2] = g; data[i+3] = 255; + } + + D3D11_TEXTURE2D_DESC td = {}; + td.Width = SZ; td.Height = SZ; + td.MipLevels = 1; td.ArraySize = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc.Count = 1; + td.Usage = D3D11_USAGE_DEFAULT; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + D3D11_SUBRESOURCE_DATA init = {}; + init.pSysMem = data.data(); + init.SysMemPitch = SZ * 4; + dx_device_->CreateTexture2D(&td, &init, &dx_noiseTex_); + if (dx_noiseTex_) + dx_device_->CreateShaderResourceView(dx_noiseTex_, nullptr, &dx_noiseSRV_); + } + + // Detect capabilities (simplified for DX11 — always capable) + refreshCapabilities(); + currentFallback_ = detectFallback(); + + initialized_ = true; + DEBUG_LOGF("[Acrylic DX11] Initialized (fallback=%d)\n", (int)currentFallback_); + return true; +} + +void AcrylicMaterial::shutdown() +{ + if (!initialized_) return; + dx_releasePipeline(); + dx_device_ = nullptr; + dx_context_ = nullptr; + initialized_ = false; + viewportWidth_ = viewportHeight_ = 0; + DEBUG_LOGF("[Acrylic DX11] Shutdown\n"); +} + +void AcrylicMaterial::resize(int width, int height) +{ + if (width == viewportWidth_ && height == viewportHeight_) return; + viewportWidth_ = width; + viewportHeight_ = height; + blurCacheValid_ = false; + + if (settings_.quality == AcrylicQuality::Off) return; + + // (Re)create capture buffer at full resolution — must be B8G8R8A8 to match swap chain for CopyResource + dx_releaseRenderTarget(dx_captureTex_, dx_captureSRV_, dx_captureRTV_); + dx_createRenderTarget(dx_captureTex_, dx_captureSRV_, dx_captureRTV_, width, height, + DXGI_FORMAT_B8G8R8A8_UNORM); + + // Blur buffers — size depends on quality + int bw = width, bh = height; + switch (settings_.quality) { + case AcrylicQuality::Low: bw /= 4; bh /= 4; break; + case AcrylicQuality::Medium: bw /= 2; bh /= 2; break; + default: break; + } + bw = std::max(64, bw); + bh = std::max(64, bh); + + for (int i = 0; i < 2; ++i) + dx_releaseRenderTarget(dx_blurTex_[i], dx_blurSRV_[i], dx_blurRTV_[i]); + // Use R16G16B16A16_FLOAT for blur intermediates to avoid banding from precision loss + for (int i = 0; i < 2; ++i) + dx_createRenderTarget(dx_blurTex_[i], dx_blurSRV_[i], dx_blurRTV_[i], bw, bh, + DXGI_FORMAT_R16G16B16A16_FLOAT); + + dx_blurWidth_ = bw; + dx_blurHeight_ = bh; + dx_blurCurrent_ = 0; + dirtyFrames_ = 2; + DEBUG_LOGF("[Acrylic DX11] Resized %dx%d (blur %dx%d)\n", width, height, bw, bh); +} + +void AcrylicMaterial::captureBackground() +{ + // Unused on DX11 — capture is done via captureBackgroundDirect() +} + +void AcrylicMaterial::captureBackgroundDirect() +{ + if (!initialized_ || shouldSkipEffect()) return; + if (viewportWidth_ <= 0 || viewportHeight_ <= 0) return; + if (dirtyFrames_ <= 0) return; + --dirtyFrames_; + + if (!dx_captureTex_ || !dx_context_) return; + + // Get the current render target (swap-chain back buffer) and + // copy it into our capture texture. + ID3D11RenderTargetView* curRTV = nullptr; + dx_context_->OMGetRenderTargets(1, &curRTV, nullptr); + if (!curRTV) return; + + ID3D11Resource* bbRes = nullptr; + curRTV->GetResource(&bbRes); + curRTV->Release(); + if (!bbRes) return; + + dx_context_->CopyResource(dx_captureTex_, bbRes); + bbRes->Release(); + + static bool s_traced = false; + if (!s_traced) { s_traced = true; DEBUG_LOGF("[Acrylic DX11] captureBackgroundDirect OK %dx%d\n", viewportWidth_, viewportHeight_); } + + hasValidCapture_ = true; + blurCacheValid_ = false; +} + +void AcrylicMaterial::applyBlur(float radius) +{ + if (!dx_blurSRV_[0] || !dx_blurPS_ || !dx_context_) return; + + float scaledRadius = radius * settings_.blurRadiusMultiplier; + if (blurCacheValid_ && std::abs(scaledRadius - lastBlurRadius_) < 0.1f) return; + + int passes = 1; + float effectiveRadius = scaledRadius; + switch (settings_.quality) { + case AcrylicQuality::Low: passes = 1; effectiveRadius *= 0.5f; break; + case AcrylicQuality::Medium: passes = 2; break; + case AcrylicQuality::High: passes = 3; break; + default: return; + } + + // ---- Save D3D11 state that ImGui might need later ---- + ID3D11RenderTargetView* savedRTV = nullptr; + ID3D11DepthStencilView* savedDSV = nullptr; + ID3D11RasterizerState* savedRS = nullptr; + ID3D11BlendState* savedBS = nullptr; + FLOAT savedBlendFactor[4] = {}; + UINT savedSampleMask = 0; + ID3D11DepthStencilState* savedDSS = nullptr; + UINT savedStencilRef = 0; + D3D11_VIEWPORT savedVP = {}; + UINT numVP = 1; + dx_context_->OMGetRenderTargets(1, &savedRTV, &savedDSV); + dx_context_->RSGetState(&savedRS); + dx_context_->OMGetBlendState(&savedBS, savedBlendFactor, &savedSampleMask); + dx_context_->OMGetDepthStencilState(&savedDSS, &savedStencilRef); + dx_context_->RSGetViewports(&numVP, &savedVP); + + // ---- Setup blur pipeline ---- + dx_context_->IASetInputLayout(dx_inputLayout_); + dx_context_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + UINT stride = 16, offset = 0; + dx_context_->IASetVertexBuffers(0, 1, &dx_vertexBuf_, &stride, &offset); + dx_context_->VSSetShader(dx_blurVS_, nullptr, 0); + dx_context_->PSSetShader(dx_blurPS_, nullptr, 0); + dx_context_->PSSetSamplers(0, 1, &dx_sampler_); + dx_context_->PSSetConstantBuffers(0, 1, &dx_blurCB_); + + // Set clean rasterizer/blend/depth states for blur passes. + // ImGui leaves ScissorEnable=TRUE with a small scissor rect which + // would clip our fullscreen quads; alpha-blending would blend with + // stale buffer contents instead of overwriting. + dx_context_->RSSetState(dx_blurRS_); + dx_context_->OMSetBlendState(dx_blurBS_, nullptr, 0xFFFFFFFF); + dx_context_->OMSetDepthStencilState(dx_blurDSS_, 0); + + // Viewport for blur buffers + D3D11_VIEWPORT vp = {}; + vp.Width = (float)dx_blurWidth_; + vp.Height = (float)dx_blurHeight_; + vp.MaxDepth = 1.0f; + dx_context_->RSSetViewports(1, &vp); + + // First pass: downsample capture → blurBuf[0] using a pass-through + // (horizontal blur with radius → serves as downscale + first H-pass) + dx_blurCurrent_ = 0; + + // Initial downscale: capture → blur[0] (horizontal pass) + // Use blur-buffer resolution for step size so the blur kernel covers the + // same fraction of the image as subsequent passes. The linear sampler + // handles the implicit downscale from capture resolution. Using the + // capture resolution here would make each step only 1 capture texel, + // producing a horizontal blur ~Nx weaker than the vertical passes at + // blur resolution (N = downscale factor). + { + // Unbind blur[0] as input if it's bound + ID3D11ShaderResourceView* nullSRV = nullptr; + dx_context_->PSSetShaderResources(0, 1, &nullSRV); + + dx_context_->OMSetRenderTargets(1, &dx_blurRTV_[0], nullptr); + dx_context_->PSSetShaderResources(0, 1, &dx_captureSRV_); + + D3D11_MAPPED_SUBRESOURCE mapped; + dx_context_->Map(dx_blurCB_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); + BlurCB* cb = (BlurCB*)mapped.pData; + cb->dirX = 1.f; cb->dirY = 0.f; + cb->resX = (float)dx_blurWidth_; cb->resY = (float)dx_blurHeight_; + cb->radius = effectiveRadius / passes; + dx_context_->Unmap(dx_blurCB_, 0); + + dx_context_->Draw(6, 0); + } + + // Remaining blur passes on the blur-sized buffers + for (int pass = 0; pass < passes; ++pass) { + float passRadius = effectiveRadius / passes; + + // Vertical pass: blur[0] → blur[1] + { + ID3D11ShaderResourceView* nullSRV = nullptr; + dx_context_->PSSetShaderResources(0, 1, &nullSRV); + + dx_context_->OMSetRenderTargets(1, &dx_blurRTV_[1], nullptr); + dx_context_->PSSetShaderResources(0, 1, &dx_blurSRV_[0]); + + D3D11_MAPPED_SUBRESOURCE mapped; + dx_context_->Map(dx_blurCB_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); + BlurCB* cb = (BlurCB*)mapped.pData; + cb->dirX = 0.f; cb->dirY = 1.f; + cb->resX = (float)dx_blurWidth_; cb->resY = (float)dx_blurHeight_; + cb->radius = passRadius; + dx_context_->Unmap(dx_blurCB_, 0); + + dx_context_->Draw(6, 0); + } + + // Horizontal pass (if not last in this pass): blur[1] → blur[0] + if (pass < passes - 1) { + ID3D11ShaderResourceView* nullSRV = nullptr; + dx_context_->PSSetShaderResources(0, 1, &nullSRV); + + dx_context_->OMSetRenderTargets(1, &dx_blurRTV_[0], nullptr); + dx_context_->PSSetShaderResources(0, 1, &dx_blurSRV_[1]); + + D3D11_MAPPED_SUBRESOURCE mapped; + dx_context_->Map(dx_blurCB_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); + BlurCB* cb = (BlurCB*)mapped.pData; + cb->dirX = 1.f; cb->dirY = 0.f; + cb->resX = (float)dx_blurWidth_; cb->resY = (float)dx_blurHeight_; + cb->radius = passRadius; + dx_context_->Unmap(dx_blurCB_, 0); + + dx_context_->Draw(6, 0); + } + } + + // The final result is in blur[1] (last pass was vertical blur[0]→blur[1]) + dx_blurCurrent_ = 1; + + // ---- Restore saved D3D11 state ---- + { + ID3D11ShaderResourceView* nullSRV = nullptr; + dx_context_->PSSetShaderResources(0, 1, &nullSRV); + } + dx_context_->OMSetRenderTargets(1, &savedRTV, savedDSV); + dx_context_->RSSetState(savedRS); + dx_context_->OMSetBlendState(savedBS, savedBlendFactor, savedSampleMask); + dx_context_->OMSetDepthStencilState(savedDSS, savedStencilRef); + dx_context_->RSSetViewports(1, &savedVP); + if (savedRTV) savedRTV->Release(); + if (savedDSV) savedDSV->Release(); + if (savedRS) savedRS->Release(); + if (savedBS) savedBS->Release(); + if (savedDSS) savedDSS->Release(); + + static bool s_traced = false; + if (!s_traced) { + s_traced = true; + DEBUG_LOGF("[Acrylic DX11] applyBlur: %d passes, radius=%.1f, blurSize=%dx%d\n", + passes, effectiveRadius, dx_blurWidth_, dx_blurHeight_); + } + + lastBlurRadius_ = scaledRadius; + blurCacheValid_ = true; +} + +ImTextureID AcrylicMaterial::getBlurredTexture() const +{ + return (ImTextureID)dx_blurSRV_[dx_blurCurrent_]; +} + +ImTextureID AcrylicMaterial::getNoiseTexture() const +{ + return (ImTextureID)dx_noiseSRV_; +} + +void AcrylicMaterial::refreshCapabilities() +{ + capabilities_.glVersion = "DX11"; + capabilities_.glRenderer = "Direct3D 11"; + capabilities_.hasFramebufferSupport = true; + capabilities_.hasShaderSupport = true; + capabilities_.hasTextureSupport = true; + capabilities_.maxTextureSize = 16384; + capabilities_.isLowEndGPU = false; + capabilities_.isOnBattery = false; + +#ifdef _WIN32 + // Check battery status (Windows) + SYSTEM_POWER_STATUS sps; + if (GetSystemPowerStatus(&sps)) { + capabilities_.isOnBattery = (sps.ACLineStatus == 0); + } +#endif + + DEBUG_LOGF("[Acrylic DX11] Capabilities: DX11 renderer\n"); +} + +AcrylicFallback AcrylicMaterial::detectFallback() const +{ + if (hasForcedFallback_) return forcedFallback_; + if (settings_.reducedTransparency) return AcrylicFallback::Solid; + if (settings_.quality == AcrylicQuality::Off) return AcrylicFallback::TintedOnly; + if (!settings_.enabled) return AcrylicFallback::TintedOnly; + if (settings_.disableOnBattery && capabilities_.isOnBattery) return AcrylicFallback::TintedOnly; + return AcrylicFallback::None; +} + +void AcrylicMaterial::setQuality(AcrylicQuality quality) +{ + if (settings_.quality != quality) { + settings_.quality = quality; + blurCacheValid_ = false; + int w = viewportWidth_, h = viewportHeight_; + viewportWidth_ = viewportHeight_ = 0; + resize(w, h); + } +} + +bool AcrylicMaterial::shouldSkipEffect() const +{ + return !settings_.enabled || + settings_.reducedTransparency || + settings_.quality == AcrylicQuality::Off; +} + +void AcrylicMaterial::drawRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding) +{ + if (!initialized_) return; + + currentFallback_ = detectFallback(); + + static bool s_traced = false; + if (!s_traced) { + s_traced = true; + DEBUG_LOGF("[Acrylic DX11] drawRect first call: fallback=%d enabled=%d quality=%d " + "hasCapture=%d blurValid=%d viewport=%dx%d\n", + (int)currentFallback_, (int)settings_.enabled, + (int)settings_.quality, (int)hasValidCapture_, + (int)blurCacheValid_, viewportWidth_, viewportHeight_); + } + + // Fallback solid fill for DX11 — scaled by UI opacity for card transparency + auto dx_scaledFallback = [&]() { + ImVec4 c = params.fallbackColor; + c.w *= settings_.uiOpacity; + return ImGui::ColorConvertFloat4ToU32(c); + }; + + if (!params.enabled) { + drawList->AddRectFilled(pMin, pMax, dx_scaledFallback(), rounding); + return; + } + + switch (currentFallback_) { + case AcrylicFallback::Solid: + drawList->AddRectFilled(pMin, pMax, dx_scaledFallback(), rounding); + return; + case AcrylicFallback::TintedOnly: + drawTintedRect(drawList, pMin, pMax, params, rounding); + return; + default: break; + } + + if (!hasValidCapture_) { + drawTintedRect(drawList, pMin, pMax, params, rounding); + return; + } + + // Run DX11 blur pipeline + applyBlur(params.blurRadius); + + // DX11 UV: top-left = (0,0), bottom-right = (1,1) — same as ImGui + // With multi-viewport, pMin/pMax are in OS screen space; subtract + // the main viewport position to get window-local coords for UVs. + ImGuiViewport* mainVp = ImGui::GetMainViewport(); + float localX0 = pMin.x - mainVp->Pos.x; + float localY0 = pMin.y - mainVp->Pos.y; + float localX1 = pMax.x - mainVp->Pos.x; + float localY1 = pMax.y - mainVp->Pos.y; + float u0 = localX0 / viewportWidth_; + float v0 = localY0 / viewportHeight_; + float u1 = localX1 / viewportWidth_; + float v1 = localY1 / viewportHeight_; + + ImTextureID blurTex = getBlurredTexture(); + + static bool s_blurTraced = false; + if (!s_blurTraced && blurTex) { + s_blurTraced = true; + DEBUG_LOGF("[Acrylic DX11] blur tex=%p UV: (%.3f,%.3f)-(%.3f,%.3f)\n", + (void*)blurTex, u0, v0, u1, v1); + } + + // Draw the blurred background. Glass opacity from fallbackColor + // alpha. Blur always renders at full strength; UI opacity is + // handled separately by card surface alpha. + uint8_t glassAlpha = (uint8_t)std::min(255.f, + std::max(0.f, params.fallbackColor.w * 255.f)); + + if (blurTex) { + drawList->AddImageRounded( + blurTex, pMin, pMax, + ImVec2(u0, v0), ImVec2(u1, v1), + IM_COL32(255, 255, 255, glassAlpha), + rounding); + } + + // Noise grain overlay — single draw call via pre-tiled texture + if (params.noiseOpacity > 0.0f && settings_.noiseOpacityMultiplier > 0.0f) { + float maxAlpha = schema::UI().drawElement("backdrop", "noise-max-alpha").sizeOr(6.0f); + float scaledNoise = params.noiseOpacity * settings_.noiseOpacityMultiplier; + uint8_t alpha = (uint8_t)std::min(255.f, maxAlpha * scaledNoise * 50.f); + ImU32 col = IM_COL32(255, 255, 255, alpha); + drawList->PushClipRect(pMin, pMax, true); + dragonx::util::DrawTiledNoiseRect(drawList, pMin, pMax, col); + drawList->PopClipRect(); + } +} + +void AcrylicMaterial::drawTintedRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding) +{ + ImU32 tintCol = ImGui::ColorConvertFloat4ToU32( + ImVec4(params.tintColor.x, params.tintColor.y, params.tintColor.z, + params.tintColor.w * params.tintOpacity * 0.9f)); + drawList->AddRectFilled(pMin, pMax, tintCol, rounding); + + // Noise grain overlay — single draw call via pre-tiled texture + if (params.noiseOpacity > 0.0f && settings_.noiseOpacityMultiplier > 0.0f) { + float maxAlpha = schema::UI().drawElement("backdrop", "noise-max-alpha").sizeOr(6.0f); + float scaledNoise = params.noiseOpacity * settings_.noiseOpacityMultiplier; + uint8_t alpha = (uint8_t)std::min(255.f, maxAlpha * scaledNoise * 50.f); + ImGuiViewport* vp = ImGui::GetMainViewport(); + int vpW = (int)vp->Size.x, vpH = (int)vp->Size.y; + int texW = 0, texH = 0; + ImTextureID noiseTex = dragonx::util::GetTiledNoiseTexture(vpW, vpH, &texW, &texH); + if (noiseTex && texW > 0 && texH > 0) { + float u0 = (pMin.x - vp->Pos.x) / (float)texW; + float v0 = (pMin.y - vp->Pos.y) / (float)texH; + float u1 = (pMax.x - vp->Pos.x) / (float)texW; + float v1 = (pMax.y - vp->Pos.y) / (float)texH; + drawList->AddImageRounded( + noiseTex, pMin, pMax, + ImVec2(u0, v0), ImVec2(u1, v1), + IM_COL32(255, 255, 255, alpha), + rounding); + } + } +} + +// ============================================================================ +// Preset Parameters (same values as GL build) +// ============================================================================ + +AcrylicParams AcrylicMaterial::getDarkPreset() +{ + AcrylicParams p; + p.tintColor = ImVec4(0.1f, 0.1f, 0.12f, 0.95f); + p.tintOpacity = 0.75f; p.luminosityOpacity = 0.6f; + p.blurRadius = 30.f; p.noiseOpacity = 0.02f; + p.fallbackColor = ImVec4(0.12f, 0.12f, 0.14f, 1.f); + return p; +} + +AcrylicParams AcrylicMaterial::getLightPreset() +{ + AcrylicParams p; + p.tintColor = ImVec4(0.95f, 0.95f, 0.97f, 0.95f); + p.tintOpacity = 0.80f; p.luminosityOpacity = 0.7f; + p.blurRadius = 25.f; p.noiseOpacity = 0.02f; + p.fallbackColor = ImVec4(0.96f, 0.96f, 0.98f, 1.f); + return p; +} + +AcrylicParams AcrylicMaterial::getDragonXPreset() +{ + AcrylicParams p; + p.tintColor = ImVec4(0.6f, 0.15f, 0.1f, 0.95f); + p.tintOpacity = 0.85f; p.luminosityOpacity = 0.3f; + p.blurRadius = 40.f; p.noiseOpacity = 0.025f; + p.fallbackColor = ImVec4(0.5f, 0.12f, 0.08f, 1.f); + return p; +} + +AcrylicParams AcrylicMaterial::getPopupPreset() +{ + AcrylicParams p; + p.tintColor = ImVec4(0.15f, 0.15f, 0.18f, 0.95f); + p.tintOpacity = 0.70f; p.luminosityOpacity = 0.5f; + p.blurRadius = 30.f; p.noiseOpacity = 0.02f; + p.fallbackColor = ImVec4(0.18f, 0.18f, 0.2f, 1.f); + return p; +} + +AcrylicParams AcrylicMaterial::getSidebarPreset() +{ + AcrylicParams p; + p.tintColor = ImVec4(0.08f, 0.08f, 0.1f, 0.95f); + p.tintOpacity = 0.80f; p.luminosityOpacity = 0.4f; + p.blurRadius = 35.f; p.noiseOpacity = 0.02f; + p.fallbackColor = ImVec4(0.1f, 0.1f, 0.12f, 1.f); + return p; +} + +AcrylicMaterial& getAcrylicMaterial() +{ + static AcrylicMaterial instance; + return instance; +} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // neither GLAD nor DX11 + +// ============================================================================ +// Stub Implementation (No graphics backend) +// ============================================================================ + +namespace dragonx { +namespace ui { +namespace effects { + +AcrylicMaterial::AcrylicMaterial() = default; +AcrylicMaterial::~AcrylicMaterial() = default; +bool AcrylicMaterial::init() { return false; } +void AcrylicMaterial::shutdown() {} +void AcrylicMaterial::resize(int, int) {} +void AcrylicMaterial::captureBackground() {} +void AcrylicMaterial::captureBackgroundDirect() {} +void AcrylicMaterial::applyBlur(float) {} +ImTextureID AcrylicMaterial::getBlurredTexture() const { return 0; } +ImTextureID AcrylicMaterial::getNoiseTexture() const { return 0; } +void AcrylicMaterial::refreshCapabilities() {} +AcrylicFallback AcrylicMaterial::detectFallback() const { return AcrylicFallback::Solid; } +void AcrylicMaterial::drawTintedRect(ImDrawList* dl, const ImVec2& a, const ImVec2& b, + const AcrylicParams& p, float r) { + dl->AddRectFilled(a, b, ImGui::ColorConvertFloat4ToU32(p.fallbackColor), r); +} +void AcrylicMaterial::drawRect(ImDrawList* dl, const ImVec2& a, const ImVec2& b, + const AcrylicParams& p, float r) { + dl->AddRectFilled(a, b, ImGui::ColorConvertFloat4ToU32(p.fallbackColor), r); +} +AcrylicParams AcrylicMaterial::getDarkPreset() { AcrylicParams p; p.enabled=false; return p; } +AcrylicParams AcrylicMaterial::getLightPreset() { AcrylicParams p; p.enabled=false; return p; } +AcrylicParams AcrylicMaterial::getDragonXPreset() { AcrylicParams p; p.enabled=false; return p; } +AcrylicParams AcrylicMaterial::getPopupPreset() { AcrylicParams p; p.enabled=false; return p; } +AcrylicParams AcrylicMaterial::getSidebarPreset() { AcrylicParams p; p.enabled=false; return p; } +AcrylicMaterial& getAcrylicMaterial() { static AcrylicMaterial i; return i; } + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_USE_DX11 + +#endif // DRAGONX_HAS_GLAD diff --git a/src/ui/effects/acrylic.h b/src/ui/effects/acrylic.h new file mode 100644 index 0000000..b966d15 --- /dev/null +++ b/src/ui/effects/acrylic.h @@ -0,0 +1,456 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "framebuffer.h" +#include "blur_shader.h" +#include "noise_texture.h" +#include "imgui.h" + +#include +#include + +#ifdef DRAGONX_USE_DX11 +#include +#endif + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief Acrylic material parameters + * + * These parameters control the appearance of the acrylic effect, + * matching Microsoft's Fluent Design system. + */ +struct AcrylicParams { + // Tint color (RGBA, pre-multiplied alpha) + ImVec4 tintColor = ImVec4(0.1f, 0.1f, 0.12f, 1.0f); + + // Tint opacity (0.0 = fully transparent, 1.0 = fully opaque) + float tintOpacity = 0.75f; + + // Luminosity opacity (controls saturation pass-through) + // Lower values = more desaturated/milky appearance + float luminosityOpacity = 0.5f; + + // Blur radius in pixels (typical: 20-60) + float blurRadius = 30.0f; + + // Noise texture opacity (typical: 0.02-0.04) + float noiseOpacity = 0.02f; + + // Fallback color when acrylic is disabled. + // The alpha channel also controls the glass opacity of the blurred + // background when acrylic IS active (lower alpha = more see-through). + ImVec4 fallbackColor = ImVec4(0.15f, 0.15f, 0.18f, 0.5f); + + // Whether acrylic is enabled (false = use fallback) + bool enabled = true; +}; + +/** + * @brief Acrylic quality levels + */ +enum class AcrylicQuality { + Off, // Solid fallback color only + Low, // Single blur pass, downsampled + Medium, // Two blur passes, slight downsample + High // Full quality blur +}; + +/** + * @brief Acrylic fallback modes for graceful degradation + */ +enum class AcrylicFallback { + None, // Full acrylic (blur + tint + noise) + TintedOnly, // No blur, just semi-transparent tint overlay + Solid // Opaque fallback color only +}; + +/** + * @brief Acrylic settings for accessibility and performance + */ +struct AcrylicSettings { + bool enabled = true; // Master toggle + bool reducedTransparency = false; // Accessibility: use solid colors + float uiOpacity = 1.0f; // Card/sidebar opacity multiplier (0.3–1.0) + AcrylicQuality quality = AcrylicQuality::Medium; // Medium default for balance of quality/performance + float blurRadiusMultiplier = 1.0f; // Scales all blur radii (0.5 - 2.0) + float noiseOpacityMultiplier = 1.0f; // Scales noise opacity (0.0 - 2.0) + + // Auto-disable conditions (checked each frame) + bool disableOnBattery = false; // Disable when on battery power + bool disableOnLowFPS = false; // Disable if FPS drops below threshold + float lowFPSThreshold = 30.0f; // FPS threshold for auto-disable +}; + +/** + * @brief System capabilities for acrylic effects + */ +struct AcrylicCapabilities { + bool hasFramebufferSupport = false; + bool hasShaderSupport = false; + bool hasTextureSupport = false; + int maxTextureSize = 0; + std::string glVersion; + std::string glRenderer; + bool isLowEndGPU = false; + bool isOnBattery = false; // Linux: check /sys/class/power_supply +}; + +/** + * @brief Main acrylic material rendering system + * + * Implements Microsoft Fluent Design's acrylic material effect: + * - Gaussian blur of background content + * - Tint color overlay + * - Luminosity blend for depth + * - Subtle noise texture for grain + */ +class AcrylicMaterial { +public: + AcrylicMaterial(); + ~AcrylicMaterial(); + + // Non-copyable + AcrylicMaterial(const AcrylicMaterial&) = delete; + AcrylicMaterial& operator=(const AcrylicMaterial&) = delete; + + /** + * @brief Initialize the acrylic system + * @return true if successful + */ + bool init(); + + /** + * @brief Release all resources + */ + void shutdown(); + + /** + * @brief Check if system is initialized + */ + bool isInitialized() const { return initialized_; } + + /** + * @brief Update internal buffers for new viewport size + * @param width Viewport width + * @param height Viewport height + */ + void resize(int width, int height); + + /** + * @brief Capture current screen content for blur source + * + * Call this BEFORE rendering any acrylic surfaces. + * Only recaptures when the background is marked dirty. + */ + void captureBackground(); + + /** + * @brief Capture background directly from the current framebuffer. + * + * Intended to be called from an ImGui draw callback inserted at + * the end of the BackgroundDrawList. At that point during + * RenderDrawData(), only the background (gradient / image / noise) + * has been rasterized — no UI elements are in the framebuffer yet. + * This gives a clean background capture for acrylic blur. + * + * Respects the dirtyFrames_ counter so the capture and blur + * are only recomputed when the background actually changes + * (resize, theme change, etc.). + */ + void captureBackgroundDirect(); + + /** + * @brief Returns true once a valid background capture has been made. + * + * drawRect() checks this and falls back to a tinted fill on the + * very first frame before the callback has fired. + */ + bool hasValidCapture() const { return hasValidCapture_; } + + /// Mark background as needing recapture (call on resize, theme change, etc.) + /// Uses a 2-frame counter so the capture re-runs after the new background + /// has actually been rendered (theme switch happens mid-frame, before the + /// BackgroundDrawList is rebuilt with new colors/images). + void markBackgroundDirty() { dirtyFrames_ = 2; } + + /** + * @brief Render an acrylic-filled rectangle + * + * @param drawList ImGui draw list to add commands to + * @param pMin Top-left corner in screen coordinates + * @param pMax Bottom-right corner in screen coordinates + * @param params Acrylic parameters + * @param rounding Corner rounding + */ + void drawRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding = 0.0f); + + /** + * @brief Get the blurred background texture for manual rendering + */ + ImTextureID getBlurredTexture() const; + + /** + * @brief Get the noise texture + */ + ImTextureID getNoiseTexture() const; + + // ======================================================================== + // Settings + // ======================================================================== + + /** + * @brief Set global acrylic quality + */ + void setQuality(AcrylicQuality quality); + AcrylicQuality getQuality() const { return settings_.quality; } + + /** + * @brief Enable/disable acrylic globally + */ + void setEnabled(bool enabled) { settings_.enabled = enabled; } + bool isEnabled() const { return settings_.enabled; } + + /** + * @brief Set blur radius multiplier (scales all blur radii) + * @param multiplier Value from 0.0 to 5.0 + */ + void setBlurMultiplier(float multiplier) { + float clamped = std::max(0.0f, std::min(5.0f, multiplier)); + settings_.blurRadiusMultiplier = clamped; + } + float getBlurMultiplier() const { return settings_.blurRadiusMultiplier; } + + /** + * @brief Set reduced transparency mode (accessibility) + */ + void setReducedTransparency(bool reduced) { settings_.reducedTransparency = reduced; } + bool getReducedTransparency() const { return settings_.reducedTransparency; } + + /** + * @brief Set UI opacity multiplier for cards/sidebar (0.3–1.0, 1=opaque) + */ + void setUIOpacity(float opacity) { + settings_.uiOpacity = std::max(0.3f, std::min(1.0f, opacity)); + } + float getUIOpacity() const { return settings_.uiOpacity; } + + /** + * @brief Set noise opacity multiplier (0.0 = no noise, 1.0 = default, 2.0 = double) + */ + void setNoiseOpacityMultiplier(float m) { + settings_.noiseOpacityMultiplier = std::max(0.0f, std::min(5.0f, m)); + } + float getNoiseOpacityMultiplier() const { return settings_.noiseOpacityMultiplier; } + + /** + * @brief Get full settings struct + */ + const AcrylicSettings& getSettings() const { return settings_; } + void setSettings(const AcrylicSettings& settings) { settings_ = settings; } + + // ======================================================================== + // Fallback System + // ======================================================================== + + /** + * @brief Detect system capabilities and determine fallback mode + * + * Checks OpenGL capabilities, GPU info, and user preferences to + * determine the appropriate rendering mode. + * + * @return The recommended fallback mode + */ + AcrylicFallback detectFallback() const; + + /** + * @brief Get current fallback mode (cached) + */ + AcrylicFallback getCurrentFallback() const { return currentFallback_; } + + /** + * @brief Force a specific fallback mode + */ + void setForcedFallback(AcrylicFallback fallback) { + forcedFallback_ = fallback; + hasForcedFallback_ = true; + } + + /** + * @brief Clear forced fallback and use auto-detection + */ + void clearForcedFallback() { hasForcedFallback_ = false; } + + /** + * @brief Get detected system capabilities + */ + const AcrylicCapabilities& getCapabilities() const { return capabilities_; } + + /** + * @brief Refresh capability detection (call after context changes) + */ + void refreshCapabilities(); + + // ======================================================================== + // Preset Parameters + // ======================================================================== + + /** + * @brief Get dark theme acrylic preset + */ + static AcrylicParams getDarkPreset(); + + /** + * @brief Get light theme acrylic preset + */ + static AcrylicParams getLightPreset(); + + /** + * @brief Get DragonX branded acrylic preset + */ + static AcrylicParams getDragonXPreset(); + + /** + * @brief Get popup/dialog acrylic preset + */ + static AcrylicParams getPopupPreset(); + + /** + * @brief Get sidebar acrylic preset + */ + static AcrylicParams getSidebarPreset(); + +private: + /** + * @brief Apply blur passes to captured content + */ + void applyBlur(float radius); + + /** + * @brief Composite final acrylic appearance + */ + void compositeAcrylic(const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params); + + /** + * @brief Check if effect should be skipped (settings/quality) + */ + bool shouldSkipEffect() const; + + /** + * @brief Draw tinted-only fallback (no blur) + */ + void drawTintedRect(ImDrawList* drawList, const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, float rounding); + + bool initialized_ = false; + AcrylicSettings settings_; // All settings in one struct + + // Fallback system + AcrylicCapabilities capabilities_; + AcrylicFallback currentFallback_ = AcrylicFallback::None; + AcrylicFallback forcedFallback_ = AcrylicFallback::None; + bool hasForcedFallback_ = false; + + // Screen dimensions + int viewportWidth_ = 0; + int viewportHeight_ = 0; + + // Noise texture config + int noiseTextureSize_ = 256; // Texture resolution (larger = less repetition) + + // Caching for performance + float lastBlurRadius_ = 0.0f; + bool blurCacheValid_ = false; + int dirtyFrames_ = 2; // >0 means recapture needed; counts down each frame + bool hasValidCapture_ = false; // true once a clean BG capture exists + + // Capture and blur framebuffers + Framebuffer captureBuffer_; + FramebufferPingPong blurBuffers_; + + // Shaders + BlurShader blurShader_; + + // Fullscreen quad for post-processing + FullscreenQuad quad_; + + // Noise texture + NoiseTexture noiseTexture_; + + // Composite shader (tint + noise overlay) + GLuint compositeShader_ = 0; + GLint uCompositeTintColor_ = -1; + GLint uCompositeTintOpacity_ = -1; + GLint uCompositeLuminosity_ = -1; + GLint uCompositeNoiseOpacity_ = -1; + GLint uCompositeBlurTex_ = -1; + GLint uCompositeNoiseTex_ = -1; + GLint uCompositeTexScale_ = -1; + +#ifdef DRAGONX_USE_DX11 + // ---- DX11 acrylic resources (used instead of GL objects above) ---- + ID3D11Device* dx_device_ = nullptr; + ID3D11DeviceContext* dx_context_ = nullptr; + + // Capture buffer (full viewport resolution) + ID3D11Texture2D* dx_captureTex_ = nullptr; + ID3D11ShaderResourceView* dx_captureSRV_ = nullptr; + ID3D11RenderTargetView* dx_captureRTV_ = nullptr; + + // Blur ping-pong buffers (possibly downscaled) + ID3D11Texture2D* dx_blurTex_[2] = {}; + ID3D11ShaderResourceView* dx_blurSRV_[2] = {}; + ID3D11RenderTargetView* dx_blurRTV_[2] = {}; + int dx_blurWidth_ = 0; + int dx_blurHeight_ = 0; + int dx_blurCurrent_ = 0; // which buffer is "source" + + // Shaders & pipeline objects + ID3D11VertexShader* dx_blurVS_ = nullptr; + ID3D11PixelShader* dx_blurPS_ = nullptr; + ID3D11InputLayout* dx_inputLayout_ = nullptr; + ID3D11Buffer* dx_blurCB_ = nullptr; + ID3D11Buffer* dx_vertexBuf_ = nullptr; + ID3D11SamplerState* dx_sampler_ = nullptr; + ID3D11RasterizerState* dx_blurRS_ = nullptr; + ID3D11BlendState* dx_blurBS_ = nullptr; + ID3D11DepthStencilState* dx_blurDSS_ = nullptr; + + // Noise texture (DX11) + ID3D11Texture2D* dx_noiseTex_ = nullptr; + ID3D11ShaderResourceView* dx_noiseSRV_ = nullptr; + + // Internal helpers + bool dx_initPipeline(); + void dx_releasePipeline(); + void dx_createRenderTarget(ID3D11Texture2D*& tex, + ID3D11ShaderResourceView*& srv, + ID3D11RenderTargetView*& rtv, + int w, int h, + DXGI_FORMAT format); + void dx_releaseRenderTarget(ID3D11Texture2D*& tex, + ID3D11ShaderResourceView*& srv, + ID3D11RenderTargetView*& rtv); +#endif // DRAGONX_USE_DX11 +}; + +// ============================================================================ +// Global Acrylic Instance +// ============================================================================ + +/** + * @brief Get the global acrylic material instance + */ +AcrylicMaterial& getAcrylicMaterial(); + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/blur_shader.cpp b/src/ui/effects/blur_shader.cpp new file mode 100644 index 0000000..43654cc --- /dev/null +++ b/src/ui/effects/blur_shader.cpp @@ -0,0 +1,282 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "blur_shader.h" + +#ifdef DRAGONX_HAS_GLAD +#include +#include +#include +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// BlurShader Implementation (GLEW Available) +// ============================================================================ + +BlurShader::BlurShader() = default; + +BlurShader::~BlurShader() +{ + destroy(); +} + +bool BlurShader::init() +{ + // Create shaders + vertexShader_ = glCreateShader(GL_VERTEX_SHADER); + fragmentShader_ = glCreateShader(GL_FRAGMENT_SHADER); + + if (!compileShader(vertexShader_, ShaderSource::BLUR_VERTEX)) { + DEBUG_LOGF("BlurShader: Failed to compile vertex shader\n"); + destroy(); + return false; + } + + if (!compileShader(fragmentShader_, ShaderSource::BLUR_FRAGMENT)) { + DEBUG_LOGF("BlurShader: Failed to compile fragment shader\n"); + destroy(); + return false; + } + + // Create program + program_ = glCreateProgram(); + glAttachShader(program_, vertexShader_); + glAttachShader(program_, fragmentShader_); + + if (!linkProgram()) { + DEBUG_LOGF("BlurShader: Failed to link program\n"); + destroy(); + return false; + } + + // Get uniform locations + uTexture_ = glGetUniformLocation(program_, "uTexture"); + uDirection_ = glGetUniformLocation(program_, "uDirection"); + uResolution_ = glGetUniformLocation(program_, "uResolution"); + uRadius_ = glGetUniformLocation(program_, "uRadius"); + + DEBUG_LOGF("BlurShader: Initialized successfully\n"); + DEBUG_LOGF(" Uniforms: uTexture=%d, uDirection=%d, uResolution=%d, uRadius=%d\n", + uTexture_, uDirection_, uResolution_, uRadius_); + + return true; +} + +void BlurShader::destroy() +{ + if (program_) { + glDeleteProgram(program_); + program_ = 0; + } + if (vertexShader_) { + glDeleteShader(vertexShader_); + vertexShader_ = 0; + } + if (fragmentShader_) { + glDeleteShader(fragmentShader_); + fragmentShader_ = 0; + } + + uTexture_ = -1; + uDirection_ = -1; + uResolution_ = -1; + uRadius_ = -1; +} + +bool BlurShader::compileShader(unsigned int shader, const char* source) +{ + glShaderSource(shader, 1, &source, nullptr); + glCompileShader(shader); + + GLint success; + glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + + if (!success) { + GLint logLength; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); + + std::vector log(logLength + 1); + glGetShaderInfoLog(shader, logLength, nullptr, log.data()); + + DEBUG_LOGF("Shader compile error:\n%s\n", log.data()); + return false; + } + + return true; +} + +bool BlurShader::linkProgram() +{ + glLinkProgram(program_); + + GLint success; + glGetProgramiv(program_, GL_LINK_STATUS, &success); + + if (!success) { + GLint logLength; + glGetProgramiv(program_, GL_INFO_LOG_LENGTH, &logLength); + + std::vector log(logLength + 1); + glGetProgramInfoLog(program_, logLength, nullptr, log.data()); + + DEBUG_LOGF("Program link error:\n%s\n", log.data()); + return false; + } + + return true; +} + +void BlurShader::bind() +{ + glUseProgram(program_); +} + +void BlurShader::unbind() +{ + glUseProgram(0); +} + +void BlurShader::setDirection(bool horizontal) +{ + if (uDirection_ >= 0) { + if (horizontal) { + glUniform2f(uDirection_, 1.0f, 0.0f); + } else { + glUniform2f(uDirection_, 0.0f, 1.0f); + } + } +} + +void BlurShader::setRadius(float radius) +{ + if (uRadius_ >= 0) { + glUniform1f(uRadius_, radius); + } +} + +void BlurShader::setResolution(int width, int height) +{ + if (uResolution_ >= 0) { + glUniform2f(uResolution_, static_cast(width), static_cast(height)); + } +} + +void BlurShader::setTexture(int unit) +{ + if (uTexture_ >= 0) { + glUniform1i(uTexture_, unit); + } +} + +// ============================================================================ +// FullscreenQuad Implementation +// ============================================================================ + +FullscreenQuad::FullscreenQuad() = default; + +FullscreenQuad::~FullscreenQuad() +{ + destroy(); +} + +bool FullscreenQuad::init() +{ + // Fullscreen quad vertices: position (x,y) and texcoord (u,v) + // NDC coordinates: -1 to 1 + static const float vertices[] = { + // Position // TexCoord + -1.0f, 1.0f, 0.0f, 1.0f, // Top-left + -1.0f, -1.0f, 0.0f, 0.0f, // Bottom-left + 1.0f, -1.0f, 1.0f, 0.0f, // Bottom-right + + -1.0f, 1.0f, 0.0f, 1.0f, // Top-left + 1.0f, -1.0f, 1.0f, 0.0f, // Bottom-right + 1.0f, 1.0f, 1.0f, 1.0f // Top-right + }; + + glGenVertexArrays(1, &vao_); + glGenBuffers(1, &vbo_); + + glBindVertexArray(vao_); + + glBindBuffer(GL_ARRAY_BUFFER, vbo_); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + // Position attribute (location = 0) + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); + glEnableVertexAttribArray(0); + + // TexCoord attribute (location = 1) + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); + glEnableVertexAttribArray(1); + + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + return vao_ != 0; +} + +void FullscreenQuad::destroy() +{ + if (vbo_) { + glDeleteBuffers(1, &vbo_); + vbo_ = 0; + } + if (vao_) { + glDeleteVertexArrays(1, &vao_); + vao_ = 0; + } +} + +void FullscreenQuad::draw() +{ + glBindVertexArray(vao_); + glDrawArrays(GL_TRIANGLES, 0, 6); + glBindVertexArray(0); +} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // !DRAGONX_HAS_GLAD + +// ============================================================================ +// Stub Implementation (No GLAD - Acrylic effects disabled) +// ============================================================================ + +namespace dragonx { +namespace ui { +namespace effects { + +BlurShader::BlurShader() = default; +BlurShader::~BlurShader() = default; + +bool BlurShader::init() { return false; } +void BlurShader::destroy() {} +bool BlurShader::compileShader(unsigned int, const char*) { return false; } +bool BlurShader::linkProgram() { return false; } +void BlurShader::bind() {} +void BlurShader::unbind() {} +void BlurShader::setDirection(bool) {} +void BlurShader::setRadius(float) {} +void BlurShader::setResolution(int, int) {} +void BlurShader::setTexture(int) {} + +FullscreenQuad::FullscreenQuad() = default; +FullscreenQuad::~FullscreenQuad() = default; + +bool FullscreenQuad::init() { return false; } +void FullscreenQuad::destroy() {} +void FullscreenQuad::draw() {} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_HAS_GLAD diff --git a/src/ui/effects/blur_shader.h b/src/ui/effects/blur_shader.h new file mode 100644 index 0000000..a11b7e0 --- /dev/null +++ b/src/ui/effects/blur_shader.h @@ -0,0 +1,211 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#ifndef GLAD_GL_H_ +typedef unsigned int GLuint; +typedef int GLint; +typedef unsigned int GLenum; +typedef int GLsizei; +#endif +#include + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief GLSL shader program for blur effects + * + * Implements a two-pass Gaussian blur using separable convolution. + * First pass blurs horizontally, second pass blurs vertically. + */ +class BlurShader { +public: + BlurShader(); + ~BlurShader(); + + // Non-copyable + BlurShader(const BlurShader&) = delete; + BlurShader& operator=(const BlurShader&) = delete; + + /** + * @brief Compile and link the blur shader program + * @return true if successful + */ + bool init(); + + /** + * @brief Release shader resources + */ + void destroy(); + + /** + * @brief Use this shader program + */ + void bind(); + + /** + * @brief Stop using this shader + */ + void unbind(); + + /** + * @brief Set the blur direction + * @param horizontal true for horizontal pass, false for vertical + */ + void setDirection(bool horizontal); + + /** + * @brief Set the blur radius/intensity + * @param radius Blur radius in pixels (typical: 1.0 - 10.0) + */ + void setRadius(float radius); + + /** + * @brief Set the texture resolution for proper texel calculation + * @param width Texture width + * @param height Texture height + */ + void setResolution(int width, int height); + + /** + * @brief Set the input texture unit + * @param unit Texture unit (0 = GL_TEXTURE0) + */ + void setTexture(int unit = 0); + + /** + * @brief Check if shader is valid + */ + bool isValid() const { return program_ != 0; } + + /** + * @brief Get the shader program ID + */ + GLuint getProgram() const { return program_; } + +private: + bool compileShader(GLuint shader, const char* source); + bool linkProgram(); + + GLuint program_ = 0; + GLuint vertexShader_ = 0; + GLuint fragmentShader_ = 0; + + // Uniform locations + GLint uTexture_ = -1; + GLint uDirection_ = -1; + GLint uResolution_ = -1; + GLint uRadius_ = -1; +}; + +/** + * @brief Manages the full-screen quad VAO for post-processing + */ +class FullscreenQuad { +public: + FullscreenQuad(); + ~FullscreenQuad(); + + /** + * @brief Initialize the quad VAO/VBO + */ + bool init(); + + /** + * @brief Release resources + */ + void destroy(); + + /** + * @brief Draw the fullscreen quad + */ + void draw(); + + bool isValid() const { return vao_ != 0; } + +private: + GLuint vao_ = 0; + GLuint vbo_ = 0; +}; + +// ============================================================================ +// Shader Source Code (embedded) +// ============================================================================ + +namespace ShaderSource { + +// Simple passthrough vertex shader for fullscreen quad +constexpr const char* BLUR_VERTEX = R"glsl( +#version 330 core + +layout (location = 0) in vec2 aPos; +layout (location = 1) in vec2 aTexCoord; + +out vec2 vTexCoord; + +void main() +{ + gl_Position = vec4(aPos, 0.0, 1.0); + vTexCoord = aTexCoord; +} +)glsl"; + +// Gaussian blur fragment shader (dynamic kernel, separable) +// Loop-based with 1-texel spacing + triangular dithering +constexpr const char* BLUR_FRAGMENT = R"glsl( +#version 330 core + +in vec2 vTexCoord; +out vec4 FragColor; + +uniform sampler2D uTexture; +uniform vec2 uDirection; // (1,0) for horizontal, (0,1) for vertical +uniform vec2 uResolution; // Texture dimensions +uniform float uRadius; // Gaussian sigma in texels + +// Screen-space hash for dithering (returns 0..1) +float hash12(vec2 p) { + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); +} + +void main() +{ + vec2 texelSize = 1.0 / uResolution; + vec2 step = uDirection * texelSize; + + // Dynamic Gaussian kernel: uRadius = sigma, extend to ~2.5 sigma + float sigma = max(uRadius, 0.5); + int iRadius = clamp(int(sigma * 2.5 + 0.5), 1, 40); + float inv2sigma2 = 1.0 / (2.0 * sigma * sigma); + + vec3 sum = vec3(0.0); + float wSum = 0.0; + + for (int i = -iRadius; i <= iRadius; i++) { + float w = exp(-float(i * i) * inv2sigma2); + sum += texture(uTexture, vTexCoord + step * float(i)).rgb * w; + wSum += w; + } + + vec3 color = sum / wSum; + + // Triangular-PDF dithering to break up 8-bit quantization banding. + // Two uniform hashes combined give a triangular distribution (-1..+1). + float d = hash12(gl_FragCoord.xy) + hash12(gl_FragCoord.xy + 71.37) - 1.0; + color += d / 255.0; + + FragColor = vec4(color, 1.0); +} +)glsl"; + +} // namespace ShaderSource + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/framebuffer.cpp b/src/ui/effects/framebuffer.cpp new file mode 100644 index 0000000..0a0a65c --- /dev/null +++ b/src/ui/effects/framebuffer.cpp @@ -0,0 +1,302 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "framebuffer.h" + +#ifdef DRAGONX_HAS_GLAD +#include +#include +#include "../../util/logger.h" + +// GL 3.0 constants — may be missing from some GLAD configurations +#ifndef GL_RGBA16F +#define GL_RGBA16F 0x881A +#endif +#ifndef GL_HALF_FLOAT +#define GL_HALF_FLOAT 0x140B +#endif + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// Framebuffer Implementation (GLEW Available) +// ============================================================================ + +Framebuffer::Framebuffer() = default; + +Framebuffer::~Framebuffer() +{ + destroy(); +} + +Framebuffer::Framebuffer(Framebuffer&& other) noexcept + : fbo_(other.fbo_) + , colorTexture_(other.colorTexture_) + , depthRbo_(other.depthRbo_) + , width_(other.width_) + , height_(other.height_) + , isComplete_(other.isComplete_) +{ + other.fbo_ = 0; + other.colorTexture_ = 0; + other.depthRbo_ = 0; + other.width_ = 0; + other.height_ = 0; + other.isComplete_ = false; +} + +Framebuffer& Framebuffer::operator=(Framebuffer&& other) noexcept +{ + if (this != &other) { + destroy(); + + fbo_ = other.fbo_; + colorTexture_ = other.colorTexture_; + depthRbo_ = other.depthRbo_; + width_ = other.width_; + height_ = other.height_; + isComplete_ = other.isComplete_; + + other.fbo_ = 0; + other.colorTexture_ = 0; + other.depthRbo_ = 0; + other.width_ = 0; + other.height_ = 0; + other.isComplete_ = false; + } + return *this; +} + +bool Framebuffer::init(int width, int height, bool useFloat16) +{ + if (width <= 0 || height <= 0) { + DEBUG_LOGF("Framebuffer::init - Invalid dimensions: %dx%d\n", width, height); + return false; + } + + // Clean up existing resources + cleanup(); + + width_ = width; + height_ = height; + useFloat16_ = useFloat16; + + // Generate framebuffer + glGenFramebuffers(1, &fbo_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + + // Create color texture — use RGBA16F for blur intermediates to avoid banding + glGenTextures(1, &colorTexture_); + glBindTexture(GL_TEXTURE_2D, colorTexture_); + if (useFloat16) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_HALF_FLOAT, nullptr); + } else { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + } + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + // Attach color texture to framebuffer + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture_, 0); + + // Create depth renderbuffer (optional, but good for completeness) + glGenRenderbuffers(1, &depthRbo_); + glBindRenderbuffer(GL_RENDERBUFFER, depthRbo_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthRbo_); + + // Check completeness + isComplete_ = checkComplete(); + + // Unbind + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindTexture(GL_TEXTURE_2D, 0); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + if (!isComplete_) { + DEBUG_LOGF("Framebuffer::init - Framebuffer is not complete!\n"); + cleanup(); + return false; + } + + return true; +} + +bool Framebuffer::resize(int width, int height) +{ + if (width == width_ && height == height_) { + return true; // No change needed + } + return init(width, height, useFloat16_); +} + +void Framebuffer::destroy() +{ + cleanup(); +} + +void Framebuffer::cleanup() +{ + if (colorTexture_) { + glDeleteTextures(1, &colorTexture_); + colorTexture_ = 0; + } + if (depthRbo_) { + glDeleteRenderbuffers(1, &depthRbo_); + depthRbo_ = 0; + } + if (fbo_) { + glDeleteFramebuffers(1, &fbo_); + fbo_ = 0; + } + width_ = 0; + height_ = 0; + isComplete_ = false; +} + +bool Framebuffer::checkComplete() +{ + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + const char* errorStr = "Unknown"; + switch (status) { + case GL_FRAMEBUFFER_UNDEFINED: errorStr = "UNDEFINED"; break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: errorStr = "INCOMPLETE_ATTACHMENT"; break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: errorStr = "INCOMPLETE_MISSING_ATTACHMENT"; break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: errorStr = "INCOMPLETE_DRAW_BUFFER"; break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: errorStr = "INCOMPLETE_READ_BUFFER"; break; + case GL_FRAMEBUFFER_UNSUPPORTED: errorStr = "UNSUPPORTED"; break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: errorStr = "INCOMPLETE_MULTISAMPLE"; break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: errorStr = "INCOMPLETE_LAYER_TARGETS"; break; + } + DEBUG_LOGF("Framebuffer error: %s (0x%X)\n", errorStr, status); + return false; + } + return true; +} + +void Framebuffer::bind() +{ + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + glViewport(0, 0, width_, height_); +} + +void Framebuffer::unbind() +{ + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +void Framebuffer::clear(float r, float g, float b, float a) +{ + glClearColor(r, g, b, a); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +void Framebuffer::blitFrom(GLuint srcFbo, int srcX, int srcY, int srcWidth, int srcHeight, + int dstX, int dstY) +{ + glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_); + + glBlitFramebuffer( + srcX, srcY, srcX + srcWidth, srcY + srcHeight, // Source rect + dstX, dstY, dstX + srcWidth, dstY + srcHeight, // Dest rect + GL_COLOR_BUFFER_BIT, + GL_LINEAR + ); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +void Framebuffer::captureScreen(int viewportWidth, int viewportHeight) +{ + // Blit from default framebuffer (0) to this framebuffer + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_); + + glBlitFramebuffer( + 0, 0, viewportWidth, viewportHeight, // Source (screen) + 0, 0, width_, height_, // Dest (this FBO) + GL_COLOR_BUFFER_BIT, + GL_LINEAR + ); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +// ============================================================================ +// FramebufferPingPong Implementation +// ============================================================================ + +bool FramebufferPingPong::init(int width, int height, bool useFloat16) +{ + if (!buffers_[0].init(width, height, useFloat16)) return false; + if (!buffers_[1].init(width, height, useFloat16)) return false; + currentSource_ = 0; + return true; +} + +bool FramebufferPingPong::resize(int width, int height) +{ + if (!buffers_[0].resize(width, height)) return false; + if (!buffers_[1].resize(width, height)) return false; + return true; +} + +void FramebufferPingPong::destroy() +{ + buffers_[0].destroy(); + buffers_[1].destroy(); + currentSource_ = 0; +} + +void FramebufferPingPong::swap() +{ + currentSource_ = 1 - currentSource_; +} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // !DRAGONX_HAS_GLAD + +// ============================================================================ +// Stub Implementation (No GLAD - Acrylic effects disabled) +// ============================================================================ + +namespace dragonx { +namespace ui { +namespace effects { + +Framebuffer::Framebuffer() = default; +Framebuffer::~Framebuffer() = default; +Framebuffer::Framebuffer(Framebuffer&&) noexcept = default; +Framebuffer& Framebuffer::operator=(Framebuffer&&) noexcept = default; + +bool Framebuffer::init(int, int, bool) { return false; } +bool Framebuffer::resize(int, int) { return false; } +void Framebuffer::destroy() {} +void Framebuffer::cleanup() {} +bool Framebuffer::checkComplete() { return false; } +void Framebuffer::bind() {} +void Framebuffer::unbind() {} +void Framebuffer::clear(float, float, float, float) {} +void Framebuffer::blitFrom(unsigned int, int, int, int, int, int, int) {} +void Framebuffer::captureScreen(int, int) {} + +bool FramebufferPingPong::init(int, int, bool) { return false; } +bool FramebufferPingPong::resize(int, int) { return false; } +void FramebufferPingPong::destroy() {} +void FramebufferPingPong::swap() {} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_HAS_GLAD diff --git a/src/ui/effects/framebuffer.h b/src/ui/effects/framebuffer.h new file mode 100644 index 0000000..3522064 --- /dev/null +++ b/src/ui/effects/framebuffer.h @@ -0,0 +1,193 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +// GL type definitions needed by class declarations. +// If GLAD was already included, these types are already defined. +#ifndef GLAD_GL_H_ +typedef unsigned int GLuint; +typedef int GLint; +typedef unsigned int GLenum; +typedef int GLsizei; +#endif +#include + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief OpenGL Framebuffer Object manager for off-screen rendering + * + * Used for capturing screen content to use as blur source for acrylic effects. + */ +class Framebuffer { +public: + Framebuffer(); + ~Framebuffer(); + + // Non-copyable + Framebuffer(const Framebuffer&) = delete; + Framebuffer& operator=(const Framebuffer&) = delete; + + // Move constructors + Framebuffer(Framebuffer&& other) noexcept; + Framebuffer& operator=(Framebuffer&& other) noexcept; + + /** + * @brief Initialize framebuffer with given dimensions + * @param width Width in pixels + * @param height Height in pixels + * @param useFloat16 Use RGBA16F format for higher precision (reduces banding) + * @return true if successful + */ + bool init(int width, int height, bool useFloat16 = false); + + /** + * @brief Resize framebuffer (recreates internal textures) + * @param width New width + * @param height New height + * @return true if successful + */ + bool resize(int width, int height); + + /** + * @brief Release all OpenGL resources + */ + void destroy(); + + /** + * @brief Bind this framebuffer for rendering + */ + void bind(); + + /** + * @brief Unbind (return to default framebuffer) + */ + void unbind(); + + /** + * @brief Clear the framebuffer + * @param r Red component (0-1) + * @param g Green component (0-1) + * @param b Blue component (0-1) + * @param a Alpha component (0-1) + */ + void clear(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f); + + /** + * @brief Get the color texture attached to this framebuffer + * @return OpenGL texture ID + */ + GLuint getColorTexture() const { return colorTexture_; } + + /** + * @brief Get the underlying framebuffer object ID + * @return OpenGL FBO ID + */ + GLuint getFbo() const { return fbo_; } + + /** + * @brief Get framebuffer dimensions + */ + int getWidth() const { return width_; } + int getHeight() const { return height_; } + + /** + * @brief Check if framebuffer is valid and complete + */ + bool isValid() const { return fbo_ != 0 && isComplete_; } + + /** + * @brief Copy a region from the current framebuffer to this one + * @param srcX Source X position + * @param srcY Source Y position + * @param srcWidth Source width + * @param srcHeight Source height + * @param dstX Destination X position + * @param dstY Destination Y position + */ + void blitFrom(GLuint srcFbo, int srcX, int srcY, int srcWidth, int srcHeight, + int dstX = 0, int dstY = 0); + + /** + * @brief Copy entire default framebuffer to this one + * @param viewportWidth Current viewport width + * @param viewportHeight Current viewport height + */ + void captureScreen(int viewportWidth, int viewportHeight); + +private: + void cleanup(); + bool checkComplete(); + + GLuint fbo_ = 0; + GLuint colorTexture_ = 0; + GLuint depthRbo_ = 0; // Renderbuffer for depth (optional) + + int width_ = 0; + int height_ = 0; + bool useFloat16_ = false; // RGBA16F for blur precision + bool isComplete_ = false; +}; + +/** + * @brief Manages multiple framebuffers for ping-pong blur operations + */ +class FramebufferPingPong { +public: + FramebufferPingPong() = default; + ~FramebufferPingPong() = default; + + /** + * @brief Initialize both framebuffers + */ + bool init(int width, int height, bool useFloat16 = false); + + /** + * @brief Resize both framebuffers + */ + bool resize(int width, int height); + + /** + * @brief Destroy both framebuffers + */ + void destroy(); + + /** + * @brief Swap which buffer is source/destination + */ + void swap(); + + /** + * @brief Get current source framebuffer + */ + Framebuffer& getSource() { return buffers_[currentSource_]; } + + /** + * @brief Get current destination framebuffer + */ + Framebuffer& getDest() { return buffers_[1 - currentSource_]; } + + /** + * @brief Get source texture for reading + */ + GLuint getSourceTexture() const { return buffers_[currentSource_].getColorTexture(); } + + /** + * @brief Get destination texture + */ + GLuint getDestTexture() const { return buffers_[1 - currentSource_].getColorTexture(); } + + bool isValid() const { return buffers_[0].isValid() && buffers_[1].isValid(); } + +private: + Framebuffer buffers_[2]; + int currentSource_ = 0; +}; + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/imgui_acrylic.cpp b/src/ui/effects/imgui_acrylic.cpp new file mode 100644 index 0000000..db64a90 --- /dev/null +++ b/src/ui/effects/imgui_acrylic.cpp @@ -0,0 +1,1178 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../../util/noise_texture.h" + +#ifdef DRAGONX_HAS_GLAD +#include +#endif + +#include +#include +#include "../../util/logger.h" + +// ============================================================================ +// Frosted scrim — shared between GLAD and non-GLAD builds. +// Drawn on the popup's draw list as the first command so it appears behind +// the popup content but over the rest of the UI. Replaces ImGui's default +// solid-colour ModalWindowDimBg with a translucent frosted overlay + noise. +// ============================================================================ +namespace dragonx { namespace ui { namespace effects { namespace ImGuiAcrylic { +static void DrawFrostedScrim(ImDrawList* dl) +{ + const auto& S = ui::schema::UI(); + auto sde = [&](const char* key, float fb) -> float { + float v = S.drawElement("components.modal-scrim", key).size; + return v >= 0.0f ? v : fb; + }; + + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImVec2 vpMin = vp->Pos; + ImVec2 vpMax(vp->Pos.x + vp->Size.x, vp->Pos.y + vp->Size.y); + + // Semi-transparent white fill (the "frost") + int fillAlpha = (int)sde("fill-alpha", 12.0f); + dl->AddRectFilled(vpMin, vpMax, IM_COL32(255, 255, 255, fillAlpha)); + + // Noise grain overlay — single draw call via pre-tiled texture + { + int noiseAlpha = (int)sde("noise-alpha", 14.0f); + ImU32 noiseTint = IM_COL32(255, 255, 255, noiseAlpha); + dragonx::util::DrawTiledNoiseRect(dl, vpMin, vpMax, noiseTint); + } +} +} } } } // namespace dragonx::ui::effects::ImGuiAcrylic + +// ============================================================================ +// Preset table — shared by all backends +// ============================================================================ +namespace dragonx { namespace ui { namespace effects { namespace ImGuiAcrylic { + +struct PresetDef { + const char* label; + AcrylicQuality quality; + float blur; +}; + +static const PresetDef kPresets[kPresetCount] = { + { "Off", AcrylicQuality::Off, 0.0f }, + { "Subtle", AcrylicQuality::Low, 0.6f }, + { "Light", AcrylicQuality::Medium, 1.0f }, + { "Standard", AcrylicQuality::Medium, 1.5f }, + { "Strong", AcrylicQuality::High, 2.5f }, + { "Frosted", AcrylicQuality::High, 4.0f }, +}; + +const char* GetPresetLabel(int preset) +{ + if (preset < 0 || preset >= kPresetCount) return "?"; + return kPresets[preset].label; +} + +AcrylicQuality PresetQuality(int preset) +{ + if (preset < 0 || preset >= kPresetCount) return AcrylicQuality::Medium; + return kPresets[preset].quality; +} + +float PresetBlur(int preset) +{ + if (preset < 0 || preset >= kPresetCount) return 1.0f; + return kPresets[preset].blur; +} + +// Find closest preset matching given quality + blur +int MatchPreset(AcrylicQuality q, float blur) +{ + // Exact match first + for (int i = 0; i < kPresetCount; ++i) { + if (kPresets[i].quality == q && + std::abs(kPresets[i].blur - blur) < 0.01f) + return i; + } + // Closest blur within same quality + int best = 3; // Standard fallback + float bestDist = 999.f; + for (int i = 0; i < kPresetCount; ++i) { + if (kPresets[i].quality == q) { + float d = std::abs(kPresets[i].blur - blur); + if (d < bestDist) { bestDist = d; best = i; } + } + } + return best; +} + +} } } } // namespace dragonx::ui::effects::ImGuiAcrylic + +#ifdef DRAGONX_HAS_GLAD + +namespace dragonx { +namespace ui { +namespace effects { + +namespace ImGuiAcrylic { + +// ============================================================================ +// Static State +// ============================================================================ + +static bool s_initialized = false; +static int s_viewportWidth = 0; +static int s_viewportHeight = 0; +static bool s_backgroundCaptured = false; + +// Track window state for acrylic rendering +struct AcrylicWindowState { + ImVec2 windowPos; + ImVec2 windowSize; + AcrylicParams params; + bool active; +}; + +static AcrylicWindowState s_currentWindow = {}; + +// ============================================================================ +// Initialization +// ============================================================================ + +bool Init() +{ + if (s_initialized) { + return true; + } + + AcrylicMaterial& acrylic = getAcrylicMaterial(); + if (!acrylic.init()) { + DEBUG_LOGF("ImGuiAcrylic: Failed to initialize acrylic material\n"); + return false; + } + + s_initialized = true; + DEBUG_LOGF("ImGuiAcrylic: Initialized successfully\n"); + return true; +} + +void Shutdown() +{ + if (!s_initialized) { + return; + } + + getAcrylicMaterial().shutdown(); + s_initialized = false; + DEBUG_LOGF("ImGuiAcrylic: Shut down\n"); +} + +bool IsAvailable() +{ + return s_initialized && getAcrylicMaterial().isInitialized(); +} + +// ============================================================================ +// Frame Operations +// ============================================================================ + +void BeginFrame(int width, int height) +{ + if (!s_initialized) { + return; + } + + // Update viewport dimensions if changed + if (width != s_viewportWidth || height != s_viewportHeight) { + s_viewportWidth = width; + s_viewportHeight = height; + getAcrylicMaterial().resize(width, height); + } + + // Capture the first few frames to ensure a clean initial blur, + // then stop. The background (gradient/image/noise) is static; + // re-capturing + re-blurring every frame causes a subtle flicker + // from GPU floating-point non-determinism in the blur shader. + // Resize / theme change already sets dirtyFrames_ via markBackgroundDirty(). + static int s_warmupFrames = 3; + if (s_warmupFrames > 0) { + getAcrylicMaterial().markBackgroundDirty(); + --s_warmupFrames; + } + + s_backgroundCaptured = false; +} + +void CaptureBackground() +{ + if (!s_initialized || s_backgroundCaptured) { + return; + } + + getAcrylicMaterial().captureBackground(); + s_backgroundCaptured = true; +} + +void InvalidateCapture() +{ + if (!s_initialized) return; + getAcrylicMaterial().markBackgroundDirty(); +} + +// Draw callback: captures framebuffer 0 (which at this point during +// RenderDrawData() contains only the rasterized BackgroundDrawList — +// no UI windows yet) into the acrylic capture buffer. +static void BackgroundCaptureCallback(const ImDrawList*, const ImDrawCmd*) +{ + if (!s_initialized) return; + getAcrylicMaterial().captureBackgroundDirect(); + s_backgroundCaptured = true; +} + +ImDrawCallback GetBackgroundCaptureCallback() +{ + return BackgroundCaptureCallback; +} + +// ============================================================================ +// Drawing Functions +// ============================================================================ + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, + float rounding) +{ + if (!drawList) { + return; + } + + // If acrylic not available or disabled, draw fallback + if (!IsAvailable() || !IsEnabled() || !params.enabled) { + drawList->AddRectFilled(pMin, pMax, + ImGui::ColorConvertFloat4ToU32(params.fallbackColor), rounding); + return; + } + + // Background capture is now handled by a draw callback inserted + // into the BackgroundDrawList (see GetBackgroundCaptureCallback()). + // On the very first frame the callback hasn't fired yet, so + // drawRect() will fall back to a tinted fill automatically. + + // Draw using acrylic material + getAcrylicMaterial().drawRect(drawList, pMin, pMax, params, rounding); +} + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + float rounding) +{ + DrawAcrylicRect(drawList, pMin, pMax, AcrylicMaterial::getDarkPreset(), rounding); +} + +// ============================================================================ +// Window Wrappers +// ============================================================================ + +bool BeginAcrylicWindow(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + // Store params for use in EndAcrylicWindow + s_currentWindow.params = params; + s_currentWindow.active = true; + + // Ensure dialog windows stay above background windows (MainContent, StatusBar, MenuBar) + if (!(flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) + ImGui::SetNextWindowFocus(); + + // Make window background transparent so acrylic shows through + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::Begin(name, p_open, flags); + + if (result) { + // Get window bounds for acrylic rendering + s_currentWindow.windowPos = ImGui::GetWindowPos(); + s_currentWindow.windowSize = ImGui::GetWindowSize(); + + // Draw acrylic background + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = s_currentWindow.windowPos; + ImVec2 pMax = ImVec2(pMin.x + s_currentWindow.windowSize.x, + pMin.y + s_currentWindow.windowSize.y); + + // Get window rounding from style + float rounding = ImGui::GetStyle().WindowRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } + + return result; +} + +void EndAcrylicWindow() +{ + ImGui::End(); + ImGui::PopStyleColor(); // WindowBg + s_currentWindow.active = false; +} + +// ============================================================================ +// Child Region Wrappers +// ============================================================================ + +bool BeginAcrylicChild(const char* str_id, + const ImVec2& size, + const AcrylicParams& params, + ImGuiChildFlags child_flags, + ImGuiWindowFlags window_flags) +{ + // Make child background transparent + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::BeginChild(str_id, size, child_flags, window_flags); + + if (result) { + // Get child bounds + ImVec2 childPos = ImGui::GetWindowPos(); + ImVec2 childSize = ImGui::GetWindowSize(); + + // Draw acrylic background + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = childPos; + ImVec2 pMax = ImVec2(pMin.x + childSize.x, pMin.y + childSize.y); + + float rounding = ImGui::GetStyle().ChildRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } + + return result; +} + +void EndAcrylicChild() +{ + ImGui::EndChild(); + ImGui::PopStyleColor(); // ChildBg +} + +// ============================================================================ +// Popup Wrappers +// ============================================================================ + +bool BeginAcrylicPopup(const char* str_id, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::BeginPopup(str_id, flags); + + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + + float rounding = ImGui::GetStyle().PopupRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); // Only pop if not opened + } + + return result; +} + +void EndAcrylicPopup() +{ + ImGui::EndPopup(); + ImGui::PopStyleColor(); // PopupBg +} + +bool BeginAcrylicPopupModal(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + // Suppress ImGui's built-in dark scrim — we draw our own frosted one + ImGui::PushStyleColor(ImGuiCol_ModalWindowDimBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::BeginPopupModal(name, p_open, flags); + ImGui::PopStyleColor(); // ModalWindowDimBg (only needed during Begin) + + if (result) { + // Draw frosted scrim behind the popup on its own draw list + ImDrawList* drawList = ImGui::GetWindowDrawList(); + DrawFrostedScrim(drawList); + + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + + float rounding = ImGui::GetStyle().PopupRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + + return result; +} + +// ============================================================================ +// Context Menu Helpers +// ============================================================================ + +bool BeginAcrylicContextItem(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::BeginPopupContextItem(str_id, popup_flags); + + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + + float rounding = ImGui::GetStyle().PopupRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + + return result; +} + +bool BeginAcrylicContextWindow(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::BeginPopupContextWindow(str_id, popup_flags); + + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + + float rounding = ImGui::GetStyle().PopupRounding; + + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + + return result; +} + +// ============================================================================ +// Sidebar Helper +// ============================================================================ + +void DrawSidebarBackground(float width, const AcrylicParams& params) +{ + ImGuiViewport* viewport = ImGui::GetMainViewport(); + + // Sidebar starts below menu bar + float menuBarHeight = ImGui::GetFrameHeight(); + + ImVec2 pMin = ImVec2(viewport->WorkPos.x, viewport->WorkPos.y + menuBarHeight); + ImVec2 pMax = ImVec2(pMin.x + width, viewport->WorkPos.y + viewport->WorkSize.y); + + // Draw to background draw list + ImDrawList* drawList = ImGui::GetBackgroundDrawList(); + + DrawAcrylicRect(drawList, pMin, pMax, params, 0.0f); +} + +// ============================================================================ +// Settings +// ============================================================================ + +void SetQuality(AcrylicQuality quality) +{ + if (s_initialized) { + getAcrylicMaterial().setQuality(quality); + } +} + +AcrylicQuality GetQuality() +{ + if (s_initialized) { + return getAcrylicMaterial().getQuality(); + } + return AcrylicQuality::Off; +} + +void SetEnabled(bool enabled) +{ + if (s_initialized) { + getAcrylicMaterial().setEnabled(enabled); + } +} + +bool IsEnabled() +{ + if (s_initialized) { + return getAcrylicMaterial().isEnabled(); + } + return false; +} + +void SetBlurMultiplier(float multiplier) +{ + if (s_initialized) { + getAcrylicMaterial().setBlurMultiplier(multiplier); + } +} + +float GetBlurMultiplier() +{ + if (s_initialized) { + return getAcrylicMaterial().getBlurMultiplier(); + } + return 1.0f; +} + +void SetReducedTransparency(bool reduced) +{ + if (s_initialized) { + getAcrylicMaterial().setReducedTransparency(reduced); + } +} + +bool GetReducedTransparency() +{ + if (s_initialized) { + return getAcrylicMaterial().getReducedTransparency(); + } + return false; +} + +void SetUIOpacity(float opacity) +{ + if (s_initialized) { + getAcrylicMaterial().setUIOpacity(opacity); + } +} + +float GetUIOpacity() +{ + if (s_initialized) { + return getAcrylicMaterial().getUIOpacity(); + } + return 1.0f; +} + +void SetNoiseOpacity(float multiplier) +{ + if (s_initialized) { + getAcrylicMaterial().setNoiseOpacityMultiplier(multiplier); + } +} + +float GetNoiseOpacity() +{ + if (s_initialized) { + return getAcrylicMaterial().getNoiseOpacityMultiplier(); + } + return 1.0f; +} + +const AcrylicSettings& GetSettings() +{ + return getAcrylicMaterial().getSettings(); +} + +void SetSettings(const AcrylicSettings& settings) +{ + if (s_initialized) { + getAcrylicMaterial().setSettings(settings); + } +} + +void SetPreset(int preset) +{ + if (preset < 0 || preset >= kPresetCount) preset = 3; + SetEnabled(preset != 0); + SetQuality(PresetQuality(preset)); + SetBlurMultiplier(PresetBlur(preset)); +} + +int GetPreset() +{ + return MatchPreset(GetQuality(), GetBlurMultiplier()); +} + +void ApplyBlurAmount(float blur) +{ + if (blur < 0.001f) { + SetEnabled(false); + SetQuality(AcrylicQuality::Off); + SetBlurMultiplier(0.0f); + } else { + SetEnabled(true); + SetQuality(AcrylicQuality::Low); + SetBlurMultiplier(blur); + } +} + +} // namespace ImGuiAcrylic + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_HAS_GLAD + +// ============================================================================ +// Stub Implementations (No GLAD) +// ============================================================================ + +#ifndef DRAGONX_HAS_GLAD + +#ifdef DRAGONX_USE_DX11 + +// ============================================================================ +// DX11 Implementation — mirrors the GLAD version above, delegating to +// AcrylicMaterial which now has a full DX11 backend. +// ============================================================================ + +namespace dragonx { +namespace ui { +namespace effects { + +namespace ImGuiAcrylic { + +static bool s_initialized = false; +static int s_viewportWidth = 0; +static int s_viewportHeight = 0; +static bool s_backgroundCaptured = false; + +struct AcrylicWindowState { + ImVec2 windowPos; + ImVec2 windowSize; + AcrylicParams params; + bool active; +}; +static AcrylicWindowState s_currentWindow = {}; + +bool Init() +{ + if (s_initialized) return true; + + AcrylicMaterial& acrylic = getAcrylicMaterial(); + if (!acrylic.init()) { + DEBUG_LOGF("ImGuiAcrylic DX11: Failed to initialize acrylic material\n"); + return false; + } + + s_initialized = true; + DEBUG_LOGF("ImGuiAcrylic DX11: Initialized successfully\n"); + return true; +} + +void Shutdown() +{ + if (!s_initialized) return; + getAcrylicMaterial().shutdown(); + s_initialized = false; +} + +bool IsAvailable() +{ + return s_initialized && getAcrylicMaterial().isInitialized(); +} + +void BeginFrame(int width, int height) +{ + if (!s_initialized) return; + + if (width != s_viewportWidth || height != s_viewportHeight) { + s_viewportWidth = width; + s_viewportHeight = height; + getAcrylicMaterial().resize(width, height); + } + + // Capture the first few frames to ensure a clean initial blur, + // then stop. Resize / theme change already sets dirtyFrames_ via markBackgroundDirty(). + static int s_warmupFrames = 3; + if (s_warmupFrames > 0) { + getAcrylicMaterial().markBackgroundDirty(); + --s_warmupFrames; + } + + s_backgroundCaptured = false; +} + +void CaptureBackground() +{ + if (!s_initialized || s_backgroundCaptured) return; + getAcrylicMaterial().captureBackground(); + s_backgroundCaptured = true; +} + +void InvalidateCapture() +{ + if (!s_initialized) return; + getAcrylicMaterial().markBackgroundDirty(); +} + +static void BackgroundCaptureCallback(const ImDrawList*, const ImDrawCmd*) +{ + if (!s_initialized) return; + getAcrylicMaterial().captureBackgroundDirect(); + s_backgroundCaptured = true; +} + +ImDrawCallback GetBackgroundCaptureCallback() +{ + return BackgroundCaptureCallback; +} + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, + float rounding) +{ + if (!drawList) return; + + if (!IsAvailable() || !IsEnabled() || !params.enabled) { + drawList->AddRectFilled(pMin, pMax, + ImGui::ColorConvertFloat4ToU32(params.fallbackColor), rounding); + return; + } + + getAcrylicMaterial().drawRect(drawList, pMin, pMax, params, rounding); +} + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + float rounding) +{ + DrawAcrylicRect(drawList, pMin, pMax, AcrylicMaterial::getDarkPreset(), rounding); +} + +bool BeginAcrylicWindow(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + s_currentWindow.params = params; + s_currentWindow.active = true; + + if (!(flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) + ImGui::SetNextWindowFocus(); + + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0)); + + bool result = ImGui::Begin(name, p_open, flags); + + if (result) { + s_currentWindow.windowPos = ImGui::GetWindowPos(); + s_currentWindow.windowSize = ImGui::GetWindowSize(); + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = s_currentWindow.windowPos; + ImVec2 pMax = ImVec2(pMin.x + s_currentWindow.windowSize.x, + pMin.y + s_currentWindow.windowSize.y); + + float rounding = ImGui::GetStyle().WindowRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } + + return result; +} + +void EndAcrylicWindow() +{ + ImGui::End(); + ImGui::PopStyleColor(); + s_currentWindow.active = false; +} + +bool BeginAcrylicChild(const char* str_id, + const ImVec2& size, + const AcrylicParams& params, + ImGuiChildFlags child_flags, + ImGuiWindowFlags window_flags) +{ + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginChild(str_id, size, child_flags, window_flags); + if (result) { + ImVec2 childPos = ImGui::GetWindowPos(); + ImVec2 childSize = ImGui::GetWindowSize(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = childPos; + ImVec2 pMax = ImVec2(pMin.x + childSize.x, pMin.y + childSize.y); + float rounding = ImGui::GetStyle().ChildRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } + return result; +} + +void EndAcrylicChild() +{ + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +bool BeginAcrylicPopup(const char* str_id, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginPopup(str_id, flags); + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + float rounding = ImGui::GetStyle().PopupRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + return result; +} + +void EndAcrylicPopup() +{ + ImGui::EndPopup(); + ImGui::PopStyleColor(); +} + +bool BeginAcrylicPopupModal(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_ModalWindowDimBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginPopupModal(name, p_open, flags); + ImGui::PopStyleColor(); // ModalWindowDimBg + + if (result) { + ImDrawList* drawList = ImGui::GetWindowDrawList(); + DrawFrostedScrim(drawList); + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + float rounding = ImGui::GetStyle().PopupRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + + return result; +} + +bool BeginAcrylicContextItem(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginPopupContextItem(str_id, popup_flags); + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + float rounding = ImGui::GetStyle().PopupRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + return result; +} + +bool BeginAcrylicContextWindow(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams& params) +{ + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginPopupContextWindow(str_id, popup_flags); + if (result) { + ImVec2 popupPos = ImGui::GetWindowPos(); + ImVec2 popupSize = ImGui::GetWindowSize(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImVec2 pMin = popupPos; + ImVec2 pMax = ImVec2(pMin.x + popupSize.x, pMin.y + popupSize.y); + float rounding = ImGui::GetStyle().PopupRounding; + DrawAcrylicRect(drawList, pMin, pMax, params, rounding); + } else { + ImGui::PopStyleColor(); + } + return result; +} + +void DrawSidebarBackground(float width, const AcrylicParams& params) +{ + ImGuiViewport* viewport = ImGui::GetMainViewport(); + float menuBarHeight = ImGui::GetFrameHeight(); + ImVec2 pMin = ImVec2(viewport->WorkPos.x, viewport->WorkPos.y + menuBarHeight); + ImVec2 pMax = ImVec2(pMin.x + width, viewport->WorkPos.y + viewport->WorkSize.y); + ImDrawList* drawList = ImGui::GetBackgroundDrawList(); + DrawAcrylicRect(drawList, pMin, pMax, params, 0.0f); +} + +void SetQuality(AcrylicQuality quality) +{ + if (s_initialized) getAcrylicMaterial().setQuality(quality); +} + +AcrylicQuality GetQuality() +{ + if (s_initialized) return getAcrylicMaterial().getQuality(); + return AcrylicQuality::Off; +} + +void SetEnabled(bool enabled) +{ + if (s_initialized) getAcrylicMaterial().setEnabled(enabled); +} + +bool IsEnabled() +{ + if (s_initialized) return getAcrylicMaterial().isEnabled(); + return false; +} + +void SetBlurMultiplier(float multiplier) +{ + if (s_initialized) getAcrylicMaterial().setBlurMultiplier(multiplier); +} + +float GetBlurMultiplier() +{ + if (s_initialized) return getAcrylicMaterial().getBlurMultiplier(); + return 1.0f; +} + +void SetReducedTransparency(bool reduced) +{ + if (s_initialized) getAcrylicMaterial().setReducedTransparency(reduced); +} + +bool GetReducedTransparency() +{ + if (s_initialized) return getAcrylicMaterial().getReducedTransparency(); + return false; +} + +void SetUIOpacity(float opacity) +{ + if (s_initialized) getAcrylicMaterial().setUIOpacity(opacity); +} + +float GetUIOpacity() +{ + if (s_initialized) return getAcrylicMaterial().getUIOpacity(); + return 1.0f; +} + +void SetNoiseOpacity(float multiplier) +{ + if (s_initialized) getAcrylicMaterial().setNoiseOpacityMultiplier(multiplier); +} + +float GetNoiseOpacity() +{ + if (s_initialized) return getAcrylicMaterial().getNoiseOpacityMultiplier(); + return 1.0f; +} + +const AcrylicSettings& GetSettings() +{ + return getAcrylicMaterial().getSettings(); +} + +void SetSettings(const AcrylicSettings& settings) +{ + if (s_initialized) getAcrylicMaterial().setSettings(settings); +} + +void SetPreset(int preset) +{ + if (preset < 0 || preset >= kPresetCount) preset = 3; + SetEnabled(preset != 0); + SetQuality(PresetQuality(preset)); + SetBlurMultiplier(PresetBlur(preset)); +} + +int GetPreset() +{ + return MatchPreset(GetQuality(), GetBlurMultiplier()); +} + +void ApplyBlurAmount(float blur) +{ + if (blur < 0.001f) { + SetEnabled(false); + SetQuality(AcrylicQuality::Off); + SetBlurMultiplier(0.0f); + } else { + SetEnabled(true); + SetQuality(AcrylicQuality::Low); + SetBlurMultiplier(blur); + } +} + +} // namespace ImGuiAcrylic + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // neither GLAD nor DX11 + +namespace dragonx { +namespace ui { +namespace effects { + +namespace ImGuiAcrylic { + +bool Init() { return false; } +void Shutdown() {} +bool IsAvailable() { return false; } + +void BeginFrame(int, int) {} +void CaptureBackground() {} +void InvalidateCapture() {} +ImDrawCallback GetBackgroundCaptureCallback() { return nullptr; } + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, + float rounding) +{ + if (drawList) { + drawList->AddRectFilled(pMin, pMax, + ImGui::ColorConvertFloat4ToU32(params.fallbackColor), rounding); + } +} + +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + float rounding) +{ + if (drawList) { + AcrylicParams params; + drawList->AddRectFilled(pMin, pMax, + ImGui::ColorConvertFloat4ToU32(params.fallbackColor), rounding); + } +} + +bool BeginAcrylicWindow(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams&) +{ + if (!(flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) + ImGui::SetNextWindowFocus(); + return ImGui::Begin(name, p_open, flags); +} + +void EndAcrylicWindow() +{ + ImGui::End(); +} + +bool BeginAcrylicChild(const char* str_id, + const ImVec2& size, + const AcrylicParams&, + ImGuiChildFlags child_flags, + ImGuiWindowFlags window_flags) +{ + return ImGui::BeginChild(str_id, size, child_flags, window_flags); +} + +void EndAcrylicChild() +{ + ImGui::EndChild(); +} + +bool BeginAcrylicPopup(const char* str_id, + ImGuiWindowFlags flags, + const AcrylicParams&) +{ + return ImGui::BeginPopup(str_id, flags); +} + +void EndAcrylicPopup() +{ + ImGui::EndPopup(); +} + +bool BeginAcrylicPopupModal(const char* name, bool* p_open, + ImGuiWindowFlags flags, + const AcrylicParams&) +{ + ImGui::PushStyleColor(ImGuiCol_ModalWindowDimBg, ImVec4(0, 0, 0, 0)); + bool result = ImGui::BeginPopupModal(name, p_open, flags); + ImGui::PopStyleColor(); + if (result) { + DrawFrostedScrim(ImGui::GetWindowDrawList()); + } + return result; +} + +bool BeginAcrylicContextItem(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams&) +{ + return ImGui::BeginPopupContextItem(str_id, popup_flags); +} + +bool BeginAcrylicContextWindow(const char* str_id, + ImGuiPopupFlags popup_flags, + const AcrylicParams&) +{ + return ImGui::BeginPopupContextWindow(str_id, popup_flags); +} + +void DrawSidebarBackground(float, const AcrylicParams&) {} + +void SetQuality(AcrylicQuality) {} +AcrylicQuality GetQuality() { return AcrylicQuality::Off; } +void SetEnabled(bool) {} +bool IsEnabled() { return false; } +void SetBlurMultiplier(float) {} +float GetBlurMultiplier() { return 1.0f; } +void SetReducedTransparency(bool) {} +bool GetReducedTransparency() { return false; } +void SetUIOpacity(float) {} +float GetUIOpacity() { return 1.0f; } +void SetNoiseOpacity(float) {} +float GetNoiseOpacity() { return 1.0f; } +static AcrylicSettings s_stubSettings; +const AcrylicSettings& GetSettings() { return s_stubSettings; } +void SetSettings(const AcrylicSettings&) {} +void SetPreset(int) {} +int GetPreset() { return 0; } +void ApplyBlurAmount(float) {} + +} // namespace ImGuiAcrylic + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_USE_DX11 + +#endif // !DRAGONX_HAS_GLAD diff --git a/src/ui/effects/imgui_acrylic.h b/src/ui/effects/imgui_acrylic.h new file mode 100644 index 0000000..551bc39 --- /dev/null +++ b/src/ui/effects/imgui_acrylic.h @@ -0,0 +1,381 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "acrylic.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief ImGui integration for acrylic effects + * + * Provides convenient wrappers around AcrylicMaterial for use with + * standard ImGui rendering patterns. + */ +namespace ImGuiAcrylic { + +// ============================================================================ +// Initialization +// ============================================================================ + +/** + * @brief Initialize the acrylic system + * + * Call once at application startup, after OpenGL context is created. + * @return true if successful + */ +bool Init(); + +/** + * @brief Shutdown the acrylic system + * + * Call at application shutdown before destroying OpenGL context. + */ +void Shutdown(); + +/** + * @brief Check if acrylic is available and initialized + */ +bool IsAvailable(); + +// ============================================================================ +// Frame Operations +// ============================================================================ + +/** + * @brief Begin a new frame for acrylic rendering + * + * Call this at the start of your render loop, before any ImGui rendering. + * This captures the current screen content for blur source. + * + * @param width Viewport width + * @param height Viewport height + */ +void BeginFrame(int width, int height); + +/** + * @brief End the acrylic frame + * + * Call this after all regular content is rendered but before acrylic overlays. + * Captures the current framebuffer content for blur. + */ +void CaptureBackground(); + +/** + * @brief Invalidate the acrylic capture so the next frame re-captures + * and re-blurs. Call after theme/skin changes that alter the + * background gradient, image, or colors. + */ +void InvalidateCapture(); + +/** + * @brief Get a draw callback for background capture. + * + * Insert this callback at the end of the BackgroundDrawList (after all + * background commands). During RenderDrawData() it fires right after + * the background is rasterized — before any UI windows — and blits + * the clean background into the acrylic capture buffer. + * + * Usage in main.cpp: + * @code + * bgDL->AddCallback(ImGuiAcrylic::GetBackgroundCaptureCallback(), nullptr); + * bgDL->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + * @endcode + */ +ImDrawCallback GetBackgroundCaptureCallback(); + +// ============================================================================ +// Drawing Functions +// ============================================================================ + +/** + * @brief Draw an acrylic-filled rectangle + * + * @param drawList ImGui draw list to add the rectangle to + * @param pMin Top-left corner (screen coordinates) + * @param pMax Bottom-right corner (screen coordinates) + * @param params Acrylic appearance parameters + * @param rounding Corner rounding radius + */ +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + const AcrylicParams& params, + float rounding = 0.0f); + +/** + * @brief Draw an acrylic-filled rectangle with default preset + */ +void DrawAcrylicRect(ImDrawList* drawList, + const ImVec2& pMin, const ImVec2& pMax, + float rounding = 0.0f); + +// ============================================================================ +// Window Wrappers +// ============================================================================ + +/** + * @brief Begin an acrylic-background window + * + * Works like ImGui::Begin but with acrylic background. + * Must be paired with EndAcrylicWindow(). + * + * @param name Window name/ID + * @param p_open Optional close button flag + * @param flags ImGui window flags + * @param params Acrylic appearance parameters + * @return true if window is visible + */ +bool BeginAcrylicWindow(const char* name, bool* p_open = nullptr, + ImGuiWindowFlags flags = 0, + const AcrylicParams& params = AcrylicMaterial::getPopupPreset()); + +/** + * @brief End an acrylic window + */ +void EndAcrylicWindow(); + +// ============================================================================ +// Child Region Wrappers +// ============================================================================ + +/** + * @brief Begin an acrylic child region + * + * Works like ImGui::BeginChild but with acrylic background. + * Must be paired with EndAcrylicChild(). + * + * @param str_id Child region ID + * @param size Child region size (0,0 = auto) + * @param params Acrylic appearance parameters + * @param child_flags ImGui child flags + * @param window_flags ImGui window flags for the child + * @return true if child is visible + */ +bool BeginAcrylicChild(const char* str_id, + const ImVec2& size = ImVec2(0, 0), + const AcrylicParams& params = AcrylicMaterial::getDarkPreset(), + ImGuiChildFlags child_flags = 0, + ImGuiWindowFlags window_flags = 0); + +/** + * @brief End an acrylic child region + */ +void EndAcrylicChild(); + +// ============================================================================ +// Popup Wrappers +// ============================================================================ + +/** + * @brief Begin an acrylic popup + * + * Works like ImGui::BeginPopup but with acrylic background. + * Must be paired with EndAcrylicPopup(). + * + * @param str_id Popup ID + * @param flags ImGui window flags + * @param params Acrylic appearance parameters + * @return true if popup is open + */ +bool BeginAcrylicPopup(const char* str_id, + ImGuiWindowFlags flags = 0, + const AcrylicParams& params = AcrylicMaterial::getPopupPreset()); + +/** + * @brief End an acrylic popup + */ +void EndAcrylicPopup(); + +/** + * @brief Begin an acrylic modal popup + * + * Works like ImGui::BeginPopupModal but with acrylic background. + * Must be paired with EndAcrylicPopup(). + */ +bool BeginAcrylicPopupModal(const char* name, bool* p_open = nullptr, + ImGuiWindowFlags flags = 0, + const AcrylicParams& params = AcrylicMaterial::getPopupPreset()); + +// ============================================================================ +// Context Menu Helpers +// ============================================================================ + +/** + * @brief Begin an acrylic context menu for the last item + * + * Works like ImGui::BeginPopupContextItem but with acrylic background. + * Must be paired with EndAcrylicPopup(). + * + * @param str_id Popup ID (nullptr to use last item ID) + * @param popup_flags ImGui popup flags + * @param params Acrylic appearance parameters + * @return true if context menu is open + */ +bool BeginAcrylicContextItem(const char* str_id = nullptr, + ImGuiPopupFlags popup_flags = 0, + const AcrylicParams& params = AcrylicMaterial::getPopupPreset()); + +/** + * @brief Begin an acrylic context menu for the current window + * + * Works like ImGui::BeginPopupContextWindow but with acrylic background. + * Must be paired with EndAcrylicPopup(). + */ +bool BeginAcrylicContextWindow(const char* str_id = nullptr, + ImGuiPopupFlags popup_flags = 0, + const AcrylicParams& params = AcrylicMaterial::getPopupPreset()); + +// ============================================================================ +// Sidebar Helper +// ============================================================================ + +/** + * @brief Draw an acrylic sidebar background + * + * Convenience function for drawing sidebar with DragonX branded acrylic. + * + * @param width Sidebar width + * @param params Optional custom parameters (default: sidebar preset) + */ +void DrawSidebarBackground(float width, + const AcrylicParams& params = AcrylicMaterial::getSidebarPreset()); + +// ============================================================================ +// Settings +// ============================================================================ + +/** + * @brief Set global acrylic quality + */ +void SetQuality(AcrylicQuality quality); + +/** + * @brief Get current quality setting + */ +AcrylicQuality GetQuality(); + +/** + * @brief Enable/disable acrylic globally + * + * When disabled, all acrylic functions fall back to solid colors. + */ +void SetEnabled(bool enabled); + +/** + * @brief Check if acrylic is enabled + */ +bool IsEnabled(); + +/** + * @brief Set blur radius multiplier (scales all blur radii) + * @param multiplier Value from 0.5 to 2.0 (1.0 = default) + */ +void SetBlurMultiplier(float multiplier); + +/** + * @brief Get current blur multiplier + */ +float GetBlurMultiplier(); + +/** + * @brief Set reduced transparency mode (accessibility) + * + * When enabled, uses solid fallback colors instead of blur effects. + */ +void SetReducedTransparency(bool reduced); + +/** + * @brief Check if reduced transparency mode is active + */ +bool GetReducedTransparency(); + +/** + * @brief Set UI opacity multiplier for cards/sidebar (0.3–1.0, 1=opaque) + */ +void SetUIOpacity(float opacity); + +/** + * @brief Get UI opacity multiplier + */ +float GetUIOpacity(); + +/** + * @brief Set noise opacity multiplier (0.0 = no noise, 1.0 = default, 2.0 = max) + */ +void SetNoiseOpacity(float multiplier); + +/** + * @brief Get noise opacity multiplier + */ +float GetNoiseOpacity(); + +/** + * @brief Get full acrylic settings + */ +const AcrylicSettings& GetSettings(); + +/** + * @brief Set full acrylic settings + */ +void SetSettings(const AcrylicSettings& settings); + +// ============================================================================ +// Presets — combined quality + blur amount +// ============================================================================ + +/// Number of built-in presets (Off … Frosted) +constexpr int kPresetCount = 6; + +/** + * @brief Apply a preset that sets both quality and blur multiplier. + * @param preset Index 0–5 (Off, Subtle, Light, Standard, Strong, Frosted) + */ +void SetPreset(int preset); + +/** + * @brief Derive the closest preset index from current quality + blur. + */ +int GetPreset(); + +/** + * @brief Human-readable label for a preset index. + */ +const char* GetPresetLabel(int preset); + +/** + * @brief Get the quality enum for a given preset index. + */ +AcrylicQuality PresetQuality(int preset); + +/** + * @brief Get the blur multiplier for a given preset index. + */ +float PresetBlur(int preset); + +/** + * @brief Find closest preset matching a quality + blur pair. + * Useful for migrating from legacy separate settings. + */ +int MatchPreset(AcrylicQuality quality, float blur); + +/** + * @brief Apply a continuous blur amount. + * + * Uses Low quality (like the old "Subtle" preset) at any non-zero blur + * level, giving fine-grained control without stepped presets. + * When blur is near zero the effect is disabled entirely. + * + * @param blur Blur multiplier (0.0 = off, up to 4.0 = maximum) + */ +void ApplyBlurAmount(float blur); + +} // namespace ImGuiAcrylic + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/low_spec.cpp b/src/ui/effects/low_spec.cpp new file mode 100644 index 0000000..4295e48 --- /dev/null +++ b/src/ui/effects/low_spec.cpp @@ -0,0 +1,24 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "low_spec.h" +#include + +namespace dragonx { +namespace ui { +namespace effects { + +static std::atomic s_low_spec{false}; + +bool isLowSpecMode() { + return s_low_spec.load(std::memory_order_relaxed); +} + +void setLowSpecMode(bool enabled) { + s_low_spec.store(enabled, std::memory_order_relaxed); +} + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/low_spec.h b/src/ui/effects/low_spec.h new file mode 100644 index 0000000..1c3fb1b --- /dev/null +++ b/src/ui/effects/low_spec.h @@ -0,0 +1,21 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +namespace ui { +namespace effects { + +/// Global low-spec mode query. When enabled, heavy visual effects are +/// skipped: glass panel noise tiling, elevation shadow layers, ripple +/// circle expansion, viewport noise overlay, scroll-edge fade shader, +/// and mining pulse animations. Individual effect toggles (acrylic, +/// theme effects, scanline) are overridden via the settings page. +bool isLowSpecMode(); +void setLowSpecMode(bool enabled); + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/noise_texture.cpp b/src/ui/effects/noise_texture.cpp new file mode 100644 index 0000000..a39c662 --- /dev/null +++ b/src/ui/effects/noise_texture.cpp @@ -0,0 +1,354 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "noise_texture.h" +#include "../../util/logger.h" + +#ifdef DRAGONX_HAS_GLAD +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// NoiseTexture Implementation (GLEW Available) +// ============================================================================ + +NoiseTexture::NoiseTexture() = default; + +NoiseTexture::~NoiseTexture() +{ + destroy(); +} + +float NoiseTexture::random(uint32_t& seed) +{ + // Xorshift32 PRNG + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + return static_cast(seed) / static_cast(0xFFFFFFFF); +} + +float NoiseTexture::noise2D(float x, float y, int wrap) +{ + // Simple value noise with smoothstep interpolation + int xi = static_cast(std::floor(x)) & (wrap - 1); + int yi = static_cast(std::floor(y)) & (wrap - 1); + + float xf = x - std::floor(x); + float yf = y - std::floor(y); + + // Smoothstep + float u = xf * xf * (3.0f - 2.0f * xf); + float v = yf * yf * (3.0f - 2.0f * yf); + + // Hash function for corners + auto hash = [wrap](int x, int y) -> float { + uint32_t seed = static_cast((x & (wrap-1)) * 374761393 + (y & (wrap-1)) * 668265263); + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + return static_cast(seed) / static_cast(0xFFFFFFFF); + }; + + // Bilinear interpolation + float n00 = hash(xi, yi); + float n10 = hash(xi + 1, yi); + float n01 = hash(xi, yi + 1); + float n11 = hash(xi + 1, yi + 1); + + float nx0 = n00 * (1.0f - u) + n10 * u; + float nx1 = n01 * (1.0f - u) + n11 * u; + + return nx0 * (1.0f - v) + nx1 * v; +} + +bool NoiseTexture::generate(int size, float intensity) +{ + destroy(); + + if (size <= 0 || (size & (size - 1)) != 0) { + DEBUG_LOGF("NoiseTexture: Size must be power of 2, got %d\n", size); + return false; + } + + size_ = size; + + // Generate pure white noise — no coherent patterns, perfectly seamless + // when tiled because every pixel is independent. + std::vector data(size * size * 4); + uint32_t seed = 12345; + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + float r = random(seed); + // Apply intensity around mid-gray center + float value = 0.5f + (r - 0.5f) * intensity; + value = std::max(0.0f, std::min(1.0f, value)); + + uint8_t gray = static_cast(value * 255.0f); + int idx = (y * size + x) * 4; + data[idx + 0] = gray; + data[idx + 1] = gray; + data[idx + 2] = gray; + data[idx + 3] = 255; + } + } + + // Create OpenGL texture + glGenTextures(1, &texture_); + glBindTexture(GL_TEXTURE_2D, texture_); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); + + // NEAREST filtering preserves individual grain pixels; + // REPEAT wrapping ensures seamless tiling. + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + glBindTexture(GL_TEXTURE_2D, 0); + + DEBUG_LOGF("NoiseTexture: Generated %dx%d white noise texture (intensity=%.2f)\n", size, size, intensity); + + return texture_ != 0; +} + +void NoiseTexture::destroy() +{ + if (texture_) { + glDeleteTextures(1, &texture_); + texture_ = 0; + } + size_ = 0; +} + +// ============================================================================ +// NoiseUtils Implementation +// ============================================================================ + +namespace NoiseUtils { + +unsigned int createWhiteNoiseTexture(int size) +{ + std::vector data(size * size * 4); + + uint32_t seed = 42; + + for (int i = 0; i < size * size; i++) { + // Simple white noise + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + + uint8_t value = static_cast((seed >> 24) & 0xFF); + + data[i * 4 + 0] = value; + data[i * 4 + 1] = value; + data[i * 4 + 2] = value; + data[i * 4 + 3] = 255; + } + + GLuint texture; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + glBindTexture(GL_TEXTURE_2D, 0); + + return texture; +} + +unsigned int createBlueNoiseTexture(int size) +{ + // Blue noise has more even distribution - good for dithering + // Using a simple void-and-cluster algorithm approximation + + std::vector noise(size * size, 0.5f); + std::vector data(size * size * 4); + + uint32_t seed = 12345; + + // Start with white noise + for (int i = 0; i < size * size; i++) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + noise[i] = static_cast(seed) / static_cast(0xFFFFFFFF); + } + + // Apply a simple high-pass filter to reduce low frequencies + // (Very simplified blue noise approximation) + std::vector filtered(size * size); + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + float center = noise[y * size + x]; + float sum = 0.0f; + int count = 0; + + // Sample neighbors + for (int dy = -2; dy <= 2; dy++) { + for (int dx = -2; dx <= 2; dx++) { + if (dx == 0 && dy == 0) continue; + int nx = (x + dx + size) % size; + int ny = (y + dy + size) % size; + sum += noise[ny * size + nx]; + count++; + } + } + + float avg = sum / count; + filtered[y * size + x] = 0.5f + (center - avg) * 2.0f; + } + } + + // Convert to texture data + for (int i = 0; i < size * size; i++) { + float value = std::max(0.0f, std::min(1.0f, filtered[i])); + uint8_t gray = static_cast(value * 255.0f); + + data[i * 4 + 0] = gray; + data[i * 4 + 1] = gray; + data[i * 4 + 2] = gray; + data[i * 4 + 3] = 255; + } + + GLuint texture; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + glBindTexture(GL_TEXTURE_2D, 0); + + return texture; +} + +unsigned int createAcrylicNoiseTexture(int size) +{ + // Specially tuned noise for Microsoft Acrylic material look + // Very subtle, with a hint of blue-ish tint + + std::vector data(size * size * 4); + + uint32_t seed = 98765; + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + // Multiple noise layers + float n1 = NoiseTexture::noise2D(x * 0.5f, y * 0.5f, size); + float n2 = NoiseTexture::noise2D(x * 1.0f, y * 1.0f, size) * 0.5f; + float n3 = NoiseTexture::noise2D(x * 2.0f, y * 2.0f, size) * 0.25f; + + // White noise component + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + float white = static_cast(seed) / static_cast(0xFFFFFFFF); + + // Combine + float combined = (n1 + n2 + n3) / 1.75f * 0.6f + white * 0.4f; + + // Very subtle intensity (0.02 - 0.04 typical for acrylic) + float value = 0.5f + (combined - 0.5f) * 0.04f; + value = std::max(0.0f, std::min(1.0f, value)); + + uint8_t gray = static_cast(value * 255.0f); + + // Slight cool tint (very subtle) + int idx = (y * size + x) * 4; + data[idx + 0] = static_cast(gray * 0.98f); // R slightly less + data[idx + 1] = gray; // G + data[idx + 2] = static_cast(std::min(255, gray + 1)); // B slightly more + data[idx + 3] = 255; + } + } + + GLuint texture; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + glBindTexture(GL_TEXTURE_2D, 0); + + return texture; +} + +} // namespace NoiseUtils + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#else // !DRAGONX_HAS_GLAD + +// ============================================================================ +// Stub Implementation (No GLAD - Acrylic effects disabled) +// ============================================================================ + +#include +#include + +namespace dragonx { +namespace ui { +namespace effects { + +NoiseTexture::NoiseTexture() = default; +NoiseTexture::~NoiseTexture() = default; + +float NoiseTexture::random(uint32_t& seed) +{ + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + return static_cast(seed) / static_cast(0xFFFFFFFF); +} + +float NoiseTexture::noise2D(float x, float y, int wrap) +{ + // Provide a basic implementation for potential use elsewhere + int xi = static_cast(std::floor(x)) & (wrap - 1); + int yi = static_cast(std::floor(y)) & (wrap - 1); + uint32_t seed = static_cast(xi * 374761393 + yi * 668265263); + return random(seed); +} + +bool NoiseTexture::generate(int, float) { return false; } +void NoiseTexture::destroy() {} + +namespace NoiseUtils { +unsigned int createWhiteNoiseTexture(int) { return 0; } +unsigned int createBlueNoiseTexture(int) { return 0; } +unsigned int createAcrylicNoiseTexture(int) { return 0; } +} // namespace NoiseUtils + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // DRAGONX_HAS_GLAD diff --git a/src/ui/effects/noise_texture.h b/src/ui/effects/noise_texture.h new file mode 100644 index 0000000..1e2e126 --- /dev/null +++ b/src/ui/effects/noise_texture.h @@ -0,0 +1,113 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#ifndef GLAD_GL_H_ +typedef unsigned int GLuint; +typedef int GLint; +typedef unsigned int GLenum; +typedef int GLsizei; +#endif +#include + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief Generates procedural noise textures for acrylic grain effect + * + * Creates a tileable noise texture that adds subtle grain to acrylic surfaces, + * matching Microsoft's Fluent Design acrylic material. + */ +class NoiseTexture { +public: + NoiseTexture(); + ~NoiseTexture(); + + // Non-copyable + NoiseTexture(const NoiseTexture&) = delete; + NoiseTexture& operator=(const NoiseTexture&) = delete; + + /** + * @brief Generate a noise texture + * @param size Texture size (width = height, should be power of 2) + * @param intensity Noise intensity (0.0 - 1.0, typical: 0.02 - 0.04) + * @return true if successful + */ + bool generate(int size = 128, float intensity = 0.04f); + + /** + * @brief Release texture resources + */ + void destroy(); + + /** + * @brief Get the OpenGL texture ID + */ + GLuint getTexture() const { return texture_; } + + /** + * @brief Check if texture is valid + */ + bool isValid() const { return texture_ != 0; } + + /** + * @brief Get texture size + */ + int getSize() const { return size_; } + + /** + * @brief Simple pseudo-random number generator + * @param seed Seed value (modified in place) + * @return Random float in range [0, 1] + */ + static float random(uint32_t& seed); + + /** + * @brief Generate tileable Perlin-style noise value + */ + static float noise2D(float x, float y, int wrap); + +private: + GLuint texture_ = 0; + int size_ = 0; +}; + +/** + * @brief Static utility functions for noise generation + */ +namespace NoiseUtils { + +/** + * @brief Create a simple white noise texture + * @param size Texture dimensions (square) + * @return OpenGL texture ID (0 on failure) + */ +GLuint createWhiteNoiseTexture(int size); + +/** + * @brief Create a blue noise texture (better for dithering) + * @param size Texture dimensions (square) + * @return OpenGL texture ID (0 on failure) + */ +GLuint createBlueNoiseTexture(int size); + +/** + * @brief Create a pre-computed acrylic noise texture + * + * This creates a specially tuned noise texture that matches + * Microsoft's acrylic material appearance. + * + * @param size Texture dimensions (128 recommended) + * @return OpenGL texture ID (0 on failure) + */ +GLuint createAcrylicNoiseTexture(int size = 128); + +} // namespace NoiseUtils + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/scroll_fade_fbo.h b/src/ui/effects/scroll_fade_fbo.h new file mode 100644 index 0000000..5dd523a --- /dev/null +++ b/src/ui/effects/scroll_fade_fbo.h @@ -0,0 +1,418 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// Offscreen render-target scroll fade — the ImGui equivalent of CSS mask-image. +// Renders scrollable content to an offscreen surface, then composites it back +// as a textured mesh strip with vertex alpha for edge fading. +// This produces a true per-pixel fade that works with any background +// (including acrylic/backdrop transparency). +// +// Supports both OpenGL (DRAGONX_HAS_GLAD) and DX11 (DRAGONX_USE_DX11). + +#pragma once + +#include "imgui.h" +#include "imgui_internal.h" +#include + +// ============================================================================ +// Platform detection +// ============================================================================ +#if defined(DRAGONX_USE_DX11) + #include + #define SCROLL_FADE_HAS_OFFSCREEN 1 + #define SCROLL_FADE_DX11 1 +#elif defined(DRAGONX_HAS_GLAD) + #include +#include "../../util/logger.h" + #ifndef GL_FRAMEBUFFER_BINDING + #define GL_FRAMEBUFFER_BINDING 0x8CA6 + #endif + #ifndef GL_VIEWPORT + #define GL_VIEWPORT 0x0BA2 + #endif + #ifndef GL_SCISSOR_TEST + #define GL_SCISSOR_TEST 0x0C11 + #endif + #define SCROLL_FADE_HAS_OFFSCREEN 1 + #define SCROLL_FADE_GL 1 +#endif + +#ifdef SCROLL_FADE_HAS_OFFSCREEN + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// ScrollFadeRT — manages an offscreen render target for scroll-fade rendering +// ============================================================================ + +class ScrollFadeRT { +public: + ScrollFadeRT() = default; + ~ScrollFadeRT() { destroy(); } + + // Non-copyable + ScrollFadeRT(const ScrollFadeRT&) = delete; + ScrollFadeRT& operator=(const ScrollFadeRT&) = delete; + + /// Ensure RT matches the required dimensions. Returns true if ready. + bool ensure(int w, int h) { + if (w <= 0 || h <= 0) return false; + if (isValid() && w == width_ && h == height_) return true; + return init(w, h); + } + + void destroy(); + bool isValid() const; + + /// Get the texture as an ImTextureID for compositing. + ImTextureID textureID() const; + + int width() const { return width_; } + int height() const { return height_; } + +#ifdef SCROLL_FADE_DX11 + ID3D11RenderTargetView* rtv() const { return rtv_; } +#endif +#ifdef SCROLL_FADE_GL + unsigned int fbo() const { return fbo_; } +#endif + +private: + bool init(int w, int h); + + int width_ = 0; + int height_ = 0; + +#ifdef SCROLL_FADE_DX11 + ID3D11Texture2D* tex_ = nullptr; + ID3D11RenderTargetView* rtv_ = nullptr; + ID3D11ShaderResourceView* srv_ = nullptr; +#endif +#ifdef SCROLL_FADE_GL + unsigned int fbo_ = 0; + unsigned int colorTex_ = 0; +#endif +}; + +// ============================================================================ +// Implementations +// ============================================================================ + +#ifdef SCROLL_FADE_DX11 + +// --- DX11 helpers to get device/context from ImGui backend --- +inline ID3D11Device* GetDX11Device() { + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return nullptr; + return *reinterpret_cast(io.BackendRendererUserData); +} +inline ID3D11DeviceContext* GetDX11Context() { + ID3D11Device* dev = GetDX11Device(); + if (!dev) return nullptr; + ID3D11DeviceContext* ctx = nullptr; + dev->GetImmediateContext(&ctx); + return ctx; // caller must Release() +} + +inline bool ScrollFadeRT::init(int w, int h) { + destroy(); + ID3D11Device* dev = GetDX11Device(); + if (!dev) return false; + + width_ = w; + height_ = h; + + // Create texture + D3D11_TEXTURE2D_DESC td = {}; + td.Width = (UINT)w; + td.Height = (UINT)h; + td.MipLevels = 1; + td.ArraySize = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc.Count = 1; + td.Usage = D3D11_USAGE_DEFAULT; + td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; + + if (FAILED(dev->CreateTexture2D(&td, nullptr, &tex_))) { + DEBUG_LOGF("ScrollFadeRT: CreateTexture2D failed\n"); + destroy(); + return false; + } + + // Render target view + if (FAILED(dev->CreateRenderTargetView(tex_, nullptr, &rtv_))) { + DEBUG_LOGF("ScrollFadeRT: CreateRenderTargetView failed\n"); + destroy(); + return false; + } + + // Shader resource view (for sampling as texture) + if (FAILED(dev->CreateShaderResourceView(tex_, nullptr, &srv_))) { + DEBUG_LOGF("ScrollFadeRT: CreateShaderResourceView failed\n"); + destroy(); + return false; + } + + return true; +} + +inline void ScrollFadeRT::destroy() { + if (srv_) { srv_->Release(); srv_ = nullptr; } + if (rtv_) { rtv_->Release(); rtv_ = nullptr; } + if (tex_) { tex_->Release(); tex_ = nullptr; } + width_ = height_ = 0; +} + +inline bool ScrollFadeRT::isValid() const { return rtv_ != nullptr; } + +inline ImTextureID ScrollFadeRT::textureID() const { + return (ImTextureID)srv_; +} + +#endif // SCROLL_FADE_DX11 + +#ifdef SCROLL_FADE_GL + +inline bool ScrollFadeRT::init(int w, int h) { + destroy(); + width_ = w; + height_ = h; + + glGenFramebuffers(1, &fbo_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + + glGenTextures(1, &colorTex_); + glBindTexture(GL_TEXTURE_2D, colorTex_); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, colorTex_, 0); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindTexture(GL_TEXTURE_2D, 0); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + DEBUG_LOGF("ScrollFadeRT: FBO incomplete (0x%X)\n", status); + destroy(); + return false; + } + return true; +} + +inline void ScrollFadeRT::destroy() { + if (colorTex_) { glDeleteTextures(1, &colorTex_); colorTex_ = 0; } + if (fbo_) { glDeleteFramebuffers(1, &fbo_); fbo_ = 0; } + width_ = height_ = 0; +} + +inline bool ScrollFadeRT::isValid() const { return fbo_ != 0; } + +inline ImTextureID ScrollFadeRT::textureID() const { + return (ImTextureID)(intptr_t)colorTex_; +} + +#endif // SCROLL_FADE_GL + +// ============================================================================ +// Callback state — singleton storage for bind/unbind data +// ============================================================================ + +struct ScrollFadeState { +#ifdef SCROLL_FADE_DX11 + ID3D11RenderTargetView* offscreenRTV = nullptr; + ID3D11RenderTargetView* savedRTV = nullptr; + ID3D11DepthStencilView* savedDSV = nullptr; + D3D11_VIEWPORT savedVP = {}; +#endif +#ifdef SCROLL_FADE_GL + unsigned int fbo = 0; + int savedFBO = 0; + int savedVP[4] = {}; + bool savedScissorEnabled = true; // ImGui always has scissor enabled +#endif + int vpW = 0, vpH = 0; // framebuffer pixel dimensions for viewport +}; + +inline ScrollFadeState& GetScrollFadeState() { + static ScrollFadeState s; + return s; +} + +// ============================================================================ +// Callbacks — inserted into the draw list via AddCallback +// ============================================================================ + +#ifdef SCROLL_FADE_DX11 + +inline void BindRTCallback(const ImDrawList*, const ImDrawCmd*) { + auto& st = GetScrollFadeState(); + ID3D11DeviceContext* ctx = GetDX11Context(); + if (!ctx) return; + + // Save current RT and viewport + UINT numVP = 1; + ctx->OMGetRenderTargets(1, &st.savedRTV, &st.savedDSV); + ctx->RSGetViewports(&numVP, &st.savedVP); + + // Bind offscreen RT + ctx->OMSetRenderTargets(1, &st.offscreenRTV, nullptr); + + // Set viewport to match RT size + D3D11_VIEWPORT vp = {}; + vp.Width = (FLOAT)st.vpW; + vp.Height = (FLOAT)st.vpH; + vp.MaxDepth = 1.0f; + ctx->RSSetViewports(1, &vp); + + // Clear to transparent + float clearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + ctx->ClearRenderTargetView(st.offscreenRTV, clearColor); + + ctx->Release(); +} + +inline void UnbindRTCallback(const ImDrawList*, const ImDrawCmd*) { + auto& st = GetScrollFadeState(); + ID3D11DeviceContext* ctx = GetDX11Context(); + if (!ctx) return; + + // Restore previous RT and viewport + ctx->OMSetRenderTargets(1, &st.savedRTV, st.savedDSV); + ctx->RSSetViewports(1, &st.savedVP); + + // Release the refs from OMGetRenderTargets + if (st.savedRTV) { st.savedRTV->Release(); st.savedRTV = nullptr; } + if (st.savedDSV) { st.savedDSV->Release(); st.savedDSV = nullptr; } + + ctx->Release(); +} + +#endif // SCROLL_FADE_DX11 + +#ifdef SCROLL_FADE_GL + +inline void BindRTCallback(const ImDrawList*, const ImDrawCmd*) { + auto& st = GetScrollFadeState(); + + // Save current FBO and viewport + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &st.savedFBO); + glGetIntegerv(GL_VIEWPORT, st.savedVP); + + glBindFramebuffer(GL_FRAMEBUFFER, st.fbo); + glViewport(0, 0, st.vpW, st.vpH); + + // Disable scissor test inside the FBO. ImGui's renderer computes + // scissor rects relative to the main framebuffer dimensions — those + // coordinates would be wrong for our offscreen surface. The child + // window's content is already bounded by ImGui's layout, and the + // composite step applies its own clip rect, so skipping scissor + // in the FBO is safe. + glDisable(GL_SCISSOR_TEST); + + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); +} + +inline void UnbindRTCallback(const ImDrawList*, const ImDrawCmd*) { + auto& st = GetScrollFadeState(); + glBindFramebuffer(GL_FRAMEBUFFER, (unsigned int)st.savedFBO); + glViewport(st.savedVP[0], st.savedVP[1], st.savedVP[2], st.savedVP[3]); + if (st.savedScissorEnabled) + glEnable(GL_SCISSOR_TEST); +} + +#endif // SCROLL_FADE_GL + +// ============================================================================ +// Composite helper — draw the RT texture as a mesh strip with alpha fade +// ============================================================================ + +/// Draw the offscreen texture onto `dl` as a vertical strip with alpha=0 at +/// the faded edges and alpha=1 in the middle. Produces a true CSS-like +/// mask-image: linear-gradient() result. +/// +/// @param logicalW, logicalH Logical display dimensions (DisplaySize) for +/// UV calculation — NOT the RT pixel dimensions. ImGui screen coords +/// are in logical units, and the FBO projection maps them 1:1 to the +/// logical coordinate space, so UVs must divide by logical size. +inline void CompositeWithFade(ImDrawList* dl, + ImTextureID texID, + const ImVec2& screenMin, + const ImVec2& screenMax, + int logicalW, int logicalH, + float fadeTop, float fadeBot, + bool needTop, bool needBot) +{ + float left = screenMin.x; + float right = screenMax.x; + float y0 = screenMin.y; + float y1 = screenMin.y + (needTop ? fadeTop : 0.0f); + float y2 = screenMax.y - (needBot ? fadeBot : 0.0f); + float y3 = screenMax.y; + + // Clamp in case fade zones overlap + if (y1 > y2) { float mid = (y0 + y3) * 0.5f; y1 = y2 = mid; } + + // UV coordinates — map screen position (logical) to render target texture. + // Screen coords are in logical (DisplaySize) space. The FBO projection + // maps these 1:1, so divide by logical dimensions to get [0,1] UVs. + float uL = screenMin.x / (float)logicalW; + float uR = screenMax.x / (float)logicalW; + +#ifdef SCROLL_FADE_GL + // OpenGL: FBO Y is flipped (ImGui top=0 → GL bottom=0) + auto uvY = [&](float y) -> float { return 1.0f - y / (float)logicalH; }; +#else + // DX11: no Y flip (both ImGui and DX11 have (0,0) at top-left) + auto uvY = [&](float y) -> float { return y / (float)logicalH; }; +#endif + + ImU32 colOpaque = IM_COL32(255, 255, 255, 255); + ImU32 colClear = IM_COL32(255, 255, 255, 0); + ImU32 colTop = needTop ? colClear : colOpaque; + ImU32 colBot = needBot ? colClear : colOpaque; + + dl->PushTextureID(texID); + dl->PrimReserve(18, 8); + + ImDrawVert* vtx = dl->_VtxWritePtr; + ImDrawIdx* idx = dl->_IdxWritePtr; + ImDrawIdx base = (ImDrawIdx)dl->_VtxCurrentIdx; + + vtx[0] = { ImVec2(left, y0), ImVec2(uL, uvY(y0)), colTop }; + vtx[1] = { ImVec2(right, y0), ImVec2(uR, uvY(y0)), colTop }; + vtx[2] = { ImVec2(left, y1), ImVec2(uL, uvY(y1)), colOpaque }; + vtx[3] = { ImVec2(right, y1), ImVec2(uR, uvY(y1)), colOpaque }; + vtx[4] = { ImVec2(left, y2), ImVec2(uL, uvY(y2)), colOpaque }; + vtx[5] = { ImVec2(right, y2), ImVec2(uR, uvY(y2)), colOpaque }; + vtx[6] = { ImVec2(left, y3), ImVec2(uL, uvY(y3)), colBot }; + vtx[7] = { ImVec2(right, y3), ImVec2(uR, uvY(y3)), colBot }; + + idx[0] = base+0; idx[1] = base+1; idx[2] = base+3; + idx[3] = base+0; idx[4] = base+3; idx[5] = base+2; + idx[6] = base+2; idx[7] = base+3; idx[8] = base+5; + idx[9] = base+2; idx[10] = base+5; idx[11] = base+4; + idx[12] = base+4; idx[13] = base+5; idx[14] = base+7; + idx[15] = base+4; idx[16] = base+7; idx[17] = base+6; + + dl->_VtxWritePtr += 8; + dl->_IdxWritePtr += 18; + dl->_VtxCurrentIdx += 8; + + dl->PopTextureID(); +} + +} // namespace effects +} // namespace ui +} // namespace dragonx + +#endif // SCROLL_FADE_HAS_OFFSCREEN diff --git a/src/ui/effects/scroll_fade_shader.h b/src/ui/effects/scroll_fade_shader.h new file mode 100644 index 0000000..75045eb --- /dev/null +++ b/src/ui/effects/scroll_fade_shader.h @@ -0,0 +1,416 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// Shader-based scroll-edge fade effect. +// +// Inserts ImDrawCallback entries into the draw list to switch from ImGui's +// default shader to a custom shader that multiplies output alpha by a +// smoothstep gradient based on screen-Y position. After the fade region, +// ImDrawCallback_ResetRenderState restores ImGui's default render state. +// +// GL path: custom GLSL 130 program (VS + FS), uses gl_FragCoord.y +// DX11 path: custom pixel shader only, uses SV_POSITION.y + +#pragma once + +#include "imgui.h" +#include "imgui_internal.h" + +// ---- Platform headers ---- +#ifdef DRAGONX_HAS_GLAD +#include +#endif + +#ifdef DRAGONX_USE_DX11 +#include +#include +#endif + +#include +#include +#include +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// ScrollFadeShader — per-pixel scroll-edge alpha mask via ImDrawCallback +// ============================================================================ + +struct ScrollFadeShader { + // ---- Caller-set parameters (logical screen-space, per-frame) ---- + float fadeTopY = 0.0f; // top of scrollable region (screen Y) + float fadeBottomY = 0.0f; // bottom of scrollable region (screen Y) + float fadeZoneTop = 0.0f; // top fade height (0 = disabled) + float fadeZoneBottom = 0.0f; // bottom fade height (0 = disabled) + + // ---- Internal state ---- + bool ready = false; + +#ifdef DRAGONX_HAS_GLAD + GLuint program_ = 0; + GLint locProjMtx_ = -1; + GLint locTexture_ = -1; + GLint locFadeTopY_ = -1; + GLint locFadeBottomY_= -1; + GLint locFadeZoneTop_= -1; + GLint locFadeZoneBot_= -1; + GLint locViewportH_ = -1; +#endif + +#ifdef DRAGONX_USE_DX11 + ID3D11PixelShader* pFadePS_ = nullptr; + ID3D11Buffer* pFadeCB_ = nullptr; +#endif + + // ---------------------------------------------------------------- + // Init / Destroy + // ---------------------------------------------------------------- + + bool init() { + if (ready) return true; +#ifdef DRAGONX_HAS_GLAD + ready = initGL(); +#elif defined(DRAGONX_USE_DX11) + ready = initDX11(); +#endif + return ready; + } + + void destroy() { +#ifdef DRAGONX_HAS_GLAD + destroyGL(); +#elif defined(DRAGONX_USE_DX11) + destroyDX11(); +#endif + ready = false; + } + + // ---------------------------------------------------------------- + // Draw-list integration helpers + // ---------------------------------------------------------------- + + /// Insert a "bind fade shader" callback into the draw list. + /// Must be followed later by addUnbind() or AddCallback(ImDrawCallback_ResetRenderState). + void addBind(ImDrawList* dl) { + dl->AddCallback(BindCB, this); + } + + /// Insert ImDrawCallback_ResetRenderState to restore ImGui's default shader. + static void addUnbind(ImDrawList* dl) { + dl->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + } + + // ================================================================ + // GL implementation + // ================================================================ +#ifdef DRAGONX_HAS_GLAD + + static constexpr const char* kFadeVS_130 = + "#version 130\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; + + static constexpr const char* kFadeFS_130 = + "#version 130\n" + "uniform sampler2D Texture;\n" + "uniform float u_fadeTopY;\n" + "uniform float u_fadeBottomY;\n" + "uniform float u_fadeZoneTop;\n" + "uniform float u_fadeZoneBot;\n" + "uniform float u_viewportH;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main() {\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + " float y = u_viewportH - gl_FragCoord.y;\n" // bottom-up → top-down + " float topA = (u_fadeZoneTop > 0.0)\n" + " ? smoothstep(u_fadeTopY, u_fadeTopY + u_fadeZoneTop, y)\n" + " : 1.0;\n" + " float botA = (u_fadeZoneBot > 0.0)\n" + " ? (1.0 - smoothstep(u_fadeBottomY - u_fadeZoneBot, u_fadeBottomY, y))\n" + " : 1.0;\n" + " Out_Color.a *= topA * botA;\n" + "}\n"; + + bool initGL() { + GLuint vs = glCreateShader(GL_VERTEX_SHADER); + GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(vs, 1, &kFadeVS_130, nullptr); + glCompileShader(vs); + if (!checkShader(vs, "fade VS")) { glDeleteShader(vs); glDeleteShader(fs); return false; } + + glShaderSource(fs, 1, &kFadeFS_130, nullptr); + glCompileShader(fs); + if (!checkShader(fs, "fade FS")) { glDeleteShader(vs); glDeleteShader(fs); return false; } + + program_ = glCreateProgram(); + glAttachShader(program_, vs); + glAttachShader(program_, fs); + + // Force attribute locations to match ImGui's typical assignment + // (Position=0, UV=1, Color=2) so that the VAO set up by ImGui's + // backend is compatible with our program. + glBindAttribLocation(program_, 0, "Position"); + glBindAttribLocation(program_, 1, "UV"); + glBindAttribLocation(program_, 2, "Color"); + + glLinkProgram(program_); + glDetachShader(program_, vs); + glDetachShader(program_, fs); + glDeleteShader(vs); + glDeleteShader(fs); + + if (!checkProgram(program_, "fade program")) { + glDeleteProgram(program_); + program_ = 0; + return false; + } + + locProjMtx_ = glGetUniformLocation(program_, "ProjMtx"); + locTexture_ = glGetUniformLocation(program_, "Texture"); + locFadeTopY_ = glGetUniformLocation(program_, "u_fadeTopY"); + locFadeBottomY_ = glGetUniformLocation(program_, "u_fadeBottomY"); + locFadeZoneTop_ = glGetUniformLocation(program_, "u_fadeZoneTop"); + locFadeZoneBot_ = glGetUniformLocation(program_, "u_fadeZoneBot"); + locViewportH_ = glGetUniformLocation(program_, "u_viewportH"); + + DEBUG_LOGF("ScrollFadeShader: GL program %u (ProjMtx=%d Tex=%d top=%d bot=%d zt=%d zb=%d vh=%d)\n", + program_, locProjMtx_, locTexture_, + locFadeTopY_, locFadeBottomY_, locFadeZoneTop_, locFadeZoneBot_, locViewportH_); + return true; + } + + void destroyGL() { + if (program_) { glDeleteProgram(program_); program_ = 0; } + } + + static bool checkShader(GLuint s, const char* label) { + GLint ok = 0; + glGetShaderiv(s, GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[512]; + glGetShaderInfoLog(s, sizeof(log), nullptr, log); + DEBUG_LOGF("ScrollFadeShader: %s compile error:\n%s\n", label, log); + } + return ok != 0; + } + + static bool checkProgram(GLuint p, const char* label) { + GLint ok = 0; + glGetProgramiv(p, GL_LINK_STATUS, &ok); + if (!ok) { + char log[512]; + glGetProgramInfoLog(p, sizeof(log), nullptr, log); + DEBUG_LOGF("ScrollFadeShader: %s link error:\n%s\n", label, log); + } + return ok != 0; + } + +#endif // DRAGONX_HAS_GLAD + + // ================================================================ + // DX11 implementation + // ================================================================ +#ifdef DRAGONX_USE_DX11 + + // Pixel-shader constant buffer layout (must be 16-byte aligned) + struct alignas(16) FadeCBData { + float fadeTopY; + float fadeBottomY; + float fadeZoneTop; + float fadeZoneBot; + }; + + static constexpr const char* kFadePS_HLSL = + "cbuffer FadeParams : register(b1) {\n" + " float u_fadeTopY;\n" + " float u_fadeBottomY;\n" + " float u_fadeZoneTop;\n" + " float u_fadeZoneBot;\n" + "};\n" + "struct PS_INPUT {\n" + " float4 pos : SV_POSITION;\n" + " float4 col : COLOR0;\n" + " float2 uv : TEXCOORD0;\n" + "};\n" + "sampler sampler0;\n" + "Texture2D texture0;\n" + "float4 main(PS_INPUT input) : SV_Target {\n" + " float4 out_col = input.col * texture0.Sample(sampler0, input.uv);\n" + " float y = input.pos.y;\n" // SV_POSITION.y is top-down in FB pixels + " float topA = (u_fadeZoneTop > 0.0)\n" + " ? smoothstep(u_fadeTopY, u_fadeTopY + u_fadeZoneTop, y)\n" + " : 1.0;\n" + " float botA = (u_fadeZoneBot > 0.0)\n" + " ? (1.0 - smoothstep(u_fadeBottomY - u_fadeZoneBot, u_fadeBottomY, y))\n" + " : 1.0;\n" + " out_col.a *= topA * botA;\n" + " return out_col;\n" + "}\n"; + + bool initDX11() { + // Get DX11 device from ImGui backend + auto* bd = ImGui::GetIO().BackendRendererUserData; + if (!bd) { DEBUG_LOGF("ScrollFadeShader: no DX11 backend data\n"); return false; } + + // ImGui_ImplDX11_Data layout: first field is ID3D11Device* + ID3D11Device* device = *(ID3D11Device**)bd; + if (!device) { DEBUG_LOGF("ScrollFadeShader: null DX11 device\n"); return false; } + + // Compile pixel shader + ID3DBlob* psBlob = nullptr; + ID3DBlob* errBlob = nullptr; + HRESULT hr = D3DCompile(kFadePS_HLSL, strlen(kFadePS_HLSL), + nullptr, nullptr, nullptr, + "main", "ps_4_0", 0, 0, + &psBlob, &errBlob); + if (FAILED(hr)) { + if (errBlob) { + DEBUG_LOGF("ScrollFadeShader: PS compile error:\n%s\n", + (const char*)errBlob->GetBufferPointer()); + errBlob->Release(); + } + return false; + } + if (errBlob) errBlob->Release(); + + hr = device->CreatePixelShader(psBlob->GetBufferPointer(), + psBlob->GetBufferSize(), + nullptr, &pFadePS_); + psBlob->Release(); + if (FAILED(hr)) { + DEBUG_LOGF("ScrollFadeShader: CreatePixelShader failed 0x%08lx\n", hr); + return false; + } + + // Create constant buffer for fade params + D3D11_BUFFER_DESC cbDesc = {}; + cbDesc.ByteWidth = sizeof(FadeCBData); + cbDesc.Usage = D3D11_USAGE_DYNAMIC; + cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + hr = device->CreateBuffer(&cbDesc, nullptr, &pFadeCB_); + if (FAILED(hr)) { + DEBUG_LOGF("ScrollFadeShader: CreateBuffer (CB) failed 0x%08lx\n", hr); + pFadePS_->Release(); pFadePS_ = nullptr; + return false; + } + + DEBUG_LOGF("ScrollFadeShader: DX11 pixel shader + CB created\n"); + return true; + } + + void destroyDX11() { + if (pFadeCB_) { pFadeCB_->Release(); pFadeCB_ = nullptr; } + if (pFadePS_) { pFadePS_->Release(); pFadePS_ = nullptr; } + } + +#endif // DRAGONX_USE_DX11 + + // ================================================================ + // Callback — called by ImGui's render backend during RenderDrawData + // ================================================================ + + static void BindCB(const ImDrawList* /*dl*/, const ImDrawCmd* cmd) { + auto* self = static_cast(cmd->UserCallbackData); + if (!self || !self->ready) return; + + ImGuiIO& io = ImGui::GetIO(); + float fbScaleY = io.DisplayFramebufferScale.y; + float fb_height = io.DisplaySize.y * fbScaleY; + + // In multi-viewport mode ImGui coordinates are OS-absolute, but + // SV_POSITION / gl_FragCoord are render-target-relative. Subtract + // the main viewport origin to convert screen-space → RT-local. + float vpY = ImGui::GetMainViewport()->Pos.y; + + // Convert logical screen-space params to framebuffer pixels + float topY = (self->fadeTopY - vpY) * fbScaleY; + float botY = (self->fadeBottomY - vpY) * fbScaleY; + float zoneTop = self->fadeZoneTop * fbScaleY; + float zoneBot = self->fadeZoneBottom * fbScaleY; + +#ifdef DRAGONX_HAS_GLAD + glUseProgram(self->program_); + + // Rebind vertex attribute pointers so our forced locations (0=Position, + // 1=UV, 2=Color) match the already-bound VBO data. ImGui's linker may + // assign different locations (e.g. Mesa uses alphabetical order: + // Color=0, Position=1, UV=2), but the VBO layout is fixed, so we + // must explicitly point our attributes at the correct offsets. + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)); + glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glEnableVertexAttribArray(2); + + // Ortho projection — must match ImGui's SetupRenderState which uses + // draw_data->DisplayPos as the origin. With ViewportsEnable, vertex + // positions are in OS screen-space; the projection matrix maps them + // to window-local framebuffer coordinates. + float vpX = ImGui::GetMainViewport()->Pos.x; + float L = vpX; + float R = vpX + io.DisplaySize.x; + float T = vpY; + float B = vpY + io.DisplaySize.y; + const float ortho[4][4] = { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, + }; + glUniformMatrix4fv(self->locProjMtx_, 1, GL_FALSE, &ortho[0][0]); + glUniform1i(self->locTexture_, 0); + glUniform1f(self->locFadeTopY_, topY); + glUniform1f(self->locFadeBottomY_, botY); + glUniform1f(self->locFadeZoneTop_, zoneTop); + glUniform1f(self->locFadeZoneBot_, zoneBot); + glUniform1f(self->locViewportH_, fb_height); +#endif + +#ifdef DRAGONX_USE_DX11 + (void)fb_height; + // Get device context from ImGui backend (first two fields of ImGui_ImplDX11_Data) + auto* bd = io.BackendRendererUserData; + if (!bd) return; + struct DX11BD { ID3D11Device* dev; ID3D11DeviceContext* ctx; }; + auto* dx = reinterpret_cast(bd); + ID3D11DeviceContext* ctx = dx->ctx; + if (!ctx) return; + + // Update constant buffer + D3D11_MAPPED_SUBRESOURCE mapped; + if (SUCCEEDED(ctx->Map(self->pFadeCB_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) { + auto* cb = static_cast(mapped.pData); + cb->fadeTopY = topY; + cb->fadeBottomY = botY; + cb->fadeZoneTop = zoneTop; + cb->fadeZoneBot = zoneBot; + ctx->Unmap(self->pFadeCB_, 0); + } + + // Bind our pixel shader + constant buffer (slot 1 = register(b1)) + ctx->PSSetShader(self->pFadePS_, nullptr, 0); + ctx->PSSetConstantBuffers(1, 1, &self->pFadeCB_); +#endif + } +}; + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/theme_effects.cpp b/src/ui/effects/theme_effects.cpp new file mode 100644 index 0000000..53051a8 --- /dev/null +++ b/src/ui/effects/theme_effects.cpp @@ -0,0 +1,1152 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "theme_effects.h" +#include "low_spec.h" +#include "../schema/ui_schema.h" +#include +#include +#include +#include +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { +namespace effects { + +// ============================================================================ +// Singleton +// ============================================================================ + +ThemeEffects& ThemeEffects::instance() { + static ThemeEffects s; + return s; +} + +// ============================================================================ +// Frame update +// ============================================================================ + +void ThemeEffects::beginFrame() { + time_ = (float)ImGui::GetTime(); + ImGuiViewport* vp = ImGui::GetMainViewport(); + vpMinY_ = vp->WorkPos.y; + vpMaxY_ = vp->WorkPos.y + vp->WorkSize.y; +} + +// ============================================================================ +// Load config from [effects] section via UISchema +// ============================================================================ + +void ThemeEffects::loadFromTheme() { + auto& S = schema::UI(); + auto eff = [&](const char* name) { + return S.drawElement("effects", name); + }; + + // ---- Hue Cycle ---- + hue_cycle_.enabled = eff("hue-cycle-enabled").sizeOr(0.0f) > 0.5f; + hue_cycle_.speed = eff("hue-cycle-speed").sizeOr(0.1f); + hue_cycle_.sat = eff("hue-cycle-saturation").sizeOr(0.6f); + hue_cycle_.val = eff("hue-cycle-value").sizeOr(0.85f); + hue_cycle_.range = eff("hue-cycle-range").sizeOr(1.0f); + hue_cycle_.offset = eff("hue-cycle-offset").sizeOr(0.0f); + + // ---- Rainbow Border ---- + rainbow_border_.enabled = eff("rainbow-border-enabled").sizeOr(0.0f) > 0.5f; + rainbow_border_.speed = eff("rainbow-border-speed").sizeOr(0.05f); + rainbow_border_.alpha = eff("rainbow-border-alpha").sizeOr(0.25f); + rainbow_border_.stops.clear(); + + // Read color stops from extraColors (stored as stop-0, stop-1, etc.) + for (int i = 0; i < 8; i++) { + char key[32]; + snprintf(key, sizeof(key), "rainbow-border-stop-%d", i); + auto elem = eff(key); + if (!elem.color.empty()) { + rainbow_border_.stops.push_back(parseHexColor(elem.color)); + } else if (elem.size > 0) { + break; // no more stops + } + } + // Fallback default stops + if (rainbow_border_.enabled && rainbow_border_.stops.empty()) { + rainbow_border_.stops.push_back(IM_COL32(255, 107, 157, 255)); + rainbow_border_.stops.push_back(IM_COL32(192, 132, 252, 255)); + rainbow_border_.stops.push_back(IM_COL32(103, 232, 249, 255)); + rainbow_border_.stops.push_back(IM_COL32(252, 165, 165, 255)); + } + + // ---- Shimmer ---- + shimmer_.enabled = eff("shimmer-enabled").sizeOr(0.0f) > 0.5f; + shimmer_.speed = eff("shimmer-speed").sizeOr(0.12f); + shimmer_.width = eff("shimmer-width").sizeOr(80.0f); + shimmer_.alpha = eff("shimmer-alpha").sizeOr(0.06f); + shimmer_.angle = eff("shimmer-angle").sizeOr(30.0f); + // Shimmer color: read from the schema's color resolver + auto shimmerColorElem = eff("shimmer-color"); + if (!shimmerColorElem.color.empty()) { + shimmer_.color = S.resolveColor(shimmerColorElem.color, IM_COL32(255,255,255,255)); + } else { + shimmer_.color = IM_COL32(255, 255, 255, 255); + } + + // ---- Positional Hue ---- + positional_hue_.enabled = eff("positional-hue-enabled").sizeOr(0.0f) > 0.5f; + positional_hue_.strength = eff("positional-hue-strength").sizeOr(0.3f); + auto topElem = eff("positional-hue-top"); + auto botElem = eff("positional-hue-bottom"); + if (!topElem.color.empty()) + positional_hue_.topColor = parseHexColorVec4(topElem.color); + if (!botElem.color.empty()) + positional_hue_.bottomColor = parseHexColorVec4(botElem.color); + + // ---- Glow Pulse ---- + glow_pulse_.enabled = eff("glow-pulse-enabled").sizeOr(0.0f) > 0.5f; + glow_pulse_.speed = eff("glow-pulse-speed").sizeOr(2.0f); + glow_pulse_.minAlpha = eff("glow-pulse-min-alpha").sizeOr(0.0f); + glow_pulse_.maxAlpha = eff("glow-pulse-max-alpha").sizeOr(0.15f); + glow_pulse_.radius = eff("glow-pulse-radius").sizeOr(4.0f); + auto glowColorElem = eff("glow-pulse-color"); + if (!glowColorElem.color.empty()) { + glow_pulse_.color = S.resolveColor(glowColorElem.color, IM_COL32(255, 218, 0, 255)); + } else { + glow_pulse_.color = IM_COL32(255, 218, 0, 255); + } + + // ---- Edge Trace ---- + edge_trace_.enabled = eff("edge-trace-enabled").sizeOr(0.0f) > 0.5f; + edge_trace_.speed = eff("edge-trace-speed").sizeOr(0.3f); + edge_trace_.length = eff("edge-trace-length").sizeOr(0.20f); + edge_trace_.thickness = eff("edge-trace-thickness").sizeOr(1.5f); + edge_trace_.alpha = eff("edge-trace-alpha").sizeOr(0.6f); + auto edgeColorElem = eff("edge-trace-color"); + if (!edgeColorElem.color.empty()) { + edge_trace_.color = S.resolveColor(edgeColorElem.color, IM_COL32(255, 255, 255, 255)); + } else { + edge_trace_.color = IM_COL32(255, 255, 255, 255); + } + + // ---- Ember Rise ---- + ember_rise_.enabled = eff("ember-rise-enabled").sizeOr(0.0f) > 0.5f; + ember_rise_.count = (int)eff("ember-rise-count").sizeOr(8.0f); + ember_rise_.speed = eff("ember-rise-speed").sizeOr(0.4f); + ember_rise_.particleSize = eff("ember-rise-particle-size").sizeOr(1.5f); + ember_rise_.alpha = eff("ember-rise-alpha").sizeOr(0.5f); + auto emberColorElem = eff("ember-rise-color"); + if (!emberColorElem.color.empty()) { + ember_rise_.color = S.resolveColor(emberColorElem.color, IM_COL32(255, 120, 20, 255)); + } else { + ember_rise_.color = IM_COL32(255, 120, 20, 255); + } + + // ---- Gradient Border Shift ---- + gradient_border_.enabled = eff("gradient-border-enabled").sizeOr(0.0f) > 0.5f; + gradient_border_.speed = eff("gradient-border-speed").sizeOr(0.15f); + gradient_border_.thickness = eff("gradient-border-thickness").sizeOr(1.5f); + gradient_border_.alpha = eff("gradient-border-alpha").sizeOr(0.6f); + auto gbColorA = eff("gradient-border-color-a"); + if (!gbColorA.color.empty()) { + gradient_border_.colorA = S.resolveColor(gbColorA.color, IM_COL32(206, 147, 216, 255)); + } + auto gbColorB = eff("gradient-border-color-b"); + if (!gbColorB.color.empty()) { + gradient_border_.colorB = S.resolveColor(gbColorB.color, IM_COL32(26, 35, 126, 255)); + } + + // ---- Specular Glare ---- + specular_glare_.enabled = eff("specular-glare-enabled").sizeOr(0.0f) > 0.5f; + specular_glare_.speed = eff("specular-glare-speed").sizeOr(0.02f); + specular_glare_.intensity = eff("specular-glare-intensity").sizeOr(0.06f); + specular_glare_.radius = eff("specular-glare-radius").sizeOr(0.5f); + specular_glare_.count = (int)eff("specular-glare-count").sizeOr(2.0f); + auto glareColorElem = eff("specular-glare-color"); + if (!glareColorElem.color.empty()) { + specular_glare_.color = S.resolveColor(glareColorElem.color, IM_COL32(255, 255, 255, 255)); + } else { + specular_glare_.color = IM_COL32(255, 255, 255, 255); + } + + // ---- Sandstorm ---- + sandstorm_.enabled = eff("sandstorm-enabled").sizeOr(0.0f) > 0.5f; + sandstorm_.count = (int)eff("sandstorm-count").sizeOr(80.0f); + sandstorm_.speed = eff("sandstorm-speed").sizeOr(0.35f); + sandstorm_.windAngle = eff("sandstorm-wind-angle").sizeOr(15.0f); + sandstorm_.particleSize = eff("sandstorm-particle-size").sizeOr(1.5f); + sandstorm_.alpha = eff("sandstorm-alpha").sizeOr(0.35f); + sandstorm_.gustSpeed = eff("sandstorm-gust-speed").sizeOr(0.07f); + sandstorm_.gustStrength = eff("sandstorm-gust-strength").sizeOr(0.4f); + sandstorm_.streakLength = eff("sandstorm-streak-length").sizeOr(3.0f); + auto sandColorElem = eff("sandstorm-color"); + if (!sandColorElem.color.empty()) { + sandstorm_.color = S.resolveColor(sandColorElem.color, IM_COL32(200, 160, 96, 255)); + } else { + sandstorm_.color = IM_COL32(200, 160, 96, 255); + } + + // ---- Viewport Overlay (shader-like post-processing) ---- + viewport_overlay_.colorWashEnabled = eff("viewport-wash-enabled").sizeOr(0.0f) > 0.5f; + viewport_overlay_.washAlpha = eff("viewport-wash-alpha").sizeOr(0.05f); + viewport_overlay_.washRotateSpeed = eff("viewport-wash-rotate").sizeOr(0.0f); + viewport_overlay_.washPulseSpeed = eff("viewport-wash-pulse").sizeOr(0.0f); + viewport_overlay_.washPulseDepth = eff("viewport-wash-pulse-depth").sizeOr(0.0f); + auto washTL = eff("viewport-wash-tl"); + auto washTR = eff("viewport-wash-tr"); + auto washBL = eff("viewport-wash-bl"); + auto washBR = eff("viewport-wash-br"); + if (!washTL.color.empty()) viewport_overlay_.cornerTL = S.resolveColor(washTL.color, IM_COL32(255,100,0,255)); + if (!washTR.color.empty()) viewport_overlay_.cornerTR = S.resolveColor(washTR.color, IM_COL32(68,34,0,255)); + if (!washBL.color.empty()) viewport_overlay_.cornerBL = S.resolveColor(washBL.color, IM_COL32(68,17,0,255)); + if (!washBR.color.empty()) viewport_overlay_.cornerBR = S.resolveColor(washBR.color, IM_COL32(255,153,0,255)); + + viewport_overlay_.vignetteEnabled = eff("viewport-vignette-enabled").sizeOr(0.0f) > 0.5f; + viewport_overlay_.vignetteRadius = eff("viewport-vignette-radius").sizeOr(0.35f); + viewport_overlay_.vignetteAlpha = eff("viewport-vignette-alpha").sizeOr(0.30f); + auto vigColorElem = eff("viewport-vignette-color"); + if (!vigColorElem.color.empty()) { + viewport_overlay_.vignetteColor = S.resolveColor(vigColorElem.color, IM_COL32(0,0,0,255)); + } else { + viewport_overlay_.vignetteColor = IM_COL32(0,0,0,255); + } + + DEBUG_LOGF("[ThemeEffects] Loaded — hue:%d rainbow:%d shimmer:%d pos_hue:%d glow:%d edge:%d ember:%d glare:%d sand:%d wash:%d vignette:%d\n", + hue_cycle_.enabled, rainbow_border_.enabled, shimmer_.enabled, + positional_hue_.enabled, glow_pulse_.enabled, + edge_trace_.enabled, ember_rise_.enabled, specular_glare_.enabled, + sandstorm_.enabled, + viewport_overlay_.colorWashEnabled, viewport_overlay_.vignetteEnabled); +} + +// ============================================================================ +// Hue-Cycling Accents +// ============================================================================ + +ImU32 ThemeEffects::getAccentColor(float phaseOffset) const { + if (!enabled_ || !hue_cycle_.enabled) return IM_COL32(255, 218, 0, 255); + + float hue = std::fmod(hue_cycle_.offset + time_ * hue_cycle_.speed + phaseOffset, 1.0f); + if (hue < 0.0f) hue += 1.0f; + // Clamp to configured range + hue = hue_cycle_.offset + std::fmod(hue, std::max(0.01f, hue_cycle_.range)); + hue = std::fmod(hue, 1.0f); + + float r, g, b; + ImGui::ColorConvertHSVtoRGB(hue, hue_cycle_.sat, hue_cycle_.val, r, g, b); + return IM_COL32((int)(r * 255), (int)(g * 255), (int)(b * 255), 255); +} + +// ============================================================================ +// Rainbow Gradient Border +// ============================================================================ + +ImU32 ThemeEffects::sampleGradient(float t) const { + if (rainbow_border_.stops.empty()) return IM_COL32(255,255,255,128); + int n = (int)rainbow_border_.stops.size(); + if (n == 1) return rainbow_border_.stops[0]; + + t = std::fmod(t, 1.0f); + if (t < 0.0f) t += 1.0f; + + float segment = t * n; + int idx = (int)segment; + float frac = segment - idx; + int next = (idx + 1) % n; + idx = idx % n; + + ImU32 c1 = rainbow_border_.stops[idx]; + ImU32 c2 = rainbow_border_.stops[next]; + + // Lerp RGBA components + int r = (int)((c1 & 0xFF) + frac * (((int)(c2 & 0xFF)) - (int)(c1 & 0xFF))); + int g = (int)(((c1 >> 8) & 0xFF) + frac * (((int)((c2 >> 8) & 0xFF)) - (int)((c1 >> 8) & 0xFF))); + int b = (int)(((c1 >> 16) & 0xFF) + frac * (((int)((c2 >> 16) & 0xFF)) - (int)((c1 >> 16) & 0xFF))); + int a = (int)(rainbow_border_.alpha * bgOpacity_ * 255.0f); + + return IM_COL32(r, g, b, a); +} + +void ThemeEffects::drawRainbowBorder(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding, float thickness) const { + if (!enabled_ || !rainbow_border_.enabled || rainbow_border_.stops.empty()) return; + + float t = time_ * rainbow_border_.speed; + + // Draw the rainbow border as line segments around the rounded perimeter. + // Each segment gets a color sampled from the gradient at its position, + // giving a smoothly rotating hue-shift that follows rounded corners. + // + // We need enough segments so that the curved corners are smooth. + // Each corner arc ≈ π*r/2 pixels. We want ~1 segment per 2-3px of arc + // to look smooth, plus the straight edges. + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + float r = std::min(rounding, std::min(w, h) * 0.5f); + float cornerSegs = (r > 0.5f) ? std::ceil(r * 1.5f) : 0.0f; // segments per corner arc + int segments = std::max(48, (int)(4 * cornerSegs + 2 * (w + h) / 8.0f)); + segments = std::min(segments, 256); // cap for perf + + ImVec2 prev = perimeterPoint(pMin, pMax, 0.0f, rounding); + for (int i = 1; i <= segments; i++) { + float frac = (float)i / (float)segments; + ImVec2 pt = perimeterPoint(pMin, pMax, frac, rounding); + + // Sample gradient at the midpoint of this segment for smooth color + float midFrac = (frac - 0.5f / segments); + ImU32 c = sampleGradient(t + midFrac); + + dl->AddLine(prev, pt, c, thickness); + prev = pt; + } +} + +// ============================================================================ +// Shimmer Sweep +// ============================================================================ + +void ThemeEffects::drawShimmer(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || !shimmer_.enabled) return; + + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w <= 0 || h <= 0) return; + + // Sweep position: band moves left to right across the panel + float period = 1.0f / std::max(0.01f, shimmer_.speed); + float totalTravel = w + shimmer_.width * 2.0f; // band enters and exits + float pos = std::fmod(time_ / period, 1.0f) * totalTravel - shimmer_.width; + + // Band bounds (horizontal, ignoring angle for simplicity in this version) + float bandLeft = pMin.x + pos; + float bandRight = bandLeft + shimmer_.width; + + // Clip to panel + float clLeft = std::max(bandLeft, pMin.x); + float clRight = std::min(bandRight, pMax.x); + if (clLeft >= clRight) return; + + float mid = (clLeft + clRight) * 0.5f; + int peakA = (int)(shimmer_.alpha * bgOpacity_ * 255.0f); + peakA = std::clamp(peakA, 0, 255); + + // Extract shimmer color RGB (ignore alpha, use shimmer_.alpha) + int sR = shimmer_.color & 0xFF; + int sG = (shimmer_.color >> 8) & 0xFF; + int sB = (shimmer_.color >> 16) & 0xFF; + + ImU32 clear = IM_COL32(sR, sG, sB, 0); + ImU32 peak = IM_COL32(sR, sG, sB, peakA); + + // Inset clip rect by corner rounding to prevent shimmer bleeding into rounded corners + float cr = std::min(rounding, std::min(w, h) * 0.5f) * 0.3f; + dl->PushClipRect(ImVec2(pMin.x + cr, pMin.y + cr), + ImVec2(pMax.x - cr, pMax.y - cr), true); + + // Left half: transparent → peak + if (clLeft < mid) { + dl->AddRectFilledMultiColor( + ImVec2(clLeft, pMin.y), ImVec2(mid, pMax.y), + clear, peak, peak, clear); + } + // Right half: peak → transparent + if (mid < clRight) { + dl->AddRectFilledMultiColor( + ImVec2(mid, pMin.y), ImVec2(clRight, pMax.y), + peak, clear, clear, peak); + } + + dl->PopClipRect(); +} + +// ============================================================================ +// Specular Glare — polished-surface highlights (obsidian / glass look) +// ============================================================================ + +void ThemeEffects::drawSpecularGlare(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || !specular_glare_.enabled || reduced_transparency_) return; + + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w <= 20 || h <= 10) return; // skip tiny panels + + float minDim = std::min(w, h); + float glareR = minDim * specular_glare_.radius; + + int cR = specular_glare_.color & 0xFF; + int cG = (specular_glare_.color >> 8) & 0xFF; + int cB = (specular_glare_.color >> 16) & 0xFF; + + // Per-panel seed from position — unique drift per panel + float seed = pMin.x * 0.0073f + pMin.y * 0.0137f; + + // Clip to panel with rounding inset + float cr = std::min(rounding, minDim * 0.5f) * 0.3f; + dl->PushClipRect(ImVec2(pMin.x + cr, pMin.y + cr), + ImVec2(pMax.x - cr, pMax.y - cr), true); + + for (int s = 0; s < specular_glare_.count; s++) { + float phaseSeed = seed + s * 3.14159265f; + + // Slow Lissajous drift — each spot follows a unique orbit + float freqX = 2.0f * 3.14159265f * specular_glare_.speed; + float freqY = freqX * 1.618f; // golden ratio offset → non-repeating path + float driftX = std::sin(time_ * freqX + phaseSeed) * 0.3f + 0.5f; + float driftY = std::cos(time_ * freqY + phaseSeed * 1.3f) * 0.25f + 0.4f; + + float cx = pMin.x + w * driftX; + float cy = pMin.y + h * driftY; + + // Concentric circles with Gaussian falloff for a soft, blurred glow. + // More rings = smoother gradient, more segments = rounder circles. + const int rings = 20; + for (int r = rings; r >= 1; r--) { + float frac = (float)r / (float)rings; // 1.0 → outer, 0.05 → innermost + float ringRadius = glareR * frac; + // Gaussian falloff: exp(-frac² * 4) — soft blur-like appearance + float alphaMul = std::exp(-frac * frac * 4.0f); + int a = (int)(specular_glare_.intensity * alphaMul * bgOpacity_ * 255.0f); + if (a <= 0) continue; + + dl->AddCircleFilled(ImVec2(cx, cy), ringRadius, + IM_COL32(cR, cG, cB, a), 32); + } + } + + dl->PopClipRect(); +} + +// ============================================================================ +// Positional Hue Tinting +// ============================================================================ + +ImU32 ThemeEffects::getPositionalTint(float screenY) const { + if (!enabled_ || !positional_hue_.enabled) return IM_COL32(255,255,255,255); + + float t = 0.5f; + float range = vpMaxY_ - vpMinY_; + if (range > 0) { + t = std::clamp((screenY - vpMinY_) / range, 0.0f, 1.0f); + } + + // Lerp between top and bottom colors + float r = positional_hue_.topColor.x + t * (positional_hue_.bottomColor.x - positional_hue_.topColor.x); + float g = positional_hue_.topColor.y + t * (positional_hue_.bottomColor.y - positional_hue_.topColor.y); + float b = positional_hue_.topColor.z + t * (positional_hue_.bottomColor.z - positional_hue_.topColor.z); + + return IM_COL32((int)(r * 255), (int)(g * 255), (int)(b * 255), 255); +} + +ImU32 ThemeEffects::tintByPosition(ImU32 baseColor, float screenY) const { + if (!enabled_ || !positional_hue_.enabled || positional_hue_.strength <= 0.0f) return baseColor; + + ImU32 tint = getPositionalTint(screenY); + float s = positional_hue_.strength; + float inv = 1.0f - s; + + int bR = baseColor & 0xFF; + int bG = (baseColor >> 8) & 0xFF; + int bB = (baseColor >> 16) & 0xFF; + int bA = (baseColor >> 24) & 0xFF; + + int tR = tint & 0xFF; + int tG = (tint >> 8) & 0xFF; + int tB = (tint >> 16) & 0xFF; + + int r = (int)(bR * inv + tR * s); + int g = (int)(bG * inv + tG * s); + int b = (int)(bB * inv + tB * s); + + return IM_COL32(r, g, b, bA); +} + +// ============================================================================ +// Glow Pulse +// ============================================================================ + +void ThemeEffects::drawGlowPulse(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || !glow_pulse_.enabled) return; + + // Sinusoidal oscillation + float phase = std::sin(time_ * glow_pulse_.speed * 2.0f * 3.14159265f) * 0.5f + 0.5f; + float alpha = glow_pulse_.minAlpha + phase * (glow_pulse_.maxAlpha - glow_pulse_.minAlpha); + if (alpha <= 0.001f) return; + + int a = std::clamp((int)(alpha * bgOpacity_ * 255.0f), 0, 255); + int cR = glow_pulse_.color & 0xFF; + int cG = (glow_pulse_.color >> 8) & 0xFF; + int cB = (glow_pulse_.color >> 16) & 0xFF; + + // Border-only glow: concentric outlines with smooth Gaussian falloff. + // Use many fine sub-rings (4× the pixel radius) to avoid visible + // stepping as the overall alpha pulses. + float maxExpand = glow_pulse_.radius; + int rings = std::max(4, (int)(maxExpand * 4.0f)); + for (int i = 1; i <= rings; i++) { + float expand = maxExpand * (float)i / (float)rings; + float frac = (float)i / (float)rings; // 0→1 from inner to outer + // Gaussian-like falloff: smooth and continuous + float falloff = std::exp(-frac * frac * 3.0f); + int ringAlpha = (int)(a * falloff); + if (ringAlpha <= 0) continue; + + float thickness = std::max(0.5f, 1.5f * (1.0f - frac)); + dl->AddRect( + ImVec2(pMin.x - expand, pMin.y - expand), + ImVec2(pMax.x + expand, pMax.y + expand), + IM_COL32(cR, cG, cB, ringAlpha), + rounding + expand * 0.5f, 0, thickness); + } +} + +// ============================================================================ +// Gradient Border Shift — border color oscillates between two gem colors +// ============================================================================ + +void ThemeEffects::drawGradientBorderShift(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || !gradient_border_.enabled) return; + + // Smooth sinusoidal oscillation between color A and color B + float phase = std::sin(time_ * gradient_border_.speed * 2.0f * 3.14159265f) * 0.5f + 0.5f; + + // Extract RGBA from both colors and lerp + int aR = gradient_border_.colorA & 0xFF; + int aG = (gradient_border_.colorA >> 8) & 0xFF; + int aB = (gradient_border_.colorA >> 16) & 0xFF; + int bR = gradient_border_.colorB & 0xFF; + int bG = (gradient_border_.colorB >> 8) & 0xFF; + int bB = (gradient_border_.colorB >> 16) & 0xFF; + + int r = aR + (int)((bR - aR) * phase); + int g = aG + (int)((bG - aG) * phase); + int b = aB + (int)((bB - aB) * phase); + int a = std::clamp((int)(gradient_border_.alpha * bgOpacity_ * 255.0f), 0, 255); + + // Draw the shifting border + dl->AddRect(pMin, pMax, IM_COL32(r, g, b, a), + rounding, 0, gradient_border_.thickness); + + // Subtle outer glow ring at lower alpha for depth + float expand = gradient_border_.thickness; + int glowA = a / 3; + if (glowA > 0) { + dl->AddRect( + ImVec2(pMin.x - expand, pMin.y - expand), + ImVec2(pMax.x + expand, pMax.y + expand), + IM_COL32(r, g, b, glowA), + rounding + expand * 0.5f, 0, 1.0f); + } +} + +// ============================================================================ +// Edge Trace — a bright segment that traces the border perimeter +// ============================================================================ + +ImVec2 ThemeEffects::perimeterPoint(ImVec2 pMin, ImVec2 pMax, float t, float rounding) const { + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w <= 0 || h <= 0) return pMin; + + // Clamp rounding to half of the smaller dimension + float r = std::min(rounding, std::min(w, h) * 0.5f); + if (r < 0.5f) r = 0.0f; // treat tiny rounding as none + + t = std::fmod(t, 1.0f); + if (t < 0.0f) t += 1.0f; + + if (r <= 0.0f) { + // Original rectangular path + float perimeter = 2.0f * (w + h); + float d = t * perimeter; + if (d < w) return ImVec2(pMin.x + d, pMin.y); + else if (d < w + h) return ImVec2(pMax.x, pMin.y + (d - w)); + else if (d < 2*w+h) return ImVec2(pMax.x - (d - w - h), pMax.y); + else return ImVec2(pMin.x, pMax.y - (d - 2*w - h)); + } + + // Rounded rect perimeter: + // Segments (clockwise starting from top-left of top edge): + // 1. Top edge: (x+r, y) → (x+w-r, y) len = w - 2r + // 2. TR arc: center (x+w-r, y+r) -90° → 0° len = πr/2 + // 3. Right edge: (x+w, y+r) → (x+w, y+h-r) len = h - 2r + // 4. BR arc: center (x+w-r, y+h-r) 0° → 90° len = πr/2 + // 5. Bottom edge: (x+w-r, y+h) → (x+r, y+h) len = w - 2r + // 6. BL arc: center (x+r, y+h-r) 90° → 180° len = πr/2 + // 7. Left edge: (x, y+h-r) → (x, y+r) len = h - 2r + // 8. TL arc: center (x+r, y+r) 180° → 270° len = πr/2 + const float PI = 3.14159265f; + float arcLen = PI * r * 0.5f; + float edgeW = w - 2.0f * r; + float edgeH = h - 2.0f * r; + float perimeter = 2.0f * edgeW + 2.0f * edgeH + 4.0f * arcLen; + float d = t * perimeter; + + // Segment boundaries (cumulative) + float s1 = edgeW; // top edge + float s2 = s1 + arcLen; // TR arc + float s3 = s2 + edgeH; // right edge + float s4 = s3 + arcLen; // BR arc + float s5 = s4 + edgeW; // bottom edge + float s6 = s5 + arcLen; // BL arc + float s7 = s6 + edgeH; // left edge + // s8 = s7 + arcLen = perimeter // TL arc + + if (d < s1) { + // Top edge + return ImVec2(pMin.x + r + d, pMin.y); + } else if (d < s2) { + // TR arc: center (pMax.x - r, pMin.y + r), angle -90° to 0° + float frac = (d - s1) / arcLen; + float angle = -PI * 0.5f + frac * PI * 0.5f; + return ImVec2(pMax.x - r + r * std::cos(angle), + pMin.y + r + r * std::sin(angle)); + } else if (d < s3) { + // Right edge + return ImVec2(pMax.x, pMin.y + r + (d - s2)); + } else if (d < s4) { + // BR arc: center (pMax.x - r, pMax.y - r), angle 0° to 90° + float frac = (d - s3) / arcLen; + float angle = frac * PI * 0.5f; + return ImVec2(pMax.x - r + r * std::cos(angle), + pMax.y - r + r * std::sin(angle)); + } else if (d < s5) { + // Bottom edge (right to left) + return ImVec2(pMax.x - r - (d - s4), pMax.y); + } else if (d < s6) { + // BL arc: center (pMin.x + r, pMax.y - r), angle 90° to 180° + float frac = (d - s5) / arcLen; + float angle = PI * 0.5f + frac * PI * 0.5f; + return ImVec2(pMin.x + r + r * std::cos(angle), + pMax.y - r + r * std::sin(angle)); + } else if (d < s7) { + // Left edge (bottom to top) + return ImVec2(pMin.x, pMax.y - r - (d - s6)); + } else { + // TL arc: center (pMin.x + r, pMin.y + r), angle 180° to 270° + float frac = (d - s7) / arcLen; + float angle = PI + frac * PI * 0.5f; + return ImVec2(pMin.x + r + r * std::cos(angle), + pMin.y + r + r * std::sin(angle)); + } +} + +void ThemeEffects::drawEdgeTrace(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || !edge_trace_.enabled) return; + + float headPos = std::fmod(time_ * edge_trace_.speed, 1.0f); + float traceLen = edge_trace_.length; + + int cR = edge_trace_.color & 0xFF; + int cG = (edge_trace_.color >> 8) & 0xFF; + int cB = (edge_trace_.color >> 16) & 0xFF; + + // Draw the trace as connected line segments with fading alpha. + // Use enough segments to make curved corners smooth. + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + float r = std::min(rounding, std::min(w, h) * 0.5f); + float cornerSegs = (r > 0.5f) ? std::ceil(r * 1.5f) : 0.0f; + // Scale by trace length — we only draw a fraction of the perimeter + int segments = std::max(24, (int)((4 * cornerSegs + 2 * (w + h) / 8.0f) * traceLen + 8)); + segments = std::min(segments, 128); + + ImVec2 prev = perimeterPoint(pMin, pMax, headPos, rounding); + for (int i = 1; i <= segments; i++) { + float frac = (float)i / (float)segments; // 0→1 from head to tail + float pos = headPos - frac * traceLen; + if (pos < 0.0f) pos += 1.0f; + + ImVec2 pt = perimeterPoint(pMin, pMax, pos, rounding); + + // Alpha fades from head (1.0) to tail (0.0), with a cubic falloff + float aFrac = 1.0f - frac; + aFrac = aFrac * aFrac; // quadratic falloff for natural fade + int a = (int)(edge_trace_.alpha * aFrac * bgOpacity_ * 255.0f); + if (a > 0) { + dl->AddLine(prev, pt, IM_COL32(cR, cG, cB, a), edge_trace_.thickness); + } + prev = pt; + } + + // Bright dot at the head + int headA = (int)(edge_trace_.alpha * bgOpacity_ * 255.0f); + ImVec2 headPt = perimeterPoint(pMin, pMax, headPos, rounding); + dl->AddCircleFilled(headPt, edge_trace_.thickness * 1.5f, + IM_COL32(cR, cG, cB, headA), 8); +} + +// ============================================================================ +// Ember Rise — fire particles that drift upward from the element +// ============================================================================ + +void ThemeEffects::drawEmberRise(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax) const { + if (!enabled_ || !ember_rise_.enabled) return; + + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w <= 0 || h <= 0) return; + + int cR = ember_rise_.color & 0xFF; + int cG = (ember_rise_.color >> 8) & 0xFF; + int cB = (ember_rise_.color >> 16) & 0xFF; + + for (int i = 0; i < ember_rise_.count; i++) { + // Golden-ratio spacing gives evenly distributed phases + float phase = std::fmod(time_ * ember_rise_.speed + i * 0.618033988f, 1.0f); + + // Deterministic pseudo-random x position per particle + // Simple hash: sin of large prime multiples + float xHash = std::sin((float)(i + 1) * 127.1f) * 0.5f + 0.5f; + float xDrift = std::sin(time_ * 0.7f + i * 2.4f) * 4.0f; // gentle sway + + float x = pMin.x + w * xHash + xDrift; + float y = pMax.y - phase * (h + 8.0f); // rise from bottom past top + + // Fade in at bottom (phase 0→0.2), full in middle, fade out at top (0.7→1.0) + float aFrac; + if (phase < 0.15f) { + aFrac = phase / 0.15f; + } else if (phase > 0.7f) { + aFrac = (1.0f - phase) / 0.3f; + } else { + aFrac = 1.0f; + } + + // Size decreases as particle rises (embers shrink) + float size = ember_rise_.particleSize * (1.0f - phase * 0.4f); + + int a = (int)(ember_rise_.alpha * aFrac * bgOpacity_ * 255.0f); + + // Warm core + dl->AddCircleFilled(ImVec2(x, y), size, + IM_COL32(cR, cG, cB, a), 6); + // Softer outer glow + if (a > 30) { + dl->AddCircleFilled(ImVec2(x, y), size * 2.0f, + IM_COL32(cR, cG, cB, a / 4), 6); + } + } +} + +// ============================================================================ +// Viewport-wide ambient ember particles (fire theme atmosphere) +// ============================================================================ + +void ThemeEffects::drawViewportEmbers(ImDrawList* dl) const { + if (!enabled_ || !ember_rise_.enabled) return; + + ImGuiViewport* vp = ImGui::GetMainViewport(); + float vpW = vp->WorkSize.x; + float vpH = vp->WorkSize.y; + float vpX = vp->WorkPos.x; + float vpY = vp->WorkPos.y; + if (vpW <= 0 || vpH <= 0) return; + + int cR = ember_rise_.color & 0xFF; + int cG = (ember_rise_.color >> 8) & 0xFF; + int cB = (ember_rise_.color >> 16) & 0xFF; + + // Viewport embers: more particles, spread across the whole screen + int vpCount = ember_rise_.count * 3; + float vpAlpha = ember_rise_.alpha * 0.4f * bgOpacity_; // softer than panel embers + + for (int i = 0; i < vpCount; i++) { + float phase = std::fmod(time_ * ember_rise_.speed * 0.6f + i * 0.618033988f, 1.0f); + + // Deterministic x position spread across viewport + float xHash = std::sin((float)(i + 1) * 127.1f) * 43758.5453f; + xHash = xHash - (int)xHash; // fractional part + if (xHash < 0) xHash += 1.0f; + float xDrift = std::sin(time_ * 0.5f + i * 1.7f) * 8.0f; + + float x = vpX + vpW * xHash + xDrift; + float y = vpY + vpH * (1.0f - phase); // rise from bottom to top + + // Fade in/out + float aFrac; + if (phase < 0.1f) aFrac = phase / 0.1f; + else if (phase > 0.75f) aFrac = (1.0f - phase) / 0.25f; + else aFrac = 1.0f; + + float size = ember_rise_.particleSize * 0.8f * (1.0f - phase * 0.3f); + int a = (int)(vpAlpha * aFrac * 255.0f); + if (a <= 0) continue; + + dl->AddCircleFilled(ImVec2(x, y), size, + IM_COL32(cR, cG, cB, a), 6); + if (a > 20) { + dl->AddCircleFilled(ImVec2(x, y), size * 2.5f, + IM_COL32(cR, cG, cB, a / 5), 6); + } + } +} + +// ============================================================================ +// Sandstorm — wind-driven sand/dust particles blowing across the viewport +// ============================================================================ + +void ThemeEffects::drawSandstorm(ImDrawList* dl) const { + if (!enabled_ || !sandstorm_.enabled || effects::isLowSpecMode()) return; + + ImGuiViewport* vp = ImGui::GetMainViewport(); + float vpW = vp->WorkSize.x; + float vpH = vp->WorkSize.y; + float vpX = vp->WorkPos.x; + float vpY = vp->WorkPos.y; + if (vpW <= 0 || vpH <= 0) return; + + int cR = sandstorm_.color & 0xFF; + int cG = (sandstorm_.color >> 8) & 0xFF; + int cB = (sandstorm_.color >> 16) & 0xFF; + + // Wind direction vector from angle (degrees from horizontal) + float windRad = sandstorm_.windAngle * 3.14159265f / 180.0f; + float windDx = std::cos(windRad); // horizontal component + float windDy = std::sin(windRad); // vertical component (positive = downward) + + // Global gust modulation: smoothly varies wind speed + float gust = 1.0f + sandstorm_.gustStrength * + std::sin(time_ * sandstorm_.gustSpeed * 2.0f * 3.14159265f); + + // Diagonal traversal distance (how far a particle travels across viewport) + float traversal = vpW + vpH * std::abs(windDy / std::max(0.01f, windDx)); + + for (int i = 0; i < sandstorm_.count; i++) { + // Deterministic pseudo-random properties per particle + float hash1 = std::sin((float)(i + 1) * 127.1f) * 43758.5453f; + hash1 = hash1 - (int)hash1; + if (hash1 < 0) hash1 += 1.0f; + + float hash2 = std::sin((float)(i + 1) * 269.5f) * 27183.3291f; + hash2 = hash2 - (int)hash2; + if (hash2 < 0) hash2 += 1.0f; + + float hash3 = std::sin((float)(i + 1) * 419.3f) * 15731.7927f; + hash3 = hash3 - (int)hash3; + if (hash3 < 0) hash3 += 1.0f; + + // Per-particle speed variation (0.5x to 1.5x base speed) + float speedMul = 0.5f + hash1; + // Per-particle size variation (0.4x to 1.6x base) + float size = sandstorm_.particleSize * (0.4f + hash2 * 1.2f); + // Per-particle alpha variation (0.5x to 1.0x) + float alphaMul = 0.5f + hash3 * 0.5f; + + // Phase: horizontal progress across viewport (0→1) + // Different particles have staggered starts via golden ratio + float phase = std::fmod( + time_ * sandstorm_.speed * speedMul * gust + i * 0.618033988f, 1.0f); + + // Y position: distributed across viewport with turbulent drift + float yBase = vpY + vpH * hash2; + float yTurb = std::sin(time_ * 0.8f + i * 3.7f) * vpH * 0.04f; + // Additional gust-correlated vertical shift + float yGust = std::sin(time_ * sandstorm_.gustSpeed * 6.28318f + i * 1.3f) * vpH * 0.02f; + + // Position: particle blows right-to-left with downward drift + float x = vpX + vpW * (1.0f - phase) + phase * traversal * (1.0f - windDx) * 0.1f; + float y = yBase + yTurb + yGust + phase * vpH * windDy * 0.3f; + + // Wrap Y if it goes out of bounds + if (y < vpY) y += vpH; + if (y > vpY + vpH) y -= vpH; + + // Fade in at entry edge (phase 0→0.1), fade out at exit (0.85→1.0) + float aFrac; + if (phase < 0.1f) aFrac = phase / 0.1f; + else if (phase > 0.85f) aFrac = (1.0f - phase) / 0.15f; + else aFrac = 1.0f; + + int a = (int)(sandstorm_.alpha * alphaMul * aFrac * bgOpacity_ * 255.0f); + if (a <= 0) continue; + + // Fast particles draw as motion-blurred streaks + float particleSpeed = sandstorm_.speed * speedMul * gust; + float streakLen = sandstorm_.streakLength * particleSpeed * size; + + if (streakLen > size * 1.5f) { + // Draw as a short line (motion streak) + float sx = -windDx * streakLen; + float sy = -windDy * streakLen * 0.3f; + dl->AddLine( + ImVec2(x, y), + ImVec2(x + sx, y + sy), + IM_COL32(cR, cG, cB, a), + size * 0.7f); + // Bright head dot + dl->AddCircleFilled(ImVec2(x, y), size * 0.5f, + IM_COL32(cR, cG, cB, std::min(255, a * 3 / 2)), 5); + } else { + // Small/slow particles: simple circle + dl->AddCircleFilled(ImVec2(x, y), size, + IM_COL32(cR, cG, cB, a), 6); + } + + // Occasional larger dust puff (every ~8th particle, double size, half alpha) + if (i % 8 == 0 && a > 15) { + dl->AddCircleFilled(ImVec2(x, y), size * 2.5f, + IM_COL32(cR, cG, cB, a / 4), 8); + } + } +} + +// ============================================================================ +// Panel-level effects (applied to every glass panel via DrawGlassPanel) +// ============================================================================ + +void ThemeEffects::drawPanelEffects(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const { + if (!enabled_ || effects::isLowSpecMode()) return; + + // Edge trace on panels — use position-based phase offset so each + // panel's tracer is at a different position around the border + if (edge_trace_.enabled) { + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w > 80 && h > 40) { // skip small panels + // Generate a consistent phase offset from panel position + float posKey = (pMin.x * 0.0073f + pMin.y * 0.0137f); + posKey = posKey - (int)posKey; // fractional 0..1 + if (posKey < 0) posKey += 1.0f; + + float headPos = std::fmod(time_ * edge_trace_.speed + posKey, 1.0f); + float traceLen = edge_trace_.length; + + int cR = edge_trace_.color & 0xFF; + int cG = (edge_trace_.color >> 8) & 0xFF; + int cB = (edge_trace_.color >> 16) & 0xFF; + + // Panel edge trace is subtler than sidebar — 60% alpha + float panelAlpha = edge_trace_.alpha * 0.6f * bgOpacity_; + + const int segments = 10; + ImVec2 prev = perimeterPoint(pMin, pMax, headPos, rounding); + for (int i = 1; i <= segments; i++) { + float frac = (float)i / (float)segments; + float pos = headPos - frac * traceLen; + if (pos < 0.0f) pos += 1.0f; + + ImVec2 pt = perimeterPoint(pMin, pMax, pos, rounding); + float aFrac = 1.0f - frac; + aFrac = aFrac * aFrac; + int a = (int)(panelAlpha * aFrac * 255.0f); + if (a > 0) { + dl->AddLine(prev, pt, IM_COL32(cR, cG, cB, a), + edge_trace_.thickness * 0.8f); + } + prev = pt; + } + + // Head dot + int headA = (int)(panelAlpha * 255.0f); + ImVec2 headPt = perimeterPoint(pMin, pMax, headPos, rounding); + dl->AddCircleFilled(headPt, edge_trace_.thickness * 1.2f, + IM_COL32(cR, cG, cB, headA), 6); + } + } + + // Ember rise on panels — sparse embers from larger panels only + if (ember_rise_.enabled) { + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + if (w > 120 && h > 60) { // only on large panels + // Fewer particles per panel (scale by area relative to viewport) + int panelCount = std::max(2, ember_rise_.count / 3); + float panelAlpha = ember_rise_.alpha * 0.5f * bgOpacity_; + + int cR = ember_rise_.color & 0xFF; + int cG = (ember_rise_.color >> 8) & 0xFF; + int cB = (ember_rise_.color >> 16) & 0xFF; + + // Use panel position as seed for unique particle distribution + float seed = pMin.x * 0.013f + pMin.y * 0.031f; + + dl->PushClipRect( + ImVec2(pMin.x - 2, pMin.y - 4), + ImVec2(pMax.x + 2, pMax.y + 2), true); + + for (int i = 0; i < panelCount; i++) { + float phase = std::fmod(time_ * ember_rise_.speed + i * 0.618033988f + seed, 1.0f); + float xHash = std::sin((float)(i + 1) * 127.1f + seed * 100.0f) * 0.5f + 0.5f; + float xDrift = std::sin(time_ * 0.7f + i * 2.4f + seed) * 3.0f; + + float x = pMin.x + w * xHash + xDrift; + float y = pMax.y - phase * (h + 6.0f); + + float aFrac; + if (phase < 0.15f) aFrac = phase / 0.15f; + else if (phase > 0.7f) aFrac = (1.0f - phase) / 0.3f; + else aFrac = 1.0f; + + float size = ember_rise_.particleSize * 0.8f * (1.0f - phase * 0.4f); + int a = (int)(panelAlpha * aFrac * 255.0f); + if (a <= 0) continue; + + dl->AddCircleFilled(ImVec2(x, y), size, + IM_COL32(cR, cG, cB, a), 6); + } + + dl->PopClipRect(); + } + } +} + +// ============================================================================ +// Viewport Overlay — shader-like full-screen color wash + vignette +// ============================================================================ + +void ThemeEffects::drawViewportOverlay(ImDrawList* dl) const { + if (!enabled_ || effects::isLowSpecMode()) return; + + ImGuiViewport* vp = ImGui::GetMainViewport(); + ImVec2 vpPos = vp->WorkPos; + ImVec2 vpSize = vp->WorkSize; + if (vpSize.x <= 0 || vpSize.y <= 0) return; + + ImVec2 vpMax = ImVec2(vpPos.x + vpSize.x, vpPos.y + vpSize.y); + + // === Color Wash: full-screen 4-corner animated gradient === + if (viewport_overlay_.colorWashEnabled) { + ImU32 corners[4] = { + viewport_overlay_.cornerTL, + viewport_overlay_.cornerTR, + viewport_overlay_.cornerBR, + viewport_overlay_.cornerBL + }; + + // Rotation: smoothly shift which color appears at which corner + if (viewport_overlay_.washRotateSpeed > 0.001f) { + float shift = std::fmod(time_ * viewport_overlay_.washRotateSpeed, 1.0f); + ImU32 originals[4] = { corners[0], corners[1], corners[2], corners[3] }; + + for (int c = 0; c < 4; c++) { + float pos = std::fmod(shift + c * 0.25f, 1.0f); + float segment = pos * 4.0f; + int idx = ((int)segment) % 4; + float frac = segment - (int)segment; + int next = (idx + 1) % 4; + + int r1 = originals[idx] & 0xFF, g1 = (originals[idx]>>8)&0xFF, b1 = (originals[idx]>>16)&0xFF; + int r2 = originals[next] & 0xFF, g2 = (originals[next]>>8)&0xFF, b2 = (originals[next]>>16)&0xFF; + corners[c] = IM_COL32( + r1 + (int)(frac * (r2 - r1)), + g1 + (int)(frac * (g2 - g1)), + b1 + (int)(frac * (b2 - b1)), + 255); + } + } + + // Calculate final alpha — keep it constant to avoid integer + // quantisation stepping at low values (0.04–0.12 → only 10–30 + // integer levels). Breathing is achieved by modulating the RGB + // colour intensity instead, which has far more resolution. + float alpha = viewport_overlay_.washAlpha * bgOpacity_; + int a = std::clamp((int)(alpha * 255.0f + 0.5f), 0, 255); + if (a > 0) { + // Smooth breathing via colour modulation (not alpha) + float colorMul = 1.0f; + if (viewport_overlay_.washPulseSpeed > 0.001f) { + float pulse = std::sin(time_ * viewport_overlay_.washPulseSpeed * 2.0f * 3.14159265f) * 0.5f + 0.5f; + colorMul = 1.0f - viewport_overlay_.washPulseDepth * (1.0f - pulse); + } + + // Apply colour modulation to each corner while keeping alpha constant + auto modCorner = [&](ImU32 c) -> ImU32 { + int r = std::clamp((int)((c & 0xFF) * colorMul + 0.5f), 0, 255); + int g = std::clamp((int)(((c >> 8) & 0xFF) * colorMul + 0.5f), 0, 255); + int b = std::clamp((int)(((c >> 16) & 0xFF) * colorMul + 0.5f), 0, 255); + return IM_COL32(r, g, b, a); + }; + + ImU32 c0 = modCorner(corners[0]); + ImU32 c1 = modCorner(corners[1]); + ImU32 c2 = modCorner(corners[2]); + ImU32 c3 = modCorner(corners[3]); + + dl->AddRectFilledMultiColor(vpPos, vpMax, c0, c1, c2, c3); + } + } + + // === Vignette: edge darkening/tinting (4 gradient strips) === + // Overlapping strips naturally darken corners more than edges — cinematic look + if (viewport_overlay_.vignetteEnabled) { + int cR = viewport_overlay_.vignetteColor & 0xFF; + int cG = (viewport_overlay_.vignetteColor >> 8) & 0xFF; + int cB = (viewport_overlay_.vignetteColor >> 16) & 0xFF; + int maxA = std::clamp((int)(viewport_overlay_.vignetteAlpha * bgOpacity_ * 255.0f), 0, 255); + + if (maxA > 0) { + ImU32 edgeCol = IM_COL32(cR, cG, cB, maxA); + ImU32 clearCol = IM_COL32(cR, cG, cB, 0); + + float fadeW = vpSize.x * viewport_overlay_.vignetteRadius; + float fadeH = vpSize.y * viewport_overlay_.vignetteRadius; + + // Top strip: dark at top edge, transparent at fade boundary + dl->AddRectFilledMultiColor( + vpPos, + ImVec2(vpMax.x, vpPos.y + fadeH), + edgeCol, edgeCol, clearCol, clearCol); + + // Bottom strip + dl->AddRectFilledMultiColor( + ImVec2(vpPos.x, vpMax.y - fadeH), + vpMax, + clearCol, clearCol, edgeCol, edgeCol); + + // Left strip + dl->AddRectFilledMultiColor( + vpPos, + ImVec2(vpPos.x + fadeW, vpMax.y), + edgeCol, clearCol, clearCol, edgeCol); + + // Right strip + dl->AddRectFilledMultiColor( + ImVec2(vpMax.x - fadeW, vpPos.y), + vpMax, + clearCol, edgeCol, edgeCol, clearCol); + } + } +} + +// ============================================================================ +// Hex color parsing helpers +// ============================================================================ + +ImU32 ThemeEffects::parseHexColor(const std::string& hex, ImU32 fallback) { + if (hex.empty() || hex[0] != '#') return fallback; + unsigned int val = 0; + if (hex.size() == 7) { // #RRGGBB + val = (unsigned int)strtoul(hex.c_str() + 1, nullptr, 16); + int r = (val >> 16) & 0xFF; + int g = (val >> 8) & 0xFF; + int b = val & 0xFF; + return IM_COL32(r, g, b, 255); + } else if (hex.size() == 9) { // #RRGGBBAA + val = (unsigned int)strtoul(hex.c_str() + 1, nullptr, 16); + int r = (val >> 24) & 0xFF; + int g = (val >> 16) & 0xFF; + int b = (val >> 8) & 0xFF; + int a = val & 0xFF; + return IM_COL32(r, g, b, a); + } + return fallback; +} + +ImVec4 ThemeEffects::parseHexColorVec4(const std::string& hex, ImVec4 fallback) { + ImU32 c = parseHexColor(hex, 0); + if (c == 0 && hex != "#000000") return fallback; + float r = (c & 0xFF) / 255.0f; + float g = ((c >> 8) & 0xFF) / 255.0f; + float b = ((c >> 16) & 0xFF) / 255.0f; + float a = ((c >> 24) & 0xFF) / 255.0f; + return ImVec4(r, g, b, a); +} + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/effects/theme_effects.h b/src/ui/effects/theme_effects.h new file mode 100644 index 0000000..7bd6b68 --- /dev/null +++ b/src/ui/effects/theme_effects.h @@ -0,0 +1,244 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace effects { + +/** + * @brief Per-theme visual effects system. + * + * Draws animated accents (hue-cycling, rainbow borders, shimmer sweeps, + * glow pulses, positional tinting) driven entirely by TOML theme config. + * All effects use ImDrawList primitives — no shaders or texture uploads. + */ +class ThemeEffects { +public: + static ThemeEffects& instance(); + + /// Called once per frame (timing updates) + void beginFrame(); + + /// Master toggle (from settings) + void setEnabled(bool enabled) { enabled_ = enabled; } + bool isEnabled() const { return enabled_; } + + /// Background opacity (from window opacity slider). Multiplies + /// all effect alphas so they fade with the backdrop while UI stays opaque. + void setBackgroundOpacity(float o) { bgOpacity_ = std::max(0.0f, std::min(1.0f, o)); } + float backgroundOpacity() const { return bgOpacity_; } + + /// Reduced transparency suppresses shimmer + rainbow border + void setReducedTransparency(bool rt) { reduced_transparency_ = rt; } + bool isReducedTransparency() const { return reduced_transparency_; } + + /// Reload [effects] config from the active UISchema overlay + void loadFromTheme(); + + // === Drawing APIs === + + /// Get the current hue-cycled accent color (optionally phase-shifted) + ImU32 getAccentColor(float phaseOffset = 0.0f) const; + + /// Draw rainbow gradient border around a rect (for glass panels) + void drawRainbowBorder(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding, float thickness) const; + + /// Draw shimmer sweep over a rect + void drawShimmer(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + /// Get positional hue tint for a given screen Y + ImU32 getPositionalTint(float screenY) const; + + /// Tint an existing color by positional hue + ImU32 tintByPosition(ImU32 baseColor, float screenY) const; + + /// Draw glow pulse behind a rect (for active elements) + void drawGlowPulse(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + /// Draw a light that traces along the border perimeter + void drawEdgeTrace(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + /// Draw a border that shifts between two colors over time (gem-like) + void drawGradientBorderShift(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + /// Draw ember particles that rise from an element (fire theme) + void drawEmberRise(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax) const; + + /// Draw specular glare highlights on a panel (polished surface look) + void drawSpecularGlare(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + /// Draw viewport-wide ambient ember particles (fire theme atmosphere) + void drawViewportEmbers(ImDrawList* dl) const; + + /// Draw viewport-wide sandstorm particles (wind-driven diagonal sand/dust) + void drawSandstorm(ImDrawList* dl) const; + + /// Draw shader-like viewport overlay (color wash + vignette post-processing) + void drawViewportOverlay(ImDrawList* dl) const; + + /// Draw all applicable panel effects (edge trace + ember rise on glass panels) + /// phaseKey provides per-panel phase diversity based on panel position + void drawPanelEffects(ImDrawList* dl, ImVec2 pMin, ImVec2 pMax, + float rounding) const; + + // === Query which effects are available === + bool hasRainbowBorder() const { return enabled_ && !reduced_transparency_ && rainbow_border_.enabled; } + bool hasShimmer() const { return enabled_ && !reduced_transparency_ && shimmer_.enabled; } + bool hasGlowPulse() const { return enabled_ && glow_pulse_.enabled; } + bool hasHueCycle() const { return enabled_ && hue_cycle_.enabled; } + bool hasPositionalHue() const { return enabled_ && positional_hue_.enabled; } + bool hasEdgeTrace() const { return enabled_ && edge_trace_.enabled; } bool hasGradientBorder() const { return enabled_ && gradient_border_.enabled; } bool hasEmberRise() const { return enabled_ && ember_rise_.enabled; } + bool hasSpecularGlare() const { return enabled_ && !reduced_transparency_ && specular_glare_.enabled; } + bool hasSandstorm() const { return enabled_ && sandstorm_.enabled; } + bool hasViewportOverlay() const { return enabled_ && (viewport_overlay_.colorWashEnabled || viewport_overlay_.vignetteEnabled); } + + /// True when any time-dependent effect is active and needs continuous redraws + bool hasActiveAnimation() const { + if (!enabled_) return false; + return hue_cycle_.enabled || rainbow_border_.enabled || shimmer_.enabled + || glow_pulse_.enabled || edge_trace_.enabled || ember_rise_.enabled + || gradient_border_.enabled || specular_glare_.enabled || sandstorm_.enabled + || (viewport_overlay_.colorWashEnabled + && (viewport_overlay_.washRotateSpeed > 0.0f || viewport_overlay_.washPulseSpeed > 0.0f)); + } + +private: + ThemeEffects() = default; + + bool enabled_ = true; + bool reduced_transparency_ = false; + float time_ = 0.0f; + float bgOpacity_ = 1.0f; ///< window-opacity multiplier for effect alphas + + // Viewport bounds (set each frame) + float vpMinY_ = 0.0f; + float vpMaxY_ = 1.0f; + + // ---- Cached config from [effects] ---- + + struct HueCycleConfig { + bool enabled = false; + float speed = 0.1f, sat = 0.6f, val = 0.85f; + float range = 1.0f, offset = 0.0f; + } hue_cycle_; + + struct RainbowBorderConfig { + bool enabled = false; + float speed = 0.05f, alpha = 0.25f; + std::vector stops; + } rainbow_border_; + + struct ShimmerConfig { + bool enabled = false; + float speed = 0.12f, width = 80.0f, alpha = 0.06f, angle = 30.0f; + ImU32 color = IM_COL32(255,255,255,255); + } shimmer_; + + struct PositionalHueConfig { + bool enabled = false; + ImVec4 topColor{1,0.42f,0.62f,1}; + ImVec4 bottomColor{0.4f,0.91f,0.98f,1}; + float strength = 0.3f; + } positional_hue_; + + struct GlowPulseConfig { + bool enabled = false; + float speed = 2.0f, minAlpha = 0.0f, maxAlpha = 0.15f, radius = 4.0f; + ImU32 color = IM_COL32(255,255,255,255); + } glow_pulse_; + + struct EdgeTraceConfig { + bool enabled = false; + float speed = 0.3f; ///< full circuits per second + float length = 0.20f; ///< fraction of perimeter lit (tail length) + float thickness = 1.5f; ///< line thickness in pixels + float alpha = 0.6f; ///< peak alpha at head of trace + ImU32 color = IM_COL32(255,255,255,255); + } edge_trace_; + + struct EmberRiseConfig { + bool enabled = false; + int count = 8; ///< number of ember particles + float speed = 0.4f; ///< rise cycles per second + float particleSize = 1.5f;///< ember radius in pixels + float alpha = 0.5f; ///< peak alpha + ImU32 color = IM_COL32(255, 120, 20, 255); + } ember_rise_; + + struct GradientBorderConfig { + bool enabled = false; + float speed = 0.15f; ///< full color shift cycles per second + float thickness = 1.5f; ///< border line thickness in pixels + float alpha = 0.6f; ///< peak alpha + ImU32 colorA = IM_COL32(206, 147, 216, 255); ///< first color (amethyst) + ImU32 colorB = IM_COL32(26, 35, 126, 255); ///< second color (indigo) + } gradient_border_; + + struct SpecularGlareConfig { + bool enabled = false; + float speed = 0.02f; ///< drift speed (Lissajous orbit cycles/sec) + float intensity = 0.06f; ///< peak alpha at glare center + float radius = 0.5f; ///< glare radius as fraction of panel min-dim + int count = 2; ///< number of specular spots per panel + ImU32 color = IM_COL32(255, 255, 255, 255); + } specular_glare_; + + struct SandstormConfig { + bool enabled = false; + int count = 80; ///< number of sand particles + float speed = 0.35f; ///< base horizontal velocity (viewport widths/sec) + float windAngle = 15.0f; ///< degrees from horizontal (+ve = downward) + float particleSize = 1.5f; ///< base particle radius in pixels + float alpha = 0.35f; ///< peak particle alpha + float gustSpeed = 0.07f; ///< gust oscillation frequency (Hz) + float gustStrength = 0.4f; ///< speed variation from gusts (fraction) + float streakLength = 3.0f; ///< motion blur multiplier for fast particles + ImU32 color = IM_COL32(200, 160, 96, 255); + } sandstorm_; + + struct ViewportOverlayConfig { + // --- Color wash: full-screen 4-corner gradient overlay --- + bool colorWashEnabled = false; + ImU32 cornerTL = IM_COL32(255,100,0,255); ///< top-left corner color (RGB; alpha applied separately) + ImU32 cornerTR = IM_COL32(68,34,0,255); ///< top-right + ImU32 cornerBL = IM_COL32(68,17,0,255); ///< bottom-left + ImU32 cornerBR = IM_COL32(255,153,0,255); ///< bottom-right + float washAlpha = 0.05f; ///< overall wash intensity + float washRotateSpeed = 0.0f; ///< corner color rotation (turns/sec) + float washPulseSpeed = 0.0f; ///< alpha breathing speed (Hz) + float washPulseDepth = 0.0f; ///< pulse depth (0=none, 1=full fade) + + // --- Vignette: edge darkening/tinting --- + bool vignetteEnabled = false; + ImU32 vignetteColor = IM_COL32(0,0,0,255); ///< tint color at edges + float vignetteRadius = 0.35f; ///< fade zone as fraction of viewport + float vignetteAlpha = 0.30f; ///< max alpha at outer edge + } viewport_overlay_; + + /// Map a 0..1 fraction to a point on the rounded rect perimeter + ImVec2 perimeterPoint(ImVec2 pMin, ImVec2 pMax, float t, float rounding = 0.0f) const; + + // Helper: parse hex color string "#RRGGBB" or "#RRGGBBAA" to ImU32 + static ImU32 parseHexColor(const std::string& hex, ImU32 fallback = IM_COL32(255,255,255,255)); + static ImVec4 parseHexColorVec4(const std::string& hex, ImVec4 fallback = ImVec4(1,1,1,1)); + + // Helper: sample a rotating multi-stop gradient + ImU32 sampleGradient(float t) const; +}; + +} // namespace effects +} // namespace ui +} // namespace dragonx diff --git a/src/ui/layout.h b/src/ui/layout.h new file mode 100644 index 0000000..268393b --- /dev/null +++ b/src/ui/layout.h @@ -0,0 +1,543 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include "material/type.h" +#include "schema/ui_schema.h" +#include +#include +#include + +namespace dragonx { +namespace ui { + +// Import material helpers into ui namespace for convenience +using material::Type; +using material::OverlineLabel; +using material::OnSurface; +using material::OnSurfaceMedium; +using material::OnSurfaceDisabled; +using material::Primary; +using material::Secondary; +using material::Error; + +/** + * @brief Centralized layout configuration for consistent UI across all tabs + * + * Values are now driven by UISchema (JSON-configurable with hot-reload). + * The k* names are preserved as inline accessors for backward compatibility. + */ +namespace Layout { + +// ============================================================================ +// DPI Scaling (must be first — other accessors multiply by dpiScale()) +// ============================================================================ + +/** + * @brief Get the current display DPI scale factor. + * + * Returns the DPI scale set during typography initialization (e.g. 2.0 for + * 200 % Windows scaling). All pixel constants from TOML are in *logical* + * pixels and must be multiplied by this factor before being used as ImGui + * coordinates (which are physical pixels on Windows Per-Monitor DPI v2). + */ +inline float dpiScale() { + return dragonx::ui::material::Typography::instance().getDpiScale(); +} + +/** + * @brief Scale a logical pixel value by the current DPI factor. + * + * Convenience wrapper: Scale(16.0f) returns 16 * dpiScale. + */ +inline float Scale(float px) { + return px * dpiScale(); +} + +// ============================================================================ +// Font Sizes (in pixels, before DPI scaling) +// ============================================================================ +// These read from UISchema which loads layout from ui.toml. +// Editing res/themes/ui.toml will hot-reload these at runtime. + +inline float kFontH1() { return schema::UI().drawElement("fonts", "h1").sizeOr(24.0f); } +inline float kFontH2() { return schema::UI().drawElement("fonts", "h2").sizeOr(20.0f); } +inline float kFontH3() { return schema::UI().drawElement("fonts", "h3").sizeOr(18.0f); } +inline float kFontH4() { return schema::UI().drawElement("fonts", "h4").sizeOr(16.0f); } +inline float kFontH5() { return schema::UI().drawElement("fonts", "h5").sizeOr(14.0f); } +inline float kFontH6() { return schema::UI().drawElement("fonts", "h6").sizeOr(14.0f); } +inline float kFontSubtitle1() { return schema::UI().drawElement("fonts", "subtitle1").sizeOr(16.0f); } +inline float kFontSubtitle2() { return schema::UI().drawElement("fonts", "subtitle2").sizeOr(14.0f); } +inline float kFontBody1() { return schema::UI().drawElement("fonts", "body1").sizeOr(14.0f); } +inline float kFontBody2() { return schema::UI().drawElement("fonts", "body2").sizeOr(12.0f); } +inline float kFontButton() { return schema::UI().drawElement("fonts", "button").sizeOr(13.0f); } +inline float kFontButtonSm() { return schema::UI().drawElement("fonts", "button-sm").sizeOr(10.0f); } +inline float kFontButtonLg() { return schema::UI().drawElement("fonts", "button-lg").sizeOr(14.0f); } +inline float kFontCaption() { return schema::UI().drawElement("fonts", "caption").sizeOr(11.0f); } +inline float kFontOverline() { return schema::UI().drawElement("fonts", "overline").sizeOr(11.0f); } + +// Global font scale +inline float kFontScale() { return schema::UI().drawElement("fonts", "scale").sizeOr(1.0f); } + +// ============================================================================ +// Panel Sizing (responsive) +// ============================================================================ + +inline float kSummaryPanelMinWidth() { return schema::UI().drawElement("panels", "summary").getFloat("min-width", 280.0f) * dpiScale(); } +inline float kSummaryPanelMaxWidth() { return schema::UI().drawElement("panels", "summary").getFloat("max-width", 400.0f) * dpiScale(); } +inline float kSummaryPanelWidthRatio() { return schema::UI().drawElement("panels", "summary").getFloat("width-ratio", 0.32f); } +inline float kSummaryPanelMinHeight() { return schema::UI().drawElement("panels", "summary").getFloat("min-height", 200.0f) * dpiScale(); } +inline float kSummaryPanelMaxHeight() { return schema::UI().drawElement("panels", "summary").getFloat("max-height", 350.0f) * dpiScale(); } +inline float kSummaryPanelHeightRatio() { return schema::UI().drawElement("panels", "summary").getFloat("height-ratio", 0.8f); } + +inline float kSidePanelMinWidth() { return schema::UI().drawElement("panels", "side-panel").getFloat("min-width", 280.0f) * dpiScale(); } +inline float kSidePanelMaxWidth() { return schema::UI().drawElement("panels", "side-panel").getFloat("max-width", 450.0f) * dpiScale(); } +inline float kSidePanelWidthRatio() { return schema::UI().drawElement("panels", "side-panel").getFloat("width-ratio", 0.4f); } + +inline float kTableMinHeight() { return schema::UI().drawElement("panels", "table").getFloat("min-height", 150.0f) * dpiScale(); } +inline float kTableHeightRatio() { return schema::UI().drawElement("panels", "table").getFloat("height-ratio", 0.45f); } + +// ============================================================================ +// Spacing +// ============================================================================ + +inline float kSectionSpacing() { return schema::UI().drawElement("spacing", "section").sizeOr(16.0f) * dpiScale(); } +inline float kItemSpacing() { return schema::UI().drawElement("spacing", "item").sizeOr(8.0f) * dpiScale(); } +inline float kLabelValueGap() { return schema::UI().drawElement("spacing", "label-value").sizeOr(4.0f) * dpiScale(); } +inline float kSeparatorGap() { return schema::UI().drawElement("spacing", "separator").sizeOr(20.0f) * dpiScale(); } + +// ============================================================================ +// Layout Tier (responsive breakpoints) +// ============================================================================ + +/** + * @brief Three-tier layout system based on content area dimensions. + * + * Compact — narrow/short window: single-column, collapsed elements + * Normal — default layout + * Expanded — large window: extra spacing, optional extra columns + */ +enum class LayoutTier { Compact, Normal, Expanded }; + +/** + * @brief Determine the current layout tier from content area dimensions. + * Call after ImGui::BeginChild for the content area, or pass explicit avail. + */ +inline LayoutTier currentTier() { + const auto& S = schema::UI(); + float dp = dpiScale(); + float cw = S.drawElement("responsive", "compact-width").sizeOr(500.0f) * dp; + float ch = S.drawElement("responsive", "compact-height").sizeOr(450.0f) * dp; + float ew = S.drawElement("responsive", "expanded-width").sizeOr(900.0f) * dp; + float eh = S.drawElement("responsive", "expanded-height").sizeOr(750.0f) * dp; + ImVec2 avail = ImGui::GetContentRegionAvail(); + if (avail.x < cw || avail.y < ch) return LayoutTier::Compact; + if (avail.x > ew && avail.y > eh) return LayoutTier::Expanded; + return LayoutTier::Normal; +} + +inline LayoutTier currentTier(float availW, float availH) { + const auto& S = schema::UI(); + float dp = dpiScale(); + float cw = S.drawElement("responsive", "compact-width").sizeOr(500.0f) * dp; + float ch = S.drawElement("responsive", "compact-height").sizeOr(450.0f) * dp; + float ew = S.drawElement("responsive", "expanded-width").sizeOr(900.0f) * dp; + float eh = S.drawElement("responsive", "expanded-height").sizeOr(750.0f) * dp; + if (availW < cw || availH < ch) return LayoutTier::Compact; + if (availW > ew && availH > eh) return LayoutTier::Expanded; + return LayoutTier::Normal; +} + +// ============================================================================ +// Responsive Scale Factors +// ============================================================================ + +/** + * @brief Horizontal scale factor relative to reference width (default 1200px). + * + * The scale is decomposed into a *logical* portion (responsive to window + * size, clamped to the configured range) multiplied by the display DPI + * factor. This ensures a DPI transition produces the same logical scale + * while emitting physical-pixel results. + */ +inline float hScale(float availWidth) { + const auto& S = schema::UI(); + float dp = dpiScale(); + float rw = S.drawElement("responsive", "ref-width").sizeOr(1200.0f) * dp; + float minH = S.drawElement("responsive", "min-h-scale").sizeOr(0.5f); + float maxH = S.drawElement("responsive", "max-h-scale").sizeOr(1.5f); + // Clamp the logical (DPI-neutral) portion, then apply DPI. + float logical = std::clamp(availWidth / rw, minH, maxH); + return logical * dp; +} + +inline float hScale() { + return hScale(ImGui::GetContentRegionAvail().x); +} + +/** + * @brief Vertical scale factor relative to reference height (default 700px). + * + * Same decomposition as hScale — logical clamp × DPI. + */ +inline float vScale(float availHeight) { + const auto& S = schema::UI(); + float dp = dpiScale(); + float rh = S.drawElement("responsive", "ref-height").sizeOr(700.0f) * dp; + float minV = S.drawElement("responsive", "min-v-scale").sizeOr(0.5f); + float maxV = S.drawElement("responsive", "max-v-scale").sizeOr(1.4f); + float logical = std::clamp(availHeight / rh, minV, maxV); + return logical * dp; +} + +inline float vScale() { + return vScale(ImGui::GetContentRegionAvail().y); +} + +/** + * @brief Density scale factor for spacing tokens. + * + * Logical portion is clamped, then multiplied by DPI so pixel spacing + * values scale proportionally with fonts and style. + */ +inline float densityScale(float availHeight) { + const auto& S = schema::UI(); + float dp = dpiScale(); + float rh = S.drawElement("responsive", "ref-height").sizeOr(700.0f) * dp; + float minDen = S.drawElement("responsive", "min-density").sizeOr(0.6f); + float maxDen = S.drawElement("responsive", "max-density").sizeOr(1.2f); + float logical = std::clamp(availHeight / rh, minDen, maxDen); + return logical * dp; +} + +inline float densityScale() { + return densityScale(ImGui::GetContentRegionAvail().y); +} + +// ============================================================================ +// Spacing Tokens (density-scaled) +// ============================================================================ + +/** @brief Get spacing token scaled by current density. */ +inline float spacingXs() { return schema::UI().drawElement("spacing-tokens", "xs").sizeOr(2.0f) * densityScale(); } +inline float spacingSm() { return schema::UI().drawElement("spacing-tokens", "sm").sizeOr(4.0f) * densityScale(); } +inline float spacingMd() { return schema::UI().drawElement("spacing-tokens", "md").sizeOr(8.0f) * densityScale(); } +inline float spacingLg() { return schema::UI().drawElement("spacing-tokens", "lg").sizeOr(12.0f) * densityScale(); } +inline float spacingXl() { return schema::UI().drawElement("spacing-tokens", "xl").sizeOr(16.0f) * densityScale(); } +inline float spacingXxl() { return schema::UI().drawElement("spacing-tokens", "xxl").sizeOr(24.0f) * densityScale(); } + +/** @brief Get raw (unscaled) spacing token. */ +inline float spacingXsRaw() { return schema::UI().drawElement("spacing-tokens", "xs").sizeOr(2.0f); } +inline float spacingSmRaw() { return schema::UI().drawElement("spacing-tokens", "sm").sizeOr(4.0f); } +inline float spacingMdRaw() { return schema::UI().drawElement("spacing-tokens", "md").sizeOr(8.0f); } +inline float spacingLgRaw() { return schema::UI().drawElement("spacing-tokens", "lg").sizeOr(12.0f); } +inline float spacingXlRaw() { return schema::UI().drawElement("spacing-tokens", "xl").sizeOr(16.0f); } +inline float spacingXxlRaw() { return schema::UI().drawElement("spacing-tokens", "xxl").sizeOr(24.0f); } + +// ============================================================================ +// Responsive Globals Helpers +// ============================================================================ + +/** @brief Default glass panel rounding (8.0 default). */ +inline float glassRounding() { return schema::UI().drawElement("responsive", "glass-rounding").sizeOr(8.0f) * dpiScale(); } + +/** @brief Default card inner padding (12.0 default). */ +inline float cardInnerPadding() { return schema::UI().drawElement("responsive", "card-inner-padding").sizeOr(12.0f) * dpiScale(); } + +/** @brief Default card gap (8.0 default). */ +inline float cardGap() { return schema::UI().drawElement("responsive", "card-gap").sizeOr(8.0f) * dpiScale(); } + +/** + * @brief Compute a responsive card height from a base value. + * @param base Design-time card height (e.g. 110.0f) in logical pixels + * @param vs Vertical scale factor (from vScale(), already DPI-scaled) + * @return Scaled height with a DPI-aware floor of base * 0.4 * dpiScale + */ +inline float cardHeight(float base, float vs) { + return std::max(base * 0.4f * dpiScale(), base * vs); +} + +/** + * @brief Compute a column offset as a ratio of available width. + * Replaces hardcoded "cx + 100" patterns. + * @param ratio Fraction of available width (e.g. 0.12) + * @param availW Available width + */ +inline float columnOffset(float ratio, float availW) { + return availW * ratio; +} + +// ============================================================================ +// Buttons +// ============================================================================ + +inline float kButtonMinWidth() { return schema::UI().drawElement("button", "min-width").sizeOr(180.0f) * dpiScale(); } +inline float kButtonStandardWidth() { return schema::UI().drawElement("button", "width").sizeOr(140.0f) * dpiScale(); } +inline float kButtonLargeWidth() { return schema::UI().drawElement("button", "width-lg").sizeOr(160.0f) * dpiScale(); } +inline float kButtonHeight() { float h = schema::UI().drawElement("button", "height").sizeOr(0.0f); return h > 0.0f ? h * dpiScale() : 0.0f; } + +// ============================================================================ +// Input Fields +// ============================================================================ + +inline float kInputMinWidth() { return schema::UI().drawElement("input", "min-width").sizeOr(150.0f) * dpiScale(); } +inline float kInputMediumWidth() { return schema::UI().drawElement("input", "width-md").sizeOr(200.0f) * dpiScale(); } +inline float kInputLargeWidth() { return schema::UI().drawElement("input", "width-lg").sizeOr(300.0f) * dpiScale(); } +inline float kSearchFieldWidthRatio() { return schema::UI().drawElement("input", "search-width-ratio").sizeOr(0.30f); } + +// ============================================================================ +// Status Bar +// ============================================================================ + +inline float kStatusBarHeight() { float dp = dpiScale(); auto h = schema::UI().window("components.status-bar", "window").height; return (h > 0 ? h : 60.0f) * dp; } +inline float kStatusBarPadding() { float dp = dpiScale(); auto w = schema::UI().window("components.status-bar", "window"); return (w.padding[0] > 0 ? w.padding[0] : 8.0f) * dp; } + +// ============================================================================ +// Helper Functions +// ============================================================================ + +/** + * @brief Calculate responsive width with min/max bounds + * @param availWidth Available width from GetContentRegionAvail().x + * @param ratio Ratio of available width (0.0-1.0) + * @param minWidth Minimum width in pixels + * @param maxWidth Maximum width in pixels + */ +inline float responsiveWidth(float availWidth, float ratio, float minWidth, float maxWidth) { + return std::max(minWidth, std::min(maxWidth, availWidth * ratio)); +} + +/** + * @brief Calculate responsive height with min/max bounds + */ +inline float responsiveHeight(float availHeight, float ratio, float minHeight, float maxHeight) { + return std::max(minHeight, std::min(maxHeight, availHeight * ratio)); +} + +/** + * @brief Get summary panel dimensions + */ +inline ImVec2 getSummaryPanelSize() { + ImVec2 avail = ImGui::GetContentRegionAvail(); + return ImVec2( + responsiveWidth(avail.x, kSummaryPanelWidthRatio(), kSummaryPanelMinWidth(), kSummaryPanelMaxWidth()), + responsiveHeight(avail.y, kSummaryPanelHeightRatio(), kSummaryPanelMinHeight(), kSummaryPanelMaxHeight()) + ); +} + +/** + * @brief Get side panel width (height fills available) + */ +inline float getSidePanelWidth() { + float avail = ImGui::GetContentRegionAvail().x; + return responsiveWidth(avail, kSidePanelWidthRatio(), kSidePanelMinWidth(), kSidePanelMaxWidth()); +} + +/** + * @brief Get table height for split view (two tables) + */ +inline float getTableHeight() { + float avail = ImGui::GetContentRegionAvail().y; + return responsiveHeight(avail, kTableHeightRatio(), kTableMinHeight(), avail * 0.6f); +} + +/** + * @brief Get remaining height (for second table/section) + */ +inline float getRemainingHeight(float reserveSpace) { + float avail = ImGui::GetContentRegionAvail().y; + return std::max(schema::UI().drawElement("panels", "table").getFloat("min-remaining", 100.0f) * dpiScale(), avail - reserveSpace); +} +inline float getRemainingHeight() { + return getRemainingHeight(schema::UI().drawElement("panels", "table").getFloat("default-reserve", 30.0f) * dpiScale()); +} + +/** + * @brief Get search/filter input width + */ +inline float getSearchWidth() { + float avail = ImGui::GetContentRegionAvail().x; + return std::min(kInputLargeWidth(), avail * kSearchFieldWidthRatio()); +} + +/** + * @brief Calculate position for right-aligned buttons + * @param buttonCount Number of buttons + * @param buttonWidth Width of each button + * @param spacing Spacing between buttons + */ +inline float getRightButtonsPos(int buttonCount, float buttonWidth, float spacing) { + float dp = dpiScale(); + float margin = schema::UI().drawElement("button", "right-align-margin").sizeOr(16.0f) * dp; + float minPos = schema::UI().drawElement("button", "right-align-min-pos").sizeOr(200.0f) * dp; + float totalWidth = buttonCount * buttonWidth + (buttonCount - 1) * spacing + margin; + return std::max(minPos, ImGui::GetWindowWidth() - totalWidth); +} +inline float getRightButtonsPos(int buttonCount, float buttonWidth) { + return getRightButtonsPos(buttonCount, buttonWidth, schema::UI().drawElement("button", "right-align-gap").sizeOr(8.0f) * dpiScale()); +} + +// ============================================================================ +// Shared Card Height (send/receive tab parity) +// ============================================================================ + +/** + * @brief Compute the target glass card height for send/receive tabs. + * + * Both tabs call this with the same formW + vs so their cards match. + * The height models the receive tab's QR-code-driven layout: + * topPad + totalQrSize + innerGap + actionBtnH + bottomPad + * + * @param formW Total card / form width in pixels + * @param vs Vertical scale factor (from vScale()) + */ +inline float mainCardTargetH(float formW, float vs) { + float dp = dpiScale(); + float pad = spacingLg(); + float innerW = formW - pad * 2; + float qrColW = innerW * 0.35f; + float qrPad = spacingMd(); + float maxQrSz = std::min(qrColW - qrPad * 2, 280.0f * dp); + float qrSize = std::max(100.0f * dp, maxQrSz); + float totalQr = qrSize + qrPad * 2; + float innerGap = spacingLg(); + float btnH = std::max(26.0f * dp, 30.0f * vs); + return pad + totalQr + innerGap + btnH + pad; +} + +// ============================================================================ +// Section Budget Allocator +// ============================================================================ + +/** + * @brief Proportional height-budget allocator for tab content. + * + * Each tab creates a SectionBudget from the available content height and + * allocates fractions to its sections. Sections receive a proportional + * share of the total height clamped to [minPx, maxPx], guaranteeing + * that all content fits without scrolling at any window size. + * + * Usage: + * SectionBudget b(ImGui::GetContentRegionAvail().y); + * float heroH = b.allocate(0.13f, 55.0f); + * float listH = b.rest(60.0f); // whatever is left + */ +struct SectionBudget { + float total; ///< Total available height passed at construction + float remaining; ///< Decrements as sections are allocated + + explicit SectionBudget(float avail) + : total(avail), remaining(avail) {} + + /** + * @brief Allocate a fraction of the total budget. + * @param fraction Fraction of *total* (e.g. 0.12 = 12%) + * @param minPx Minimum pixel height in logical pixels (auto DPI-scaled) + * @param maxPx Maximum pixel height in logical pixels (auto DPI-scaled, default unlimited) + * @return The allocated height in physical pixels. + */ + float allocate(float fraction, float minPx, float maxPx = FLT_MAX) { + float dp = dpiScale(); + float scaledMin = minPx * dp; + float scaledMax = (maxPx >= FLT_MAX * 0.5f) ? FLT_MAX : maxPx * dp; + float h = std::clamp(total * fraction, scaledMin, scaledMax); + remaining -= h; + if (remaining < 0.0f) remaining = 0.0f; + return h; + } + + /** + * @brief Allocate whatever height remains (for the final section). + * @param minPx Minimum logical pixels guaranteed even if budget is exhausted. + * @return Remaining height (at least minPx * dpiScale). + */ + float rest(float minPx = 0.0f) { + return std::max(minPx * dpiScale(), remaining); + } +}; + +} // namespace Layout + +// ============================================================================ +// Convenience Macros/Functions for Common Patterns +// ============================================================================ + +/** + * @brief Begin a summary panel with responsive sizing + */ +inline bool BeginSummaryPanel(const char* id) { + ImVec2 size = Layout::getSummaryPanelSize(); + return ImGui::BeginChild(id, size, true); +} + +/** + * @brief Begin a side panel with responsive width + */ +inline bool BeginSidePanel(const char* id) { + float width = Layout::getSidePanelWidth(); + return ImGui::BeginChild(id, ImVec2(width, 0), true); +} + +/** + * @brief Begin a content panel that fills remaining space + */ +inline bool BeginContentPanel(const char* id) { + return ImGui::BeginChild(id, ImVec2(0, 0), true); +} + +/** + * @brief Add standard section header with separator + */ +inline void SectionHeader(const char* label) { + OverlineLabel(label); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); +} + +/** + * @brief Add spacing between sections + */ +inline void SectionSpacing() { + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); +} + +/** + * @brief Render a label-value pair + */ +inline void LabelValue(const char* label, const char* value) { + Type().textColored(material::TypeStyle::Caption, OnSurfaceMedium(), label); + ImGui::Text("%s", value); +} + +/** + * @brief Render a label-value pair with colored value + */ +inline void LabelValueColored(const char* label, const char* value, ImU32 color) { + Type().textColored(material::TypeStyle::Caption, OnSurfaceMedium(), label); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(color), "%s", value); +} + +/** + * @brief Render a balance display (amount + ticker) + */ +inline void BalanceDisplay(double amount, const char* ticker, ImU32 color = 0) { + char buf[64]; + snprintf(buf, sizeof(buf), "%.8f", amount); + + if (color != 0) { + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(color), "%s", buf); + } else { + ImGui::Text("%s", buf); + } + ImGui::SameLine(); + Type().textColored(material::TypeStyle::Body2, OnSurfaceMedium(), ticker); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/app_layout.h b/src/ui/material/app_layout.h new file mode 100644 index 0000000..790ec64 --- /dev/null +++ b/src/ui/material/app_layout.h @@ -0,0 +1,501 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "layout.h" +#include "colors.h" +#include "typography.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// App Layout Manager +// ============================================================================ +// Manages the overall application layout following Material Design patterns. +// +// Usage: +// // In your main render loop: +// auto& layout = AppLayout::instance(); +// layout.beginFrame(); +// +// // Render app bar +// if (layout.beginAppBar("DragonX Wallet")) { +// // App bar content (menu items, etc.) +// layout.endAppBar(); +// } +// +// // Render navigation +// if (layout.beginNavigation()) { +// layout.navItem("Balance", ICON_WALLET, currentTab == 0); +// layout.navItem("Send", ICON_SEND, currentTab == 1); +// layout.endNavigation(); +// } +// +// // Render main content +// if (layout.beginContent()) { +// // Your content here +// layout.endContent(); +// } +// +// layout.endFrame(); + +class AppLayout { +public: + static AppLayout& instance() { + static AppLayout s_instance; + return s_instance; + } + + // ======================================================================== + // Frame Management + // ======================================================================== + + /** + * @brief Begin a new frame layout + * + * Call this at the start of each frame before any layout calls. + * Updates responsive breakpoints and calculates regions. + */ + void beginFrame(); + + /** + * @brief End the frame layout + */ + void endFrame(); + + // ======================================================================== + // Layout Regions + // ======================================================================== + + /** + * @brief Begin the app bar region + * + * @param title App title to display + * @param showBack Show back button (for sub-pages) + * @return true if app bar is visible + */ + bool beginAppBar(const char* title, bool showBack = false); + void endAppBar(); + + /** + * @brief Begin the navigation region (drawer/rail/bottom) + * + * @return true if navigation region is visible + */ + bool beginNavigation(); + void endNavigation(); + + /** + * @brief Render a navigation item + * + * @param label Item label + * @param icon Icon glyph (can be nullptr) + * @param selected Whether this item is currently selected + * @return true if clicked + */ + bool navItem(const char* label, const char* icon, bool selected); + + /** + * @brief Add a navigation section divider + * + * @param title Optional section title + */ + void navSection(const char* title = nullptr); + + /** + * @brief Begin the main content region + * + * @return true if content region is visible + */ + bool beginContent(); + void endContent(); + + // ======================================================================== + // Card Helpers + // ======================================================================== + + /** + * @brief Begin a Material Design card + * + * @param id Unique ID for the card + * @param layout Card layout configuration + * @return true if card is visible + */ + bool beginCard(const char* id, const CardLayout& layout = CardLayout()); + void endCard(); + + // ======================================================================== + // Layout Queries + // ======================================================================== + + /** + * @brief Get current breakpoint category + */ + breakpoint::Category getBreakpoint() const { return breakpoint_; } + + /** + * @brief Get current navigation style + */ + breakpoint::NavStyle getNavStyle() const { return navStyle_; } + + /** + * @brief Get content region available width + */ + float getContentWidth() const { return contentWidth_; } + + /** + * @brief Get content region available height + */ + float getContentHeight() const { return contentHeight_; } + + /** + * @brief Check if navigation drawer is expanded + */ + bool isNavExpanded() const { return navExpanded_; } + + /** + * @brief Toggle navigation drawer expansion + */ + void toggleNav() { navExpanded_ = !navExpanded_; } + + /** + * @brief Set navigation drawer expansion state + */ + void setNavExpanded(bool expanded) { navExpanded_ = expanded; } + +private: + AppLayout(); + ~AppLayout() = default; + AppLayout(const AppLayout&) = delete; + AppLayout& operator=(const AppLayout&) = delete; + + // Layout state + breakpoint::Category breakpoint_ = breakpoint::Category::Md; + breakpoint::NavStyle navStyle_ = breakpoint::NavStyle::NavDrawer; + float windowWidth_ = 0; + float windowHeight_ = 0; + float contentWidth_ = 0; + float contentHeight_ = 0; + bool navExpanded_ = true; + + // Region tracking + bool inAppBar_ = false; + bool inNav_ = false; + bool inContent_ = false; + + // Calculated regions + ImVec2 appBarPos_; + ImVec2 appBarSize_; + ImVec2 navPos_; + ImVec2 navSize_; + ImVec2 contentPos_; + ImVec2 contentSize_; + + void calculateRegions(); +}; + +// ============================================================================ +// Inline Implementation +// ============================================================================ + +inline AppLayout::AppLayout() { + // Initialize with reasonable defaults + navExpanded_ = true; +} + +inline void AppLayout::beginFrame() { + // Get main viewport size + ImGuiViewport* viewport = ImGui::GetMainViewport(); + windowWidth_ = viewport->WorkSize.x; + windowHeight_ = viewport->WorkSize.y; + + // Update responsive state + breakpoint_ = breakpoint::GetCategory(windowWidth_); + navStyle_ = breakpoint::GetNavStyle(breakpoint_); + + // Auto-collapse nav on small screens + if (breakpoint_ == breakpoint::Category::Xs) { + navExpanded_ = false; + } + + calculateRegions(); +} + +inline void AppLayout::endFrame() { + // Reset state + inAppBar_ = false; + inNav_ = false; + inContent_ = false; +} + +inline void AppLayout::calculateRegions() { + // App bar at top + appBarPos_ = ImVec2(0, 0); + appBarSize_ = ImVec2(windowWidth_, size::AppBarHeight); + + float belowAppBar = size::AppBarHeight; + float contentAreaHeight = windowHeight_ - belowAppBar; + + // Navigation region + switch (navStyle_) { + case breakpoint::NavStyle::NavDrawer: + if (navExpanded_) { + navSize_ = ImVec2(size::NavDrawerWidth, contentAreaHeight); + } else { + navSize_ = ImVec2(size::NavRailWidth, contentAreaHeight); + } + navPos_ = ImVec2(0, belowAppBar); + break; + + case breakpoint::NavStyle::NavRail: + navSize_ = ImVec2(size::NavRailWidth, contentAreaHeight); + navPos_ = ImVec2(0, belowAppBar); + break; + + case breakpoint::NavStyle::BottomNav: + // Bottom nav handled separately + navSize_ = ImVec2(windowWidth_, size::NavItemHeight); + navPos_ = ImVec2(0, windowHeight_ - size::NavItemHeight); + contentAreaHeight -= size::NavItemHeight; + break; + } + + // Content region + if (navStyle_ == breakpoint::NavStyle::BottomNav) { + contentPos_ = ImVec2(0, belowAppBar); + contentSize_ = ImVec2(windowWidth_, contentAreaHeight); + } else { + contentPos_ = ImVec2(navSize_.x, belowAppBar); + contentSize_ = ImVec2(windowWidth_ - navSize_.x, contentAreaHeight); + } + + contentWidth_ = contentSize_.x; + contentHeight_ = contentSize_.y; +} + +inline bool AppLayout::beginAppBar(const char* title, bool showBack) { + ImGui::SetNextWindowPos(appBarPos_); + ImGui::SetNextWindowSize(appBarSize_); + + ImGuiWindowFlags flags = + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus; + + // Use elevated surface color for app bar + ImGui::PushStyleColor(ImGuiCol_WindowBg, SurfaceVec4(4)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(size::AppBarPadding, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + + bool visible = ImGui::Begin("##AppBar", nullptr, flags); + + if (visible) { + inAppBar_ = true; + + // Center content vertically + float centerY = (size::AppBarHeight - Typography::instance().getFont(TypeStyle::H6)->FontSize) * 0.5f; + ImGui::SetCursorPosY(centerY); + + // Menu/back button + if (showBack) { + if (ImGui::Button("<")) { + // Back action - handled by caller + } + ImGui::SameLine(); + } else if (navStyle_ != breakpoint::NavStyle::BottomNav) { + // Menu button to toggle nav + if (ImGui::Button("=")) { + toggleNav(); + } + ImGui::SameLine(); + } + + // Title + Typography::instance().text(TypeStyle::H6, title); + } + + return visible; +} + +inline void AppLayout::endAppBar() { + ImGui::End(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + inAppBar_ = false; +} + +inline bool AppLayout::beginNavigation() { + if (navStyle_ == breakpoint::NavStyle::BottomNav) { + ImGui::SetNextWindowPos(navPos_); + } else { + ImGui::SetNextWindowPos(navPos_); + } + ImGui::SetNextWindowSize(navSize_); + + ImGuiWindowFlags flags = + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus; + + // Nav drawer has higher elevation + int elevation = (navStyle_ == breakpoint::NavStyle::NavDrawer) ? 16 : 0; + ImGui::PushStyleColor(ImGuiCol_WindowBg, SurfaceVec4(elevation)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, size::NavSectionPadding)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + + bool visible = ImGui::Begin("##Navigation", nullptr, flags); + + if (visible) { + inNav_ = true; + } + + return visible; +} + +inline void AppLayout::endNavigation() { + ImGui::End(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + inNav_ = false; +} + +inline bool AppLayout::navItem(const char* label, const char* icon, bool selected) { + bool compact = !navExpanded_ || navStyle_ == breakpoint::NavStyle::NavRail; + + float itemWidth = navSize_.x; + float itemHeight = size::NavItemHeight; + + ImGui::PushID(label); + + // Selection highlight + if (selected) { + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + drawList->AddRectFilled( + pos, + ImVec2(pos.x + itemWidth, pos.y + itemHeight), + StateSelected() + ); + } + + // Padding + ImGui::SetCursorPosX(size::NavItemPadding); + + // Content + bool clicked = false; + ImGui::BeginGroup(); + + if (compact) { + // Rail/collapsed: Icon only, centered + CenterHorizontally(size::IconSize); + clicked = ImGui::Selectable(icon ? icon : "?", selected, 0, ImVec2(size::IconSize, itemHeight)); + } else { + // Drawer: Icon + label + if (icon) { + ImGui::Text("%s", icon); + ImGui::SameLine(); + } + float selectableWidth = itemWidth - size::NavItemPadding * 2 - (icon ? size::IconSize + spacing::Sm : 0); + clicked = ImGui::Selectable(label, selected, 0, ImVec2(selectableWidth, itemHeight)); + } + + ImGui::EndGroup(); + ImGui::PopID(); + + return clicked; +} + +inline void AppLayout::navSection(const char* title) { + VSpace(1); + + if (title && navExpanded_) { + ImGui::SetCursorPosX(size::NavItemPadding); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), title); + } + + // Divider + ImGui::Separator(); + VSpace(1); +} + +inline bool AppLayout::beginContent() { + ImGui::SetNextWindowPos(contentPos_); + ImGui::SetNextWindowSize(contentSize_); + + ImGuiWindowFlags flags = + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus; + + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::ColorConvertU32ToFloat4(Background())); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(spacing::Md, spacing::Md)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + + bool visible = ImGui::Begin("##Content", nullptr, flags); + + if (visible) { + inContent_ = true; + } + + return visible; +} + +inline void AppLayout::endContent() { + ImGui::End(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + inContent_ = false; +} + +inline bool AppLayout::beginCard(const char* id, const CardLayout& layout) { + float width = layout.width > 0 ? layout.width : ImGui::GetContentRegionAvail().x; + + ImGui::PushID(id); + + // Card background + ImGui::PushStyleColor(ImGuiCol_ChildBg, SurfaceVec4(layout.elevation)); + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, layout.cornerRadius); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(layout.padding, layout.padding)); + + ImVec2 size(width, layout.minHeight > 0 ? layout.minHeight : 0); + bool visible = ImGui::BeginChild(id, size, ImGuiChildFlags_AutoResizeY); + + return visible; +} + +inline void AppLayout::endCard() { + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + ImGui::PopID(); + + // Add spacing after card + VSpace(2); +} + +// ============================================================================ +// Convenience Function +// ============================================================================ + +/** + * @brief Get the app layout instance + */ +inline AppLayout& Layout() { + return AppLayout::instance(); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/color_theme.cpp b/src/ui/material/color_theme.cpp new file mode 100644 index 0000000..1faa728 --- /dev/null +++ b/src/ui/material/color_theme.cpp @@ -0,0 +1,516 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "color_theme.h" +#include "../schema/ui_schema.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Color Utility Implementations +// ============================================================================ + +ImU32 BlendOverlay(ImU32 base, ImU32 overlay, float overlayOpacity) +{ + // Extract components + float baseR = ((base >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float baseG = ((base >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float baseB = ((base >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + float baseA = ((base >> IM_COL32_A_SHIFT) & 0xFF) / 255.0f; + + float overlayR = ((overlay >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float overlayG = ((overlay >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float overlayB = ((overlay >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + + // Blend + float resultR = baseR + (overlayR - baseR) * overlayOpacity; + float resultG = baseG + (overlayG - baseG) * overlayOpacity; + float resultB = baseB + (overlayB - baseB) * overlayOpacity; + + return IM_COL32( + static_cast(resultR * 255.0f), + static_cast(resultG * 255.0f), + static_cast(resultB * 255.0f), + static_cast(baseA * 255.0f) + ); +} + +ImU32 Lighten(ImU32 color, float amount) +{ + return BlendOverlay(color, IM_COL32(255, 255, 255, 255), amount); +} + +ImU32 Darken(ImU32 color, float amount) +{ + return BlendOverlay(color, IM_COL32(0, 0, 0, 255), amount); +} + +// ============================================================================ +// Elevation System +// ============================================================================ + +// Material Design elevation overlay values for dark theme +// These values lighten the surface to indicate elevation +static const float kElevationOverlays[] = { + 0.00f, // 0dp + 0.05f, // 1dp + 0.07f, // 2dp + 0.08f, // 3dp + 0.09f, // 4dp + 0.10f, // 5dp + 0.11f, // 6dp + 0.115f, // 7dp + 0.12f, // 8dp + 0.125f, // 9dp + 0.13f, // 10dp + 0.135f, // 11dp + 0.14f, // 12dp + 0.14f, // 13dp + 0.14f, // 14dp + 0.14f, // 15dp + 0.15f, // 16dp + 0.15f, // 17dp + 0.15f, // 18dp + 0.15f, // 19dp + 0.15f, // 20dp + 0.15f, // 21dp + 0.15f, // 22dp + 0.15f, // 23dp + 0.16f // 24dp +}; + +float GetElevationOverlay(Elevation level) +{ + return GetElevationOverlay(static_cast(level)); +} + +float GetElevationOverlay(int dp) +{ + if (dp < 0) return 0.0f; + if (dp > 24) dp = 24; + return kElevationOverlays[dp]; +} + +ImU32 GetElevatedSurface(const ColorTheme& theme, Elevation level) +{ + return GetElevatedSurface(theme, static_cast(level)); +} + +ImU32 GetElevatedSurface(const ColorTheme& theme, int dp) +{ + float overlay = GetElevationOverlay(dp); + if (overlay <= 0.0f) { + return theme.surface; + } + return BlendOverlay(theme.surface, IM_COL32(255, 255, 255, 255), overlay); +} + +// ============================================================================ +// Theme State +// ============================================================================ + +static ColorTheme s_currentTheme; +static bool s_themeInitialized = false; +static bool s_isDarkTheme = true; +static bool s_backdropActive = false; + +// ============================================================================ +// DragonX Theme (Dark with Red Primary) +// ============================================================================ + +ColorTheme GetDragonXColorTheme() +{ + ColorTheme theme; + + // Primary: DragonX Red + theme.primary = Hex(0xF64740); // Bright red accent + theme.primaryVariant = Hex(0x6F1A07); // Dark maroon variant + theme.primaryLight = Hex(0xF87A75); // Lighter red for highlights + + // Secondary: Blue-gray from text palette + theme.secondary = Hex(0xBFD1E5); // Light blue-gray + theme.secondaryVariant = Hex(0x8BA3BD); // Mid blue-gray + theme.secondaryLight = Hex(0xDAE5F0); // Pale blue-gray + + // Surfaces (Dark navy palette) + theme.background = Hex(0x121420); // Deep navy background + theme.surface = Hex(0x1B2432); // Dark navy surface + theme.surfaceVariant = Hex(0x253345); // Lighter navy variant + + // "On" colors — blue-gray text tones + theme.onPrimary = Hex(0xFFFFFF); // White on red + theme.onSecondary = Hex(0x121420); // Navy on blue-gray + theme.onBackground = Hex(0xE2EDF8); // Bright blue-gray on dark + theme.onSurface = Hex(0xE2EDF8); // Bright blue-gray on surface + theme.onSurfaceMedium = HexA(0xE2EDF8, 179); // 70% + theme.onSurfaceDisabled = HexA(0xE2EDF8, 97); // 38% + + // Error + theme.error = Hex(0xF64740); // Primary red + theme.onError = Hex(0xFFFFFF); // White on error + + // Success/Warning (follow DragonX palette) + theme.success = Hex(0xBFD1E5); // Blue-gray secondary + theme.onSuccess = Hex(0x121420); // Dark on success + theme.warning = Hex(0xF64740); // Primary red + theme.onWarning = Hex(0xFFFFFF); // White on warning + + // State overlays (blue-gray tinted for dark navy theme) + theme.stateHover = HexA(0xBFD1E5, 10); // 4% + theme.stateFocus = HexA(0xBFD1E5, 31); // 12% + theme.statePressed = HexA(0xBFD1E5, 25); // 10% + theme.stateSelected = HexA(0xBFD1E5, 20); // 8% + theme.stateDragged = HexA(0xBFD1E5, 20); // 8% + + // UI elements + theme.divider = HexA(0xBFD1E5, 31); // 12% blue-gray + theme.outline = HexA(0xBFD1E5, 31); // 12% blue-gray + theme.scrim = HexA(0x000000, 128); // 50% black + + return theme; +} + +// ============================================================================ +// Material Dark Theme +// ============================================================================ + +ColorTheme GetMaterialDarkTheme() +{ + ColorTheme theme; + + // Primary: Deep Purple (Material baseline) + theme.primary = Hex(0xBB86FC); // Purple 200 + theme.primaryVariant = Hex(0x3700B3); // Purple 700 + theme.primaryLight = Hex(0xE1BEE7); // Purple 100 + + // Secondary: Teal + theme.secondary = Hex(0x03DAC6); // Teal 200 + theme.secondaryVariant = Hex(0x018786); // Teal 700 + theme.secondaryLight = Hex(0x64FFDA); // Teal A200 + + // Surfaces + theme.background = Hex(0x121212); + theme.surface = Hex(0x1E1E1E); + theme.surfaceVariant = Hex(0x2D2D2D); + + // "On" colors + theme.onPrimary = Hex(0x000000); + theme.onSecondary = Hex(0x000000); + theme.onBackground = Hex(0xFFFFFF); + theme.onSurface = Hex(0xFFFFFF); + theme.onSurfaceMedium = HexA(0xFFFFFF, 179); + theme.onSurfaceDisabled = HexA(0xFFFFFF, 97); + + // Error + theme.error = Hex(0xF64740); + theme.onError = Hex(0xFFFFFF); + + // Success/Warning (follow DragonX palette) + theme.success = Hex(0xBFD1E5); + theme.onSuccess = Hex(0x121420); + theme.warning = Hex(0xF64740); + theme.onWarning = Hex(0xFFFFFF); + + // State overlays + theme.stateHover = HexA(0xFFFFFF, 10); + theme.stateFocus = HexA(0xFFFFFF, 31); + theme.statePressed = HexA(0xFFFFFF, 25); + theme.stateSelected = HexA(0xFFFFFF, 20); + theme.stateDragged = HexA(0xFFFFFF, 20); + + // UI elements + theme.divider = HexA(0xFFFFFF, 31); + theme.outline = HexA(0xFFFFFF, 31); + theme.scrim = HexA(0x000000, 128); + + return theme; +} + +// ============================================================================ +// Material Light Theme +// ============================================================================ + +ColorTheme GetMaterialLightTheme() +{ + ColorTheme theme; + + // Primary: Deep Purple + theme.primary = Hex(0x6200EE); // Purple 500 + theme.primaryVariant = Hex(0x3700B3); // Purple 700 + theme.primaryLight = Hex(0xBB86FC); // Purple 200 + + // Secondary: Teal + theme.secondary = Hex(0x03DAC6); // Teal 200 + theme.secondaryVariant = Hex(0x018786); // Teal 700 + theme.secondaryLight = Hex(0x64FFDA); + + // Surfaces (light) + theme.background = Hex(0xFFFFFF); + theme.surface = Hex(0xFFFFFF); + theme.surfaceVariant = Hex(0xF5F5F5); + + // "On" colors + theme.onPrimary = Hex(0xFFFFFF); + theme.onSecondary = Hex(0x000000); + theme.onBackground = Hex(0x000000); + theme.onSurface = Hex(0x000000); + theme.onSurfaceMedium = HexA(0x000000, 153); // 60% + theme.onSurfaceDisabled = HexA(0x000000, 97); // 38% + + // Error + theme.error = Hex(0xF64740); + theme.onError = Hex(0xFFFFFF); + + // Success/Warning (follow DragonX palette) + theme.success = Hex(0xBFD1E5); // Blue-gray + theme.onSuccess = Hex(0x121420); + theme.warning = Hex(0xF64740); // Primary red + theme.onWarning = Hex(0xFFFFFF); + + // State overlays (black for light theme) + theme.stateHover = HexA(0x000000, 10); + theme.stateFocus = HexA(0x000000, 31); + theme.statePressed = HexA(0x000000, 25); + theme.stateSelected = HexA(0x000000, 20); + theme.stateDragged = HexA(0x000000, 20); + + // UI elements + theme.divider = HexA(0x000000, 31); + theme.outline = HexA(0x000000, 31); + theme.scrim = HexA(0x000000, 128); + + return theme; +} + +// ============================================================================ +// Theme Management +// ============================================================================ + +const ColorTheme& GetCurrentColorTheme() +{ + if (!s_themeInitialized) { + s_currentTheme = GetDragonXColorTheme(); + s_themeInitialized = true; + s_isDarkTheme = true; + } + return s_currentTheme; +} + +void SetCurrentColorTheme(const ColorTheme& theme) +{ + s_currentTheme = theme; + s_themeInitialized = true; + + // Detect if dark theme based on background luminance + float bgR = ((theme.background >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float bgG = ((theme.background >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float bgB = ((theme.background >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + float luminance = 0.299f * bgR + 0.587f * bgG + 0.114f * bgB; + s_isDarkTheme = (luminance < 0.5f); +} + +bool IsDarkTheme() +{ + GetCurrentColorTheme(); // Ensure initialized + return s_isDarkTheme; +} + +void SetBackdropActive(bool active) +{ + s_backdropActive = active; +} + +bool IsBackdropActive() +{ + return s_backdropActive; +} + +// ============================================================================ +// Apply Theme to ImGui +// ============================================================================ + +void ApplyColorThemeToImGui(const ColorTheme& theme) +{ + SetCurrentColorTheme(theme); + + ImGuiStyle& style = ImGui::GetStyle(); + ImVec4* colors = style.Colors; + const auto& S = schema::UI(); + + // Helper to convert ImU32 to ImVec4 + auto toVec4 = [](ImU32 col) -> ImVec4 { + return ImGui::ColorConvertU32ToFloat4(col); + }; + + // Backdrop transparency: when DWM Acrylic is active, make backgrounds + // semi-transparent so the blurred + noisy Acrylic material shows through. + // A dark blue gradient is drawn on the background draw list (in app.cpp) + // for a stylish tinted look while retaining blur + noise. + auto bdElem = [&](const char* key, float fb) { + float v = S.drawElement("backdrop", key).size; + return v >= 0 ? v : fb; + }; + const float bgAlpha = s_backdropActive ? bdElem("background-alpha", 0.40f) : 1.0f; + // When acrylic is active, ChildBg must be fully transparent so the + // sharp background doesn't bleed through behind acrylic cards. + // DrawGlassPanel draws the blurred card fill directly. + const float surfAlpha = s_backdropActive ? 0.0f : 1.0f; + const float tabAlpha = s_backdropActive ? 0.75f : 1.0f; + + // Background colors + colors[ImGuiCol_WindowBg] = toVec4(WithAlphaF(theme.background, bgAlpha)); + colors[ImGuiCol_ChildBg] = toVec4(WithAlphaF(GetElevatedSurface(theme, 1), surfAlpha)); + colors[ImGuiCol_PopupBg] = toVec4(WithAlphaF(GetElevatedSurface(theme, 8), 0.95f)); + + // Borders — dark themes use white outlines; light themes use dark outlines + if (s_isDarkTheme) { + colors[ImGuiCol_Border] = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); + colors[ImGuiCol_BorderShadow] = ImVec4(0, 0, 0, 0.08f); + } else { + colors[ImGuiCol_Border] = ImVec4(0, 0, 0, 0.12f); + colors[ImGuiCol_BorderShadow] = ImVec4(0, 0, 0, 0.04f); + } + + // Frame backgrounds (inputs, checkboxes) — glass-card in dark, subtle grey in light + if (s_isDarkTheme) { + colors[ImGuiCol_FrameBg] = ImVec4(1.0f, 1.0f, 1.0f, 0.07f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(1.0f, 1.0f, 1.0f, 0.10f); + colors[ImGuiCol_FrameBgActive] = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); + } else { + colors[ImGuiCol_FrameBg] = ImVec4(0, 0, 0, 0.04f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0, 0, 0, 0.07f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0, 0, 0, 0.10f); + } + + // Title bar + colors[ImGuiCol_TitleBg] = toVec4(WithAlphaF(GetElevatedSurface(theme, 4), surfAlpha)); + colors[ImGuiCol_TitleBgActive] = toVec4(theme.primary); + colors[ImGuiCol_TitleBgCollapsed] = toVec4(WithAlphaF(GetElevatedSurface(theme, 4), 0.75f)); + + // Menu bar — fully transparent, no background + colors[ImGuiCol_MenuBarBg] = ImVec4(0, 0, 0, 0); + + // Scrollbar — minimal style (dark overlays for light, white overlays for dark) + colors[ImGuiCol_ScrollbarBg] = ImVec4(0, 0, 0, 0); + if (s_isDarkTheme) { + colors[ImGuiCol_ScrollbarGrab] = ImVec4(1.0f, 1.0f, 1.0f, 15.0f / 255.0f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(1.0f, 1.0f, 1.0f, 30.0f / 255.0f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(1.0f, 1.0f, 1.0f, 45.0f / 255.0f); + } else { + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0, 0, 0, 0.10f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0, 0, 0, 0.18f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0, 0, 0, 0.25f); + } + + // Checkmarks, sliders + colors[ImGuiCol_CheckMark] = toVec4(theme.primary); + colors[ImGuiCol_SliderGrab] = toVec4(theme.primary); + colors[ImGuiCol_SliderGrabActive] = toVec4(theme.primaryLight); + + // Buttons — glass-style overlays (white on dark, dark on light) + if (s_isDarkTheme) { + colors[ImGuiCol_Button] = ImVec4(1.0f, 1.0f, 1.0f, 15.0f / 255.0f); + colors[ImGuiCol_ButtonHovered] = ImVec4(1.0f, 1.0f, 1.0f, 30.0f / 255.0f); + colors[ImGuiCol_ButtonActive] = ImVec4(1.0f, 1.0f, 1.0f, 45.0f / 255.0f); + } else { + colors[ImGuiCol_Button] = ImVec4(0, 0, 0, 0.05f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0, 0, 0, 0.08f); + colors[ImGuiCol_ButtonActive] = ImVec4(0, 0, 0, 0.12f); + } + + // Headers (collapsing headers, tree nodes, selectable, menu items) + colors[ImGuiCol_Header] = toVec4(WithAlphaF(theme.primary, 0.6f)); + colors[ImGuiCol_HeaderHovered] = toVec4(WithAlphaF(theme.primary, 0.8f)); + colors[ImGuiCol_HeaderActive] = toVec4(theme.primary); + + // Separator + colors[ImGuiCol_Separator] = toVec4(theme.divider); + colors[ImGuiCol_SeparatorHovered] = toVec4(theme.primaryLight); + colors[ImGuiCol_SeparatorActive] = toVec4(theme.primary); + + // Resize grip + colors[ImGuiCol_ResizeGrip] = toVec4(WithAlphaF(theme.primary, 0.25f)); + colors[ImGuiCol_ResizeGripHovered] = toVec4(WithAlphaF(theme.primary, 0.67f)); + colors[ImGuiCol_ResizeGripActive] = toVec4(WithAlphaF(theme.primary, 0.95f)); + + // Tabs + ImU32 tabBg = GetElevatedSurface(theme, 4); + colors[ImGuiCol_Tab] = toVec4(WithAlphaF(tabBg, tabAlpha)); + colors[ImGuiCol_TabHovered] = toVec4(WithAlphaF(Lighten(theme.primary, 0.15f), tabAlpha)); + colors[ImGuiCol_TabSelected] = toVec4(WithAlphaF(theme.primary, tabAlpha)); + colors[ImGuiCol_TabSelectedOverline] = toVec4(theme.secondary); + colors[ImGuiCol_TabDimmed] = toVec4(WithAlphaF(Darken(tabBg, 0.2f), tabAlpha)); + colors[ImGuiCol_TabDimmedSelected] = toVec4(WithAlphaF(theme.primary, tabAlpha * 0.7f)); + + // Plot colors + colors[ImGuiCol_PlotLines] = toVec4(theme.primary); + colors[ImGuiCol_PlotLinesHovered] = toVec4(theme.secondary); + colors[ImGuiCol_PlotHistogram] = toVec4(theme.primary); + colors[ImGuiCol_PlotHistogramHovered] = toVec4(theme.secondary); + + // Tables + colors[ImGuiCol_TableHeaderBg] = toVec4(WithAlphaF(GetElevatedSurface(theme, 2), surfAlpha)); + colors[ImGuiCol_TableBorderStrong] = toVec4(theme.outline); + colors[ImGuiCol_TableBorderLight] = toVec4(theme.divider); + colors[ImGuiCol_TableRowBg] = ImVec4(0, 0, 0, 0); + colors[ImGuiCol_TableRowBgAlt] = toVec4(WithAlphaF(theme.onSurface, 0.03f)); + + // Text + colors[ImGuiCol_Text] = toVec4(theme.onSurface); + colors[ImGuiCol_TextDisabled] = toVec4(theme.onSurfaceDisabled); + colors[ImGuiCol_TextSelectedBg] = toVec4(WithAlphaF(theme.primary, 0.43f)); + + // Drag/drop + colors[ImGuiCol_DragDropTarget] = toVec4(WithAlphaF(theme.secondary, 0.9f)); + + // Navigation highlight + colors[ImGuiCol_NavCursor] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); + colors[ImGuiCol_NavWindowingHighlight]= ImVec4(1, 1, 1, 0.7f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.8f, 0.8f, 0.8f, 0.2f); + + // Modal window dim + colors[ImGuiCol_ModalWindowDimBg] = toVec4(theme.scrim); + + // Style adjustments (from UISchema) + auto brElem = S.drawElement("style", "border-radius"); + style.WindowRounding = brElem.extraFloats.count("window") ? brElem.extraFloats.at("window") : 6.0f; + style.ChildRounding = brElem.extraFloats.count("child") ? brElem.extraFloats.at("child") : 4.0f; + style.FrameRounding = brElem.extraFloats.count("frame") ? brElem.extraFloats.at("frame") : 4.0f; + style.PopupRounding = brElem.extraFloats.count("popup") ? brElem.extraFloats.at("popup") : 4.0f; + style.ScrollbarRounding = brElem.extraFloats.count("scrollbar") ? brElem.extraFloats.at("scrollbar") : 4.0f; + style.GrabRounding = brElem.extraFloats.count("grab") ? brElem.extraFloats.at("grab") : 4.0f; + style.TabRounding = brElem.extraFloats.count("tab") ? brElem.extraFloats.at("tab") : 4.0f; + + style.WindowTitleAlign = ImVec2(0.0f, 0.5f); // Left-aligned titles (Material) + auto sElem = [&](const char* key, float fb) { + float v = S.drawElement("style", key).size; + return v >= 0 ? v : fb; + }; + style.WindowPadding = ImVec2(sElem("window-padding-x", 10.0f), sElem("window-padding-y", 10.0f)); + style.FramePadding = ImVec2(sElem("frame-padding-x", 8.0f), sElem("frame-padding-y", 4.0f)); + style.ItemSpacing = ImVec2(sElem("item-spacing-x", 8.0f), sElem("item-spacing-y", 6.0f)); + style.ItemInnerSpacing = ImVec2(sElem("item-inner-spacing-x", 6.0f), sElem("item-inner-spacing-y", 4.0f)); + style.IndentSpacing = sElem("indent-spacing", 20.0f); + + style.ScrollbarSize = sElem("scrollbar-size", 6.0f); + style.GrabMinSize = sElem("grab-min-size", 8.0f); + + auto bwElem = S.drawElement("style", "border-width"); + style.WindowBorderSize = bwElem.extraFloats.count("window") ? bwElem.extraFloats.at("window") : 1.0f; + style.ChildBorderSize = bwElem.extraFloats.count("child") ? bwElem.extraFloats.at("child") : 1.0f; + style.PopupBorderSize = bwElem.extraFloats.count("popup") ? bwElem.extraFloats.at("popup") : 1.0f; + style.FrameBorderSize = bwElem.extraFloats.count("frame") ? bwElem.extraFloats.at("frame") : 0.0f; + style.TabBorderSize = 0.0f; + + style.AntiAliasedLines = true; + style.AntiAliasedFill = true; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/color_theme.h b/src/ui/material/color_theme.h new file mode 100644 index 0000000..52746db --- /dev/null +++ b/src/ui/material/color_theme.h @@ -0,0 +1,284 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// Material Design 2 Color Theme System +// Based on https://m2.material.io/design/color/the-color-system.html + +#pragma once + +#include "imgui.h" +#include + +// Windows defines RGB as a macro - undefine it to avoid conflicts +#ifdef RGB +#undef RGB +#endif + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Color Utilities +// ============================================================================ + +/** + * @brief Convert ImU32 to ImVec4 + */ +inline ImVec4 ColorU32ToVec4(ImU32 color) { + return ImGui::ColorConvertU32ToFloat4(color); +} + +/** + * @brief Convert ImVec4 to ImU32 + */ +inline ImU32 ColorVec4ToU32(const ImVec4& color) { + return ImGui::ColorConvertFloat4ToU32(color); +} + +/** + * @brief Create color from RGB values (0-255) + */ +constexpr ImU32 MakeRGB(uint8_t r, uint8_t g, uint8_t b) { + return IM_COL32(r, g, b, 255); +} + +/** + * @brief Create color from RGBA values (0-255) + */ +constexpr ImU32 MakeRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + return IM_COL32(r, g, b, a); +} + +/** + * @brief Create color from hex value (0xRRGGBB) + */ +constexpr ImU32 Hex(uint32_t hex) { + return IM_COL32( + (hex >> 16) & 0xFF, + (hex >> 8) & 0xFF, + hex & 0xFF, + 255 + ); +} + +/** + * @brief Create color from hex value with alpha (0xRRGGBB, alpha 0-255) + */ +constexpr ImU32 HexA(uint32_t hex, uint8_t alpha) { + return IM_COL32( + (hex >> 16) & 0xFF, + (hex >> 8) & 0xFF, + hex & 0xFF, + alpha + ); +} + +/** + * @brief Apply alpha to existing color + */ +inline ImU32 WithAlpha(ImU32 color, uint8_t alpha) { + return (color & 0x00FFFFFF) | (static_cast(alpha) << 24); +} + +/** + * @brief Apply alpha percentage (0.0 - 1.0) to existing color + */ +inline ImU32 WithAlphaF(ImU32 color, float alpha) { + return WithAlpha(color, static_cast(alpha * 255.0f)); +} + +/** + * @brief Blend two colors with overlay opacity + */ +ImU32 BlendOverlay(ImU32 base, ImU32 overlay, float overlayOpacity); + +/** + * @brief Lighten a color by percentage (0.0 - 1.0) + */ +ImU32 Lighten(ImU32 color, float amount); + +/** + * @brief Darken a color by percentage (0.0 - 1.0) + */ +ImU32 Darken(ImU32 color, float amount); + +// ============================================================================ +// Material Design Color Theme +// ============================================================================ + +/** + * @brief Complete Material Design 2 color theme + * + * Based on the Material Design color system with: + * - Primary and secondary brand colors + * - Surface and background colors + * - "On" colors for content on surfaces + * - State overlay colors + * - Error colors + */ +struct ColorTheme { + // ======================================================================== + // Brand Colors - Primary + // ======================================================================== + ImU32 primary; // Main brand color (displayed most frequently) + ImU32 primaryVariant; // Darker variant for contrast + ImU32 primaryLight; // Lighter variant for highlights + + // ======================================================================== + // Brand Colors - Secondary (Accent) + // ======================================================================== + ImU32 secondary; // Accent color for emphasis + ImU32 secondaryVariant; // Darker variant + ImU32 secondaryLight; // Lighter variant + + // ======================================================================== + // Surface Colors + // ======================================================================== + ImU32 background; // App background + ImU32 surface; // Card/dialog surfaces (elevation 0dp) + ImU32 surfaceVariant; // Alternative surface + + // ======================================================================== + // "On" Colors - Content colors for surfaces + // ======================================================================== + ImU32 onPrimary; // Text/icons on primary color + ImU32 onSecondary; // Text/icons on secondary color + ImU32 onBackground; // Text/icons on background + ImU32 onSurface; // Text/icons on surface (high emphasis) + ImU32 onSurfaceMedium; // Medium emphasis text (70% opacity) + ImU32 onSurfaceDisabled; // Disabled text (38% opacity) + + // ======================================================================== + // Error Colors + // ======================================================================== + ImU32 error; // Error indication + ImU32 onError; // Text on error color + + // ======================================================================== + // Success/Warning Colors (Material extension) + // ======================================================================== + ImU32 success; // Success indication + ImU32 onSuccess; // Text on success + ImU32 warning; // Warning indication + ImU32 onWarning; // Text on warning + + // ======================================================================== + // State Overlay Colors (applied to surfaces) + // ======================================================================== + ImU32 stateHover; // Hover overlay (4% white/black) + ImU32 stateFocus; // Focus overlay (12%) + ImU32 statePressed; // Pressed overlay (10%) + ImU32 stateSelected; // Selected overlay (8%) + ImU32 stateDragged; // Dragged overlay (8%) + + // ======================================================================== + // Additional UI Colors + // ======================================================================== + ImU32 divider; // Divider lines + ImU32 outline; // Outline/border color + ImU32 scrim; // Modal overlay background +}; + +// ============================================================================ +// Elevation System (Dark Theme) +// ============================================================================ + +/** + * @brief Material Design elevation levels + * + * In dark theme, elevation is shown through surface color lightening + * rather than shadows. + */ +enum class Elevation { + Dp0 = 0, // 0dp - Background + Dp1 = 1, // 1dp - Cards at rest, Search bar + Dp2 = 2, // 2dp - Buttons at rest + Dp3 = 3, // 3dp - Refresh indicator + Dp4 = 4, // 4dp - App bar + Dp6 = 6, // 6dp - FAB, Snackbar + Dp8 = 8, // 8dp - Bottom sheet, Menu, Cards picked up + Dp12 = 12, // 12dp - FAB pressed + Dp16 = 16, // 16dp - Navigation drawer, Modal sheets + Dp24 = 24 // 24dp - Dialog +}; + +/** + * @brief Get overlay opacity for elevation level (dark theme) + * + * Material Design uses white overlay on dark surfaces to indicate elevation. + * Higher elevation = more white overlay = lighter surface. + */ +float GetElevationOverlay(Elevation level); +float GetElevationOverlay(int dp); + +/** + * @brief Calculate surface color for given elevation + * + * Applies white overlay to base surface color based on elevation. + */ +ImU32 GetElevatedSurface(const ColorTheme& theme, Elevation level); +ImU32 GetElevatedSurface(const ColorTheme& theme, int dp); + +// ============================================================================ +// Predefined Themes +// ============================================================================ + +/** + * @brief DragonX branded dark theme with red primary color + */ +ColorTheme GetDragonXColorTheme(); + +/** + * @brief Standard Material dark theme + */ +ColorTheme GetMaterialDarkTheme(); + +/** + * @brief Standard Material light theme + */ +ColorTheme GetMaterialLightTheme(); + +// ============================================================================ +// Theme Management +// ============================================================================ + +/** + * @brief Get current active color theme + */ +const ColorTheme& GetCurrentColorTheme(); + +/** + * @brief Set current color theme + */ +void SetCurrentColorTheme(const ColorTheme& theme); + +/** + * @brief Check if current theme is dark mode + */ +bool IsDarkTheme(); + +/** + * @brief Set whether OS-level backdrop (DWM Mica/Acrylic) is active + * + * When active, background and surface colors become semi-transparent + * so the compositor's blur effect shows through. + */ +void SetBackdropActive(bool active); + +/** + * @brief Check if OS-level backdrop is active + */ +bool IsBackdropActive(); + +/** + * @brief Apply Material Design color theme to ImGui + * + * This updates ImGui's color palette to use the Material theme colors. + */ +void ApplyColorThemeToImGui(const ColorTheme& theme); + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/colors.h b/src/ui/material/colors.h new file mode 100644 index 0000000..1c29124 --- /dev/null +++ b/src/ui/material/colors.h @@ -0,0 +1,201 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// ============================================================================ +// Material Design Color Tokens +// ============================================================================ +// +// This header provides convenient access to Material Design color tokens. +// Use these instead of hardcoded colors to maintain theme consistency. +// +// Usage: +// #include "ui/material/colors.h" +// +// // Get surface colors at different elevations +// ImU32 cardBg = dragonx::ui::material::Surface(4); // 4dp elevation +// +// // Get state colors +// ImU32 hovered = dragonx::ui::material::Primary() | dragonx::ui::material::StateHover(); +// +// // Use in ImGui +// ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(cardBg)); + +#pragma once + +#include "color_theme.h" +#include "../schema/ui_schema.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Color Token Accessors (Inline for performance) +// ============================================================================ + +// Primary colors +inline ImU32 Primary() { return GetCurrentColorTheme().primary; } +inline ImU32 PrimaryVariant() { return GetCurrentColorTheme().primaryVariant; } +inline ImU32 PrimaryLight() { return GetCurrentColorTheme().primaryLight; } + +// Secondary colors +inline ImU32 Secondary() { return GetCurrentColorTheme().secondary; } +inline ImU32 SecondaryVariant() { return GetCurrentColorTheme().secondaryVariant; } +inline ImU32 SecondaryLight() { return GetCurrentColorTheme().secondaryLight; } + +// Surface colors (semi-transparent when OS backdrop is active) +inline ImU32 Background() { + ImU32 bg = GetCurrentColorTheme().background; + if (!IsBackdropActive()) return bg; + float alpha = dragonx::ui::schema::UI().drawElement("backdrop", "background-inline-alpha").size; + if (alpha < 0) alpha = 0.30f; + return WithAlphaF(bg, alpha); +} +inline ImU32 Surface() { + ImU32 s = GetCurrentColorTheme().surface; + if (!IsBackdropActive()) return s; + float alpha = dragonx::ui::schema::UI().drawElement("backdrop", "surface-inline-alpha").size; + if (alpha < 0) alpha = 0.55f; + return WithAlphaF(s, alpha); +} +inline ImU32 SurfaceVariant() { return GetCurrentColorTheme().surfaceVariant; } + +// Elevated surfaces - use for cards, dialogs, menus +inline ImU32 Surface(int dp) { + ImU32 s = GetElevatedSurface(GetCurrentColorTheme(), dp); + if (!IsBackdropActive()) return s; + float alpha = dragonx::ui::schema::UI().drawElement("backdrop", "surface-inline-alpha").size; + if (alpha < 0) alpha = 0.55f; + return WithAlphaF(s, alpha); +} +inline ImU32 SurfaceAt(Elevation level) { return GetElevatedSurface(GetCurrentColorTheme(), level); } + +// "On" colors (text on various backgrounds) +inline ImU32 OnPrimary() { return GetCurrentColorTheme().onPrimary; } +inline ImU32 OnSecondary() { return GetCurrentColorTheme().onSecondary; } +inline ImU32 OnBackground() { return GetCurrentColorTheme().onBackground; } +inline ImU32 OnSurface() { return GetCurrentColorTheme().onSurface; } +inline ImU32 OnSurfaceMedium() { return GetCurrentColorTheme().onSurfaceMedium; } +inline ImU32 OnSurfaceDisabled() { return GetCurrentColorTheme().onSurfaceDisabled; } + +// Semantic colors +inline ImU32 Error() { return GetCurrentColorTheme().error; } +inline ImU32 OnError() { return GetCurrentColorTheme().onError; } +inline ImU32 Success() { return GetCurrentColorTheme().success; } +inline ImU32 OnSuccess() { return GetCurrentColorTheme().onSuccess; } +inline ImU32 Warning() { return GetCurrentColorTheme().warning; } +inline ImU32 OnWarning() { return GetCurrentColorTheme().onWarning; } + +// State overlay colors (use with BlendOverlay) +inline ImU32 StateHover() { return GetCurrentColorTheme().stateHover; } +inline ImU32 StateFocus() { return GetCurrentColorTheme().stateFocus; } +inline ImU32 StatePressed() { return GetCurrentColorTheme().statePressed; } +inline ImU32 StateSelected() { return GetCurrentColorTheme().stateSelected; } +inline ImU32 StateDragged() { return GetCurrentColorTheme().stateDragged; } + +// UI structure +inline ImU32 Divider() { return GetCurrentColorTheme().divider; } +inline ImU32 Outline() { return GetCurrentColorTheme().outline; } +inline ImU32 Scrim() { return GetCurrentColorTheme().scrim; } + +// ============================================================================ +// ImVec4 Variants (for direct use with ImGui style colors) +// ============================================================================ + +inline ImVec4 PrimaryVec4() { return ImGui::ColorConvertU32ToFloat4(Primary()); } +inline ImVec4 SecondaryVec4() { return ImGui::ColorConvertU32ToFloat4(Secondary()); } +inline ImVec4 SurfaceVec4() { return ImGui::ColorConvertU32ToFloat4(Surface()); } +inline ImVec4 SurfaceVec4(int dp) { return ImGui::ColorConvertU32ToFloat4(Surface(dp)); } +inline ImVec4 OnSurfaceVec4() { return ImGui::ColorConvertU32ToFloat4(OnSurface()); } +inline ImVec4 ErrorVec4() { return ImGui::ColorConvertU32ToFloat4(Error()); } +inline ImVec4 SuccessVec4() { return ImGui::ColorConvertU32ToFloat4(Success()); } +inline ImVec4 WarningVec4() { return ImGui::ColorConvertU32ToFloat4(Warning()); } + +// ============================================================================ +// Convenience Functions for Common Patterns +// ============================================================================ + +/** + * @brief Get color with applied state overlay + * + * @param base Base color + * @param state State overlay (StateHover, StateFocus, etc.) + * @return Color with state applied + * + * Usage: + * ImU32 hoveredButton = WithState(Primary(), StateHover()); + */ +inline ImU32 WithState(ImU32 base, ImU32 state) +{ + return BlendOverlay(base, state, 1.0f); +} + +/** + * @brief Get button color for current state + * + * @param isHovered Button is hovered + * @param isActive Button is pressed + * @return Appropriate button color + */ +inline ImU32 ButtonColor(bool isHovered, bool isActive) +{ + if (isActive) return WithState(Primary(), StatePressed()); + if (isHovered) return WithState(Primary(), StateHover()); + return Primary(); +} + +/** + * @brief Get surface color for card at specified elevation + * + * @param elevation Elevation in dp (0-24) + * @return Surface color with elevation overlay + */ +inline ImU32 CardSurface(int elevation = 2) +{ + return Surface(elevation); +} + +/** + * @brief Get surface color for dialog/modal + * + * @return Surface color at 24dp elevation + */ +inline ImU32 DialogSurface() +{ + return SurfaceAt(Elevation::Dp24); +} + +/** + * @brief Get surface color for menu/popup + * + * @return Surface color at 8dp elevation + */ +inline ImU32 MenuSurface() +{ + return SurfaceAt(Elevation::Dp8); +} + +/** + * @brief Get surface color for app bar/toolbar + * + * @return Surface color at 4dp elevation + */ +inline ImU32 AppBarSurface() +{ + return SurfaceAt(Elevation::Dp4); +} + +/** + * @brief Get surface color for nav drawer + * + * @return Surface color at 16dp elevation + */ +inline ImU32 NavDrawerSurface() +{ + return SurfaceAt(Elevation::Dp16); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/app_bar.h b/src/ui/material/components/app_bar.h new file mode 100644 index 0000000..b0042e8 --- /dev/null +++ b/src/ui/material/components/app_bar.h @@ -0,0 +1,330 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "buttons.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design App Bar Component +// ============================================================================ +// Based on https://m2.material.io/components/app-bars-top +// +// The top app bar displays information and actions relating to the current +// screen. + +enum class AppBarType { + Regular, // Standard height (56/64dp) + Prominent, // Extended height for larger titles + Dense // Smaller height for desktop +}; + +/** + * @brief App bar configuration + */ +struct AppBarSpec { + AppBarType type = AppBarType::Regular; + ImU32 backgroundColor = 0; // 0 = use elevated surface + bool elevated = true; // Show elevation + bool centerTitle = false; // Center title (default: left) + float elevation = 4.0f; // Elevation in dp +}; + +/** + * @brief Begin a top app bar + * + * @param id Unique identifier + * @param spec App bar configuration + * @return true if app bar is visible + */ +bool BeginAppBar(const char* id, const AppBarSpec& spec = AppBarSpec()); + +/** + * @brief End app bar + */ +void EndAppBar(); + +/** + * @brief Set app bar navigation icon (left side) + * + * @param icon Icon text (e.g., "☰" for menu) + * @param tooltip Optional tooltip + * @return true if clicked + */ +bool AppBarNavIcon(const char* icon, const char* tooltip = nullptr); + +/** + * @brief Set app bar title + */ +void AppBarTitle(const char* title); + +/** + * @brief Add app bar action button (right side) + * + * @param icon Icon text + * @param tooltip Optional tooltip + * @return true if clicked + */ +bool AppBarAction(const char* icon, const char* tooltip = nullptr); + +/** + * @brief Begin app bar action menu (for overflow) + */ +bool BeginAppBarMenu(const char* icon); + +/** + * @brief End app bar action menu + */ +void EndAppBarMenu(); + +/** + * @brief Add menu item to app bar menu + */ +bool AppBarMenuItem(const char* label, const char* icon = nullptr); + +// ============================================================================ +// Implementation +// ============================================================================ + +struct AppBarState { + ImVec2 barMin; + ImVec2 barMax; + float height; + float navIconWidth; + float actionsStartX; + float titleX; + bool hasNavIcon; + bool centerTitle; + ImU32 backgroundColor; +}; + +static AppBarState g_appBarState; + +inline bool BeginAppBar(const char* id, const AppBarSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(id); + + ImGuiIO& io = ImGui::GetIO(); + + // Calculate height based on type + float barHeight; + switch (spec.type) { + case AppBarType::Prominent: + barHeight = 128.0f; + break; + case AppBarType::Dense: + barHeight = 48.0f; + break; + default: + barHeight = size::AppBarHeight; // 56dp + break; + } + + g_appBarState.height = barHeight; + g_appBarState.hasNavIcon = false; + g_appBarState.centerTitle = spec.centerTitle; + g_appBarState.navIconWidth = 0; + g_appBarState.actionsStartX = io.DisplaySize.x; // Will be adjusted as actions added + + // Bar position (always at top) + g_appBarState.barMin = ImVec2(0, 0); + g_appBarState.barMax = ImVec2(io.DisplaySize.x, barHeight); + + // Background color + if (spec.backgroundColor != 0) { + g_appBarState.backgroundColor = spec.backgroundColor; + } else { + g_appBarState.backgroundColor = Surface(Elevation::Dp4); + } + + // Draw app bar background + ImDrawList* drawList = window->DrawList; + drawList->AddRectFilled(g_appBarState.barMin, g_appBarState.barMax, g_appBarState.backgroundColor); + + // Bottom divider/shadow + if (spec.elevated) { + drawList->AddLine( + ImVec2(g_appBarState.barMin.x, g_appBarState.barMax.y), + ImVec2(g_appBarState.barMax.x, g_appBarState.barMax.y), + schema::UI().resolveColor("var(--app-bar-shadow)", IM_COL32(0, 0, 0, 50)) + ); + } + + // Set up layout + g_appBarState.titleX = spacing::dp(2); // Default title position + + return true; +} + +inline void EndAppBar() { + ImGui::PopID(); +} + +inline bool AppBarNavIcon(const char* icon, const char* tooltip) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + g_appBarState.hasNavIcon = true; + g_appBarState.navIconWidth = size::TouchTarget; + + // Position nav icon on left + float iconX = spacing::dp(0.5f); // 4dp left margin + float centerY = g_appBarState.barMin.y + g_appBarState.height * 0.5f; + + ImVec2 buttonPos(iconX, centerY - size::TouchTarget * 0.5f); + + // Draw icon button + ImGui::SetCursorScreenPos(buttonPos); + bool clicked = IconButton(icon, tooltip); + + // Update title position + g_appBarState.titleX = iconX + size::TouchTarget + spacing::dp(1); + + return clicked; +} + +inline void AppBarTitle(const char* title) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + float centerY = g_appBarState.barMin.y + g_appBarState.height * 0.5f; + + // Calculate title position + float titleX; + if (g_appBarState.centerTitle) { + // Center title between nav icon and actions + float availableWidth = g_appBarState.actionsStartX - g_appBarState.titleX; + Typography::instance().pushFont(TypeStyle::H6); + float titleWidth = ImGui::CalcTextSize(title).x; + Typography::instance().popFont(); + titleX = g_appBarState.titleX + (availableWidth - titleWidth) * 0.5f; + } else { + titleX = g_appBarState.titleX; + } + + // Render title + Typography::instance().pushFont(TypeStyle::H6); + float titleY = centerY - ImGui::GetFontSize() * 0.5f; + + ImDrawList* drawList = window->DrawList; + drawList->AddText(ImVec2(titleX, titleY), OnSurface(), title); + + Typography::instance().popFont(); +} + +inline bool AppBarAction(const char* icon, const char* tooltip) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Actions are positioned from right edge + g_appBarState.actionsStartX -= size::TouchTarget; + + float centerY = g_appBarState.barMin.y + g_appBarState.height * 0.5f; + ImVec2 buttonPos(g_appBarState.actionsStartX, centerY - size::TouchTarget * 0.5f); + + ImGui::SetCursorScreenPos(buttonPos); + return IconButton(icon, tooltip); +} + +inline bool BeginAppBarMenu(const char* icon) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Position menu button + g_appBarState.actionsStartX -= size::TouchTarget; + + float centerY = g_appBarState.barMin.y + g_appBarState.height * 0.5f; + ImVec2 buttonPos(g_appBarState.actionsStartX, centerY - size::TouchTarget * 0.5f); + + ImGui::SetCursorScreenPos(buttonPos); + + bool menuOpen = false; + if (IconButton(icon, "More options")) { + ImGui::OpenPopup("##appbar_menu"); + } + + // Style the popup menu + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, spacing::dp(1))); + ImGui::PushStyleVar(ImGuiStyleVar_PopupRounding, size::MenuCornerRadius); + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImGui::ColorConvertU32ToFloat4(Surface(Elevation::Dp8))); + + if (ImGui::BeginPopup("##appbar_menu")) { + menuOpen = true; + } + + return menuOpen; +} + +inline void EndAppBarMenu() { + ImGui::EndPopup(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(2); +} + +inline bool AppBarMenuItem(const char* label, const char* icon) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + + const float itemHeight = size::ListItemHeight; + const float itemWidth = 200.0f; // Menu min width + + ImVec2 pos = window->DC.CursorPos; + ImRect itemBB(pos, ImVec2(pos.x + itemWidth, pos.y + itemHeight)); + + ImGuiID id = window->GetID(label); + ImGui::ItemSize(itemBB); + if (!ImGui::ItemAdd(itemBB, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(itemBB, id, &hovered, &held); + + // Draw + ImDrawList* drawList = window->DrawList; + + if (hovered) { + drawList->AddRectFilled(itemBB.Min, itemBB.Max, schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 10))); + } + + float contentX = pos.x + spacing::dp(2); + float centerY = pos.y + itemHeight * 0.5f; + + // Icon + if (icon) { + drawList->AddText(ImVec2(contentX, centerY - 12.0f), OnSurfaceMedium(), icon); + contentX += 24.0f + spacing::dp(2); + } + + // Label + Typography::instance().pushFont(TypeStyle::Body1); + float labelY = centerY - ImGui::GetFontSize() * 0.5f; + drawList->AddText(ImVec2(contentX, labelY), OnSurface(), label); + Typography::instance().popFont(); + + if (pressed) { + ImGui::CloseCurrentPopup(); + } + + return pressed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/buttons.h b/src/ui/material/components/buttons.h new file mode 100644 index 0000000..370ae7b --- /dev/null +++ b/src/ui/material/components/buttons.h @@ -0,0 +1,351 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Button Components +// ============================================================================ +// Based on https://m2.material.io/components/buttons +// +// Three button variants: +// - Text Button: Low emphasis, no container +// - Outlined Button: Medium emphasis, border only +// - Contained Button: High emphasis, filled background + +enum class ButtonStyle { + Text, // Low emphasis - text only + Outlined, // Medium emphasis - border + Contained // High emphasis - filled (default) +}; + +/** + * @brief Button configuration + */ +struct ButtonSpec { + ButtonStyle style = ButtonStyle::Contained; + bool enabled = true; + bool fullWidth = false; + const char* icon = nullptr; // Leading icon (text glyph) + ImU32 color = 0; // 0 = use primary color +}; + +/** + * @brief Render a Material Design button + * + * @param label Button text (will be uppercased per Material spec) + * @param spec Button configuration + * @return true if clicked + */ +bool Button(const char* label, const ButtonSpec& spec = ButtonSpec()); + +/** + * @brief Render a text-only button (low emphasis) + */ +inline bool TextButton(const char* label, bool enabled = true) { + ButtonSpec spec; + spec.style = ButtonStyle::Text; + spec.enabled = enabled; + return Button(label, spec); +} + +/** + * @brief Render an outlined button (medium emphasis) + */ +inline bool OutlinedButton(const char* label, bool enabled = true) { + ButtonSpec spec; + spec.style = ButtonStyle::Outlined; + spec.enabled = enabled; + return Button(label, spec); +} + +/** + * @brief Render a contained/filled button (high emphasis) + */ +inline bool ContainedButton(const char* label, bool enabled = true) { + ButtonSpec spec; + spec.style = ButtonStyle::Contained; + spec.enabled = enabled; + return Button(label, spec); +} + +/** + * @brief Render an icon button (circular touch target) + * + * @param icon Icon glyph/character + * @param tooltip Hover tooltip text + * @param enabled Whether button is enabled + * @return true if clicked + */ +bool IconButton(const char* icon, const char* tooltip = nullptr, bool enabled = true); + +/** + * @brief Render a Floating Action Button (FAB) + * + * @param icon Icon glyph + * @param label Optional label for extended FAB + * @param mini Use mini size (40dp instead of 56dp) + * @return true if clicked + */ +bool FAB(const char* icon, const char* label = nullptr, bool mini = false); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool Button(const char* label, const ButtonSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + // Convert label to uppercase for Material Design + char upperLabel[256]; + { + const char* src = label; + char* dst = upperLabel; + char* end = upperLabel + sizeof(upperLabel) - 1; + while (*src && dst < end) { + *dst++ = (char)toupper((unsigned char)*src++); + } + *dst = '\0'; + } + + // Get button font + ImFont* buttonFont = Typography::instance().button(); + ImGui::PushFont(buttonFont); + + // Calculate button size + ImVec2 labelSize = ImGui::CalcTextSize(upperLabel); + float iconWidth = spec.icon ? (size::IconSize + size::ButtonIconGap) : 0.0f; + + ImVec2 buttonSize; + buttonSize.x = spec.fullWidth ? ImGui::GetContentRegionAvail().x + : ImMax(labelSize.x + iconWidth + size::ButtonPaddingH * 2, size::ButtonMinWidth); + buttonSize.y = size::ButtonHeight; + + // Get position + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + buttonSize.x, pos.y + buttonSize.y)); + + ImGui::ItemSize(buttonSize, style.FramePadding.y); + if (!ImGui::ItemAdd(bb, id)) { + ImGui::PopFont(); + return false; + } + + // Handle interaction + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held, 0); + + if (!spec.enabled) { + hovered = held = false; + } + + if (hovered) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Get colors + ImU32 primaryColor = spec.color ? spec.color : Primary(); + ImU32 textColor; + ImU32 bgColor; + ImU32 borderColor = 0; + + switch (spec.style) { + case ButtonStyle::Text: + bgColor = 0; // No background + textColor = spec.enabled ? primaryColor : OnSurfaceDisabled(); + if (hovered) bgColor = BlendOverlay(Surface(), StateHover(), 1.0f); + if (held) bgColor = BlendOverlay(Surface(), StatePressed(), 1.0f); + break; + + case ButtonStyle::Outlined: + bgColor = 0; // No background + textColor = spec.enabled ? primaryColor : OnSurfaceDisabled(); + borderColor = spec.enabled ? primaryColor : OnSurfaceDisabled(); + if (hovered) bgColor = BlendOverlay(Surface(), StateHover(), 1.0f); + if (held) bgColor = BlendOverlay(Surface(), StatePressed(), 1.0f); + break; + + case ButtonStyle::Contained: + default: + if (spec.enabled) { + bgColor = primaryColor; + textColor = OnPrimary(); + if (hovered) bgColor = BlendOverlay(primaryColor, StateHover(), 1.0f); + if (held) bgColor = BlendOverlay(primaryColor, StatePressed(), 1.0f); + } else { + bgColor = WithAlphaF(OnSurface(), 0.12f); + textColor = OnSurfaceDisabled(); + } + break; + } + + // Render + ImDrawList* drawList = window->DrawList; + + // Background + if (bgColor) { + drawList->AddRectFilled(bb.Min, bb.Max, bgColor, size::ButtonCornerRadius); + } + + // Border (for outlined) + if (borderColor) { + drawList->AddRect(bb.Min, bb.Max, borderColor, size::ButtonCornerRadius, 0, 1.0f); + } + + // Icon + float contentX = bb.Min.x + size::ButtonPaddingH; + float contentY = bb.Min.y + (buttonSize.y - labelSize.y) * 0.5f; + + if (spec.icon) { + ImFont* iconFont = Type().iconMed(); + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, spec.icon); + ImVec2 iconPos(contentX, bb.Min.y + (buttonSize.y - iconSize.y) * 0.5f); + drawList->AddText(iconFont, iconFont->LegacySize, iconPos, textColor, spec.icon); + contentX += iconSize.x + size::ButtonIconGap; + } + + // Label + drawList->AddText(ImVec2(contentX, contentY), textColor, upperLabel); + + ImGui::PopFont(); + + return pressed && spec.enabled; +} + +inline bool IconButton(const char* icon, const char* tooltip, bool enabled) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(icon); + + ImVec2 pos = window->DC.CursorPos; + ImVec2 size(size::IconButtonSize, size::IconButtonSize); + ImRect bb(pos, ImVec2(pos.x + size.x, pos.y + size.y)); + + ImGui::ItemSize(size); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held, 0); + + if (!enabled) { + hovered = held = false; + } + + if (hovered) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Render ripple/hover circle + ImDrawList* drawList = window->DrawList; + ImVec2 center = bb.GetCenter(); + float radius = size::IconButtonSize * 0.5f; + + if (hovered || held) { + ImU32 overlayColor = held ? StatePressed() : StateHover(); + drawList->AddCircleFilled(center, radius, overlayColor); + } + + // Render icon (use icon font) + ImFont* iconFont = Type().iconMed(); + ImU32 iconColor = enabled ? OnSurface() : OnSurfaceDisabled(); + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, icon); + ImVec2 iconPos(center.x - iconSize.x * 0.5f, center.y - iconSize.y * 0.5f); + drawList->AddText(iconFont, iconFont->LegacySize, iconPos, iconColor, icon); + + // Tooltip + if (tooltip && hovered) { + ImGui::SetTooltip("%s", tooltip); + } + + return pressed && enabled; +} + +inline bool FAB(const char* icon, const char* label, bool mini) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(icon); + + bool extended = (label != nullptr); + float fabSize = mini ? size::FabMiniSize : size::FabSize; + + ImVec2 buttonSize; + if (extended) { + ImVec2 labelSize = ImGui::CalcTextSize(label); + buttonSize.x = size::FabExtendedPadding * 2 + size::IconSize + spacing::Sm + labelSize.x; + buttonSize.y = size::FabExtendedHeight; + } else { + buttonSize.x = fabSize; + buttonSize.y = fabSize; + } + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + buttonSize.x, pos.y + buttonSize.y)); + + ImGui::ItemSize(buttonSize); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held, 0); + + if (hovered) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Colors + ImU32 bgColor = Secondary(); + ImU32 textColor = OnSecondary(); + + if (hovered) bgColor = BlendOverlay(bgColor, StateHover(), 1.0f); + if (held) bgColor = BlendOverlay(bgColor, StatePressed(), 1.0f); + + // Render + ImDrawList* drawList = window->DrawList; + float radius = extended ? size::FabCornerRadius : (fabSize * 0.5f); + drawList->AddRectFilled(bb.Min, bb.Max, bgColor, radius); + + // Icon + ImVec2 center = bb.GetCenter(); + ImFont* iconFont = Type().iconMed(); + if (extended) { + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, icon); + float iconX = bb.Min.x + size::FabExtendedPadding; + float iconY = center.y - iconSize.y * 0.5f; + drawList->AddText(iconFont, iconFont->LegacySize, ImVec2(iconX, iconY), textColor, icon); + + // Label + Typography::instance().pushFont(TypeStyle::Button); + float labelX = iconX + iconSize.x + spacing::Sm; + float labelY = center.y - ImGui::GetFontSize() * 0.5f; + drawList->AddText(ImVec2(labelX, labelY), textColor, label); + Typography::instance().popFont(); + } else { + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, icon); + ImVec2 iconPos(center.x - iconSize.x * 0.5f, center.y - iconSize.y * 0.5f); + drawList->AddText(iconFont, iconFont->LegacySize, iconPos, textColor, icon); + } + + return pressed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/cards.h b/src/ui/material/components/cards.h new file mode 100644 index 0000000..dbd08f4 --- /dev/null +++ b/src/ui/material/components/cards.h @@ -0,0 +1,214 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../draw_helpers.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Card Component +// ============================================================================ +// Based on https://m2.material.io/components/cards +// +// Cards contain content and actions about a single subject. +// They can be elevated (with shadow) or outlined (with border). + +/** + * @brief Card configuration + */ +struct CardSpec { + int elevation = 1; // Elevation in dp (0-24) + bool outlined = false; // Use outline instead of elevation + float cornerRadius = 4.0f; // Corner radius in dp + bool clickable = false; // Make entire card clickable + float padding = 16.0f; // Content padding + float minHeight = 0.0f; // Minimum height (0 = auto) +}; + +/** + * @brief Begin a Material Design card + * + * @param id Unique identifier for the card + * @param spec Card configuration + * @return true if card is visible and content should be rendered + */ +bool BeginCard(const char* id, const CardSpec& spec = CardSpec()); + +/** + * @brief End the card + */ +void EndCard(); + +/** + * @brief Begin a clickable card that returns click state + * + * @param id Unique identifier + * @param spec Card configuration + * @param clicked Output: true if card was clicked + * @return true if card is visible + */ +bool BeginClickableCard(const char* id, const CardSpec& spec, bool* clicked); + +/** + * @brief Card header with title and optional subtitle + * + * @param title Primary title text + * @param subtitle Optional secondary text + * @param avatar Optional avatar texture (rendered as circle) + */ +void CardHeader(const char* title, const char* subtitle = nullptr); + +/** + * @brief Card supporting text/content + * + * @param text Body text content + */ +void CardContent(const char* text); + +/** + * @brief Begin card action area (for buttons) + * + * Actions are typically placed at the bottom of the card. + */ +void CardActions(); + +/** + * @brief End card action area + */ +void CardActionsEnd(); + +/** + * @brief Add divider within card + */ +void CardDivider(); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool BeginCard(const char* id, const CardSpec& spec) { + ImGui::PushID(id); + + // Calculate surface color based on elevation + ImU32 bgColor = spec.outlined ? Surface() : GetElevatedSurface(GetCurrentColorTheme(), spec.elevation); + + // When acrylic backdrop is active, scale card bg alpha by UI opacity + // so cards smoothly transition from opaque (1.0) to see-through. + bool opaqueCards = dragonx::ui::effects::isLowSpecMode(); + if (IsBackdropActive() && !opaqueCards) { + ImVec4 c = ImGui::ColorConvertU32ToFloat4(bgColor); + float uiOp = dragonx::ui::effects::ImGuiAcrylic::GetUIOpacity(); + c.w *= uiOp; + ImGui::PushStyleColor(ImGuiCol_ChildBg, c); + } else { + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(bgColor)); + } + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, spec.cornerRadius); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(spec.padding, spec.padding)); + + // Border for outlined variant + if (spec.outlined) { + ImGui::PushStyleColor(ImGuiCol_Border, ImGui::ColorConvertU32ToFloat4(Outline())); + ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 1.0f); + } else { + ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); + } + + ImVec2 size(0, spec.minHeight); // 0 width = use available width + ImGuiChildFlags flags = ImGuiChildFlags_AutoResizeY; + if (spec.outlined) { + flags |= ImGuiChildFlags_Borders; + } + + bool visible = ImGui::BeginChild(id, size, flags); + + return visible; +} + +inline void EndCard() { + ImGui::EndChild(); + + ImGui::PopStyleVar(3); // ChildRounding, WindowPadding, ChildBorderSize + ImGui::PopStyleColor(1); // ChildBg + + // Check if we used outline style (need to pop extra color) + // Note: We always push the border size var, handle outline color in BeginCard + + ImGui::PopID(); + + // Add spacing after card + VSpace(2); +} + +inline bool BeginClickableCard(const char* id, const CardSpec& spec, bool* clicked) { + *clicked = false; + + ImGui::PushID(id); + + ImVec2 startPos = ImGui::GetCursorScreenPos(); + + // Render card background + ImU32 bgColor = spec.outlined ? Surface() : GetElevatedSurface(GetCurrentColorTheme(), spec.elevation); + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(bgColor)); + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, spec.cornerRadius); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(spec.padding, spec.padding)); + ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, spec.outlined ? 1.0f : 0.0f); + + if (spec.outlined) { + ImGui::PushStyleColor(ImGuiCol_Border, ImGui::ColorConvertU32ToFloat4(Outline())); + } + + ImVec2 size(0, spec.minHeight); + ImGuiChildFlags flags = ImGuiChildFlags_AutoResizeY; + if (spec.outlined) { + flags |= ImGuiChildFlags_Borders; + } + + bool visible = ImGui::BeginChild(id, size, flags); + + return visible; +} + +inline void CardHeader(const char* title, const char* subtitle) { + Typography::instance().text(TypeStyle::H6, title); + + if (subtitle) { + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), subtitle); + } + + VSpace(1); +} + +inline void CardContent(const char* text) { + Typography::instance().textWrapped(TypeStyle::Body2, text); + VSpace(1); +} + +inline void CardActions() { + ImGui::Separator(); + VSpace(1); + ImGui::BeginGroup(); +} + +inline void CardActionsEnd() { + ImGui::EndGroup(); +} + +inline void CardDivider() { + ImGui::Separator(); + VSpace(1); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/chips.h b/src/ui/material/components/chips.h new file mode 100644 index 0000000..075b58e --- /dev/null +++ b/src/ui/material/components/chips.h @@ -0,0 +1,296 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Chips Component +// ============================================================================ +// Based on https://m2.material.io/components/chips +// +// Chips are compact elements that represent an input, attribute, or action. + +enum class ChipType { + Input, // User input (deletable) + Choice, // Single selection from set + Filter, // Filter/checkbox style + Action // Triggers action +}; + +/** + * @brief Chip configuration + */ +struct ChipSpec { + ChipType type = ChipType::Action; + const char* label = nullptr; + const char* icon = nullptr; // Leading icon + const char* avatar = nullptr; // Avatar text (overrides icon) + ImU32 avatarColor = 0; // Avatar background color + bool selected = false; // For choice/filter chips + bool disabled = false; + bool outlined = false; // Outlined vs filled style +}; + +/** + * @brief Render a chip + * + * @param spec Chip configuration + * @return For filter/choice: true if clicked (toggle selection) + * For input: true if delete clicked + * For action: true if clicked + */ +bool Chip(const ChipSpec& spec); + +/** + * @brief Simple action chip + */ +bool Chip(const char* label); + +/** + * @brief Filter chip (toggleable) + */ +bool FilterChip(const char* label, bool* selected); + +/** + * @brief Choice chip (radio-style) + */ +bool ChoiceChip(const char* label, bool selected); + +/** + * @brief Input chip with delete + */ +bool InputChip(const char* label, const char* avatar = nullptr); + +/** + * @brief Begin a chip group for layout + */ +void BeginChipGroup(); + +/** + * @brief End a chip group + */ +void EndChipGroup(); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool Chip(const ChipSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(spec.label); + + // Chip dimensions + const float chipHeight = 32.0f; + const float cornerRadius = chipHeight * 0.5f; + const float horizontalPadding = 12.0f; + const float iconSize = 18.0f; + const float avatarSize = 24.0f; + const float deleteIconSize = 18.0f; + + // Calculate content width + float contentWidth = horizontalPadding * 2; + + bool hasLeading = spec.icon || spec.avatar; + bool hasDelete = (spec.type == ChipType::Input); + bool hasCheckmark = (spec.type == ChipType::Filter && spec.selected); + + if (spec.avatar) { + contentWidth += avatarSize + 8.0f; + } else if (spec.icon || hasCheckmark) { + contentWidth += iconSize + 8.0f; + } + + contentWidth += ImGui::CalcTextSize(spec.label).x; + + if (hasDelete) { + contentWidth += deleteIconSize + 8.0f; + } + + // Layout + ImVec2 pos = window->DC.CursorPos; + ImRect chipBB(pos, ImVec2(pos.x + contentWidth, pos.y + chipHeight)); + + // Interaction + ImGuiID id = window->GetID("##chip"); + ImGui::ItemSize(chipBB); + if (!ImGui::ItemAdd(chipBB, id)) + return false; + + bool hovered, held; + bool clicked = ImGui::ButtonBehavior(chipBB, id, &hovered, &held) && !spec.disabled; + + // Delete button hit test (for input chips) + bool deleteClicked = false; + if (hasDelete) { + float deleteX = chipBB.Max.x - horizontalPadding - deleteIconSize; + ImRect deleteBB( + ImVec2(deleteX, pos.y + (chipHeight - deleteIconSize) * 0.5f), + ImVec2(deleteX + deleteIconSize, pos.y + (chipHeight + deleteIconSize) * 0.5f) + ); + + ImGuiID deleteId = window->GetID("##delete"); + bool deleteHovered, deleteHeld; + deleteClicked = ImGui::ButtonBehavior(deleteBB, deleteId, &deleteHovered, &deleteHeld); + } + + // Draw + ImDrawList* drawList = window->DrawList; + + // Background + ImU32 bgColor; + ImU32 borderColor = 0; + + if (spec.disabled) { + bgColor = schema::UI().resolveColor("var(--surface-hover)", IM_COL32(255, 255, 255, 30)); + } else if (spec.selected) { + bgColor = WithAlpha(Primary(), 51); // Primary at 20% + } else if (spec.outlined) { + bgColor = 0; // Transparent + borderColor = OnSurfaceMedium(); + } else { + bgColor = schema::UI().resolveColor("var(--surface-hover)", IM_COL32(255, 255, 255, 30)); + } + + // Hover/press overlay + if (!spec.disabled) { + if (held) { + bgColor = IM_COL32_ADD(bgColor, schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25))); + } else if (hovered) { + bgColor = IM_COL32_ADD(bgColor, schema::UI().resolveColor("var(--active-overlay)", IM_COL32(255, 255, 255, 10))); + } + } + + // Draw background + if (bgColor) { + drawList->AddRectFilled(chipBB.Min, chipBB.Max, bgColor, cornerRadius); + } + + // Draw border for outlined + if (borderColor) { + drawList->AddRect(chipBB.Min, chipBB.Max, borderColor, cornerRadius, 0, 1.0f); + } + + // Content + float currentX = pos.x + horizontalPadding; + float centerY = pos.y + chipHeight * 0.5f; + + ImU32 contentColor = spec.disabled ? OnSurfaceDisabled() : OnSurface(); + ImU32 iconColor = spec.disabled ? OnSurfaceDisabled() : + spec.selected ? Primary() : OnSurfaceMedium(); + + // Avatar or icon + if (spec.avatar) { + // Avatar circle + ImVec2 avatarCenter(currentX + avatarSize * 0.5f - 4.0f, centerY); + ImU32 avatarBg = spec.avatarColor ? spec.avatarColor : Primary(); + drawList->AddCircleFilled(avatarCenter, avatarSize * 0.5f, avatarBg); + + // Avatar text + ImVec2 textSize = ImGui::CalcTextSize(spec.avatar); + ImVec2 textPos(avatarCenter.x - textSize.x * 0.5f, avatarCenter.y - textSize.y * 0.5f); + drawList->AddText(textPos, OnPrimary(), spec.avatar); + + currentX += avatarSize + 4.0f; + } else if (hasCheckmark) { + // Checkmark for selected filter chips + ImFont* iconFont = Typography::instance().iconSmall(); + ImVec2 chkSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, ICON_MD_CHECK); + drawList->AddText(iconFont, iconFont->LegacySize, + ImVec2(currentX, centerY - chkSz.y * 0.5f), Primary(), ICON_MD_CHECK); + currentX += iconSize + 4.0f; + } else if (spec.icon) { + drawList->AddText(ImVec2(currentX, centerY - iconSize * 0.5f), iconColor, spec.icon); + currentX += iconSize + 4.0f; + } + + // Label + Typography::instance().pushFont(TypeStyle::Body2); + float labelY = centerY - ImGui::GetFontSize() * 0.5f; + drawList->AddText(ImVec2(currentX, labelY), contentColor, spec.label); + Typography::instance().popFont(); + + // Delete icon (for input chips) + if (hasDelete) { + float deleteX = chipBB.Max.x - horizontalPadding - deleteIconSize; + ImFont* iconFont = Typography::instance().iconSmall(); + ImVec2 delSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, ICON_MD_CLOSE); + drawList->AddText(iconFont, iconFont->LegacySize, + ImVec2(deleteX, centerY - delSz.y * 0.5f), + OnSurfaceMedium(), ICON_MD_CLOSE + ); + } + + ImGui::PopID(); + + // Return value depends on chip type + if (spec.type == ChipType::Input) { + return deleteClicked; + } + return clicked; +} + +inline bool Chip(const char* label) { + ChipSpec spec; + spec.label = label; + spec.type = ChipType::Action; + return Chip(spec); +} + +inline bool FilterChip(const char* label, bool* selected) { + ChipSpec spec; + spec.label = label; + spec.type = ChipType::Filter; + spec.selected = *selected; + + bool clicked = Chip(spec); + if (clicked) { + *selected = !*selected; + } + return clicked; +} + +inline bool ChoiceChip(const char* label, bool selected) { + ChipSpec spec; + spec.label = label; + spec.type = ChipType::Choice; + spec.selected = selected; + return Chip(spec); +} + +inline bool InputChip(const char* label, const char* avatar) { + ChipSpec spec; + spec.label = label; + spec.type = ChipType::Input; + spec.avatar = avatar; + return Chip(spec); +} + +inline void BeginChipGroup() { + ImGui::BeginGroup(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing::dp(1), spacing::dp(1))); // 8dp spacing +} + +inline void EndChipGroup() { + ImGui::PopStyleVar(); + ImGui::EndGroup(); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/components.h b/src/ui/material/components/components.h new file mode 100644 index 0000000..fed34bf --- /dev/null +++ b/src/ui/material/components/components.h @@ -0,0 +1,122 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +// ============================================================================ +// Material Design Components - Unified Header +// ============================================================================ +// Include this single header to get all Material Design components. +// +// Based on Material Design 2 (m2.material.io) +// +// All components are in the namespace: dragonx::ui::material + +// Core dependencies +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" + +// Components +#include "buttons.h" // Button, IconButton, FAB +#include "cards.h" // Card, CardHeader, CardContent, CardActions +#include "text_fields.h" // TextField +#include "lists.h" // ListItem, ListDivider, ListSubheader +#include "dialogs.h" // Dialog, ConfirmDialog, AlertDialog +#include "inputs.h" // Switch, Checkbox, RadioButton +#include "progress.h" // LinearProgress, CircularProgress +#include "snackbar.h" // Snackbar, ShowSnackbar +#include "slider.h" // Slider, SliderDiscrete, SliderRange +#include "tabs.h" // TabBar, Tab +#include "chips.h" // Chip, FilterChip, ChoiceChip, InputChip +#include "nav_drawer.h" // NavDrawer, NavItem +#include "app_bar.h" // AppBar, AppBarTitle, AppBarAction + +// ============================================================================ +// Quick Reference +// ============================================================================ +// +// BUTTONS: +// Button(label, spec) - Generic button with style config +// TextButton(label) - Text-only button +// OutlinedButton(label) - Button with outline +// ContainedButton(label) - Filled button (primary) +// IconButton(icon, tooltip) - Circular icon button +// FAB(icon) - Floating action button +// +// CARDS: +// BeginCard(spec)/EndCard() - Card container +// CardHeader(title, subtitle) - Card header section +// CardContent(text) - Card body text +// CardActions()/EndCardActions()- Card button area +// +// TEXT FIELDS: +// TextField(label, buf, size) - Text input field +// TextField(id, buf, size, spec)- Configurable text field +// +// LISTS: +// BeginList(id)/EndList() - List container +// ListItem(text) - Simple list item +// ListItem(primary, secondary) - Two-line item +// ListItem(spec) - Full config item +// ListDivider(inset) - Divider line +// ListSubheader(text) - Section header +// +// DIALOGS: +// BeginDialog(id, &open, spec) - Modal dialog +// EndDialog() +// ConfirmDialog(...) - Confirm/cancel dialog +// AlertDialog(...) - Single-action alert +// +// SELECTION CONTROLS: +// Switch(label, &value) - Toggle switch +// Checkbox(label, &value) - Checkbox +// RadioButton(label, active) - Radio button +// RadioButton(label, &sel, val) - Radio with int selection +// +// PROGRESS: +// LinearProgress(fraction) - Determinate progress bar +// LinearProgressIndeterminate() - Indeterminate progress bar +// CircularProgress(fraction) - Circular progress +// CircularProgressIndeterminate()- Spinner +// +// SNACKBAR: +// ShowSnackbar(msg, action) - Show notification +// DismissSnackbar() - Dismiss current snackbar +// RenderSnackbar() - Call each frame to render +// +// SLIDER: +// Slider(label, &val, min, max) - Continuous slider +// SliderInt(label, &val, ...) - Integer slider +// SliderDiscrete(...) - Stepped slider +// SliderRange(...) - Two-thumb range slider +// +// TABS: +// BeginTabBar(id, &idx) - Tab bar container +// Tab(label) - Tab item +// EndTabBar() +// TabBar(id, labels, count, &idx) - Simple tab bar +// +// CHIPS: +// Chip(label) - Action chip +// FilterChip(label, &selected) - Toggleable filter chip +// ChoiceChip(label, selected) - Choice chip +// InputChip(label, avatar) - Deletable input chip +// BeginChipGroup()/EndChipGroup()- Chip layout helper +// +// NAVIGATION DRAWER: +// BeginNavDrawer(id, &open, spec) - Navigation drawer +// EndNavDrawer() +// NavItem(icon, label, selected) - Navigation item +// NavDivider() - Drawer divider +// NavSubheader(text) - Section header +// +// APP BAR: +// BeginAppBar(id, spec) - Top app bar +// EndAppBar() +// AppBarNavIcon(icon) - Navigation icon (left) +// AppBarTitle(title) - App bar title +// AppBarAction(icon) - Action button (right) +// BeginAppBarMenu(icon) - Overflow menu +// AppBarMenuItem(label) - Menu item diff --git a/src/ui/material/components/dialogs.h b/src/ui/material/components/dialogs.h new file mode 100644 index 0000000..482b47a --- /dev/null +++ b/src/ui/material/components/dialogs.h @@ -0,0 +1,293 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "buttons.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Dialog Component +// ============================================================================ +// Based on https://m2.material.io/components/dialogs +// +// Dialogs inform users about a task and can contain critical information, +// require decisions, or involve multiple tasks. + +/** + * @brief Dialog configuration + */ +struct DialogSpec { + const char* title = nullptr; // Dialog title + float width = 560.0f; // Dialog width (280-560dp typical) + float maxHeight = 0; // Max height (0 = auto) + bool scrollableContent = false; // Enable content scrolling + bool fullWidth = false; // Actions span full width +}; + +/** + * @brief Begin a modal dialog + * + * @param id Unique identifier + * @param open Pointer to open state (will be set false when closed) + * @param spec Dialog configuration + * @return true if dialog is open + */ +bool BeginDialog(const char* id, bool* open, const DialogSpec& spec = DialogSpec()); + +/** + * @brief End a dialog + */ +void EndDialog(); + +/** + * @brief Simple dialog with just text content + */ +bool BeginDialog(const char* id, bool* open, const char* title); + +/** + * @brief Dialog content area (scrollable if configured) + */ +void BeginDialogContent(); + +/** + * @brief End dialog content area + */ +void EndDialogContent(); + +/** + * @brief Dialog actions area (buttons) + */ +void BeginDialogActions(); + +/** + * @brief End dialog actions area + */ +void EndDialogActions(); + +/** + * @brief Standard confirm dialog + * + * @param id Unique identifier + * @param open Pointer to open state + * @param title Dialog title + * @param message Dialog message + * @param confirmText Confirm button text + * @param cancelText Cancel button text (nullptr for no cancel) + * @return 0 = still open, 1 = confirmed, -1 = cancelled + */ +int ConfirmDialog(const char* id, bool* open, const char* title, const char* message, + const char* confirmText = "Confirm", const char* cancelText = "Cancel"); + +/** + * @brief Alert dialog (single action) + * + * @param id Unique identifier + * @param open Pointer to open state + * @param title Dialog title + * @param message Dialog message + * @param buttonText Button text + * @return true when dismissed + */ +bool AlertDialog(const char* id, bool* open, const char* title, const char* message, + const char* buttonText = "OK"); + +// ============================================================================ +// Implementation +// ============================================================================ + +// Internal state for dialog rendering +struct DialogState { + ImVec2 contentMin; + ImVec2 contentMax; + float contentScrollY; + bool scrollable; + float width; +}; + +static DialogState g_currentDialog; + +inline bool BeginDialog(const char* id, bool* open, const DialogSpec& spec) { + if (!*open) + return false; + + // Center dialog on screen + ImGuiIO& io = ImGui::GetIO(); + ImVec2 center = ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + + // Set dialog size + float dialogWidth = spec.width; + ImGui::SetNextWindowSizeConstraints( + ImVec2(280.0f, 0), // Min size + ImVec2(dialogWidth, spec.maxHeight > 0 ? spec.maxHeight : io.DisplaySize.y * 0.9f) + ); + + // Style dialog + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, size::DialogCornerRadius); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::ColorConvertU32ToFloat4(Surface(Elevation::Dp24))); + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImGui::ColorConvertU32ToFloat4(Surface(Elevation::Dp24))); + + // Modal background (scrim) + ImDrawList* bgDrawList = ImGui::GetBackgroundDrawList(); + bgDrawList->AddRectFilled( + ImVec2(0, 0), io.DisplaySize, + schema::UI().resolveColor("var(--scrim)", IM_COL32(0, 0, 0, (int)(0.32f * 255))) + ); + + // Open popup + ImGui::OpenPopup(id); + bool isOpen = ImGui::BeginPopupModal(id, open, + ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoTitleBar); + + if (isOpen) { + g_currentDialog.scrollable = spec.scrollableContent; + g_currentDialog.width = dialogWidth; + + // Title + if (spec.title) { + ImGui::Dummy(ImVec2(0, spacing::dp(3))); // 24dp top padding + ImGui::SetCursorPosX(spacing::dp(3)); // 24dp left padding + Typography::instance().text(TypeStyle::H6, spec.title); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); // 16dp below title + } else { + ImGui::Dummy(ImVec2(0, spacing::dp(2))); // 16dp top padding without title + } + } + + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(2); + + return isOpen; +} + +inline void EndDialog() { + ImGui::EndPopup(); +} + +inline bool BeginDialog(const char* id, bool* open, const char* title) { + DialogSpec spec; + spec.title = title; + return BeginDialog(id, open, spec); +} + +inline void BeginDialogContent() { + ImGui::SetCursorPosX(spacing::dp(3)); // 24dp left padding + + // Start content region + float maxWidth = g_currentDialog.width - spacing::dp(6); // 24dp padding each side + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + maxWidth); + + if (g_currentDialog.scrollable) { + ImGui::BeginChild("##dialogContent", ImVec2(maxWidth, 200), false); + } +} + +inline void EndDialogContent() { + if (g_currentDialog.scrollable) { + ImGui::EndChild(); + } + ImGui::PopTextWrapPos(); + ImGui::Dummy(ImVec2(0, spacing::dp(3))); // 24dp after content +} + +inline void BeginDialogActions() { + // Actions area - right-aligned buttons with 8dp spacing + float contentWidth = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(spacing::dp(1)); // 8dp left padding for actions + + // Push style for action buttons + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing::dp(1), 0)); // 8dp between buttons + + // Right-align: use a dummy to push buttons right + // Buttons will be added inline with SameLine +} + +inline void EndDialogActions() { + ImGui::PopStyleVar(); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp bottom padding +} + +inline int ConfirmDialog(const char* id, bool* open, const char* title, const char* message, + const char* confirmText, const char* cancelText) { + int result = 0; + + if (BeginDialog(id, open, title)) { + BeginDialogContent(); + Typography::instance().textWrapped(TypeStyle::Body1, message); + EndDialogContent(); + + BeginDialogActions(); + + // Calculate button positions for right alignment + float cancelWidth = cancelText ? ImGui::CalcTextSize(cancelText).x + spacing::dp(2) : 0; + float confirmWidth = ImGui::CalcTextSize(confirmText).x + spacing::dp(2); + float totalButtonWidth = cancelWidth + confirmWidth + (cancelText ? spacing::dp(1) : 0); + float startX = ImGui::GetContentRegionAvail().x - totalButtonWidth - spacing::dp(2); + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + startX); + + if (cancelText) { + if (TextButton(cancelText)) { + *open = false; + result = -1; + } + ImGui::SameLine(); + } + + if (ContainedButton(confirmText)) { + *open = false; + result = 1; + } + + EndDialogActions(); + EndDialog(); + } + + return result; +} + +inline bool AlertDialog(const char* id, bool* open, const char* title, const char* message, + const char* buttonText) { + bool dismissed = false; + + if (BeginDialog(id, open, title)) { + BeginDialogContent(); + Typography::instance().textWrapped(TypeStyle::Body1, message); + EndDialogContent(); + + BeginDialogActions(); + + // Right-align single button + float buttonWidth = ImGui::CalcTextSize(buttonText).x + spacing::dp(2); + float startX = ImGui::GetContentRegionAvail().x - buttonWidth - spacing::dp(2); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + startX); + + if (ContainedButton(buttonText)) { + *open = false; + dismissed = true; + } + + EndDialogActions(); + EndDialog(); + } + + return dismissed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/inputs.h b/src/ui/material/components/inputs.h new file mode 100644 index 0000000..c331f93 --- /dev/null +++ b/src/ui/material/components/inputs.h @@ -0,0 +1,414 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Input Controls +// ============================================================================ +// Based on https://m2.material.io/components/selection-controls +// +// Selection controls allow users to complete tasks that involve making choices: +// - Switch: Toggle single option on/off +// - Checkbox: Select multiple options +// - Radio: Select one option from a set + +// ============================================================================ +// Switch +// ============================================================================ + +/** + * @brief Material Design switch (toggle) + * + * @param label Text label + * @param value Pointer to boolean value + * @param disabled If true, switch is non-interactive + * @return true if value changed + */ +bool Switch(const char* label, bool* value, bool disabled = false); + +// ============================================================================ +// Checkbox +// ============================================================================ + +/** + * @brief Checkbox state + */ +enum class CheckboxState { + Unchecked, + Checked, + Indeterminate // For parent with mixed children +}; + +/** + * @brief Material Design checkbox + * + * @param label Text label + * @param value Pointer to boolean value + * @param disabled If true, checkbox is non-interactive + * @return true if value changed + */ +bool Checkbox(const char* label, bool* value, bool disabled = false); + +/** + * @brief Tri-state checkbox + */ +bool Checkbox(const char* label, CheckboxState* state, bool disabled = false); + +// ============================================================================ +// Radio Button +// ============================================================================ + +/** + * @brief Material Design radio button + * + * @param label Text label + * @param active true if this option is selected + * @param disabled If true, radio is non-interactive + * @return true if clicked (caller should update selection) + */ +bool RadioButton(const char* label, bool active, bool disabled = false); + +/** + * @brief Radio button with int selection + * + * @param label Text label + * @param selection Pointer to current selection + * @param value Value this radio represents + * @return true if clicked + */ +bool RadioButton(const char* label, int* selection, int value, bool disabled = false); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool Switch(const char* label, bool* value, bool disabled) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + // Switch dimensions (Material spec: 36x14 track, 20dp thumb) + const float trackWidth = 36.0f; + const float trackHeight = 14.0f; + const float thumbRadius = 10.0f; // 20dp diameter + const float thumbTravel = trackWidth - thumbRadius * 2; + + // Calculate layout + ImVec2 pos = window->DC.CursorPos; + float labelWidth = ImGui::CalcTextSize(label).x; + float totalWidth = trackWidth + spacing::dp(2) + labelWidth; + float totalHeight = ImMax(trackHeight + 6.0f, size::TouchTarget); // Min 48dp touch target + + ImRect bb(pos, ImVec2(pos.x + totalWidth, pos.y + totalHeight)); + + // Interaction + ImGuiID id = window->GetID("##switch"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held) && !disabled; + + bool changed = false; + if (pressed) { + *value = !*value; + changed = true; + } + + // Animation (simple snap for now) + float thumbX = *value ? (thumbTravel) : 0; + + // Draw track + ImDrawList* drawList = window->DrawList; + float trackY = pos.y + totalHeight * 0.5f; + ImVec2 trackMin(pos.x, trackY - trackHeight * 0.5f); + ImVec2 trackMax(pos.x + trackWidth, trackY + trackHeight * 0.5f); + + ImU32 trackColor; + if (disabled) { + trackColor = schema::UI().resolveColor("var(--switch-track-off)", IM_COL32(255, 255, 255, 30)); + } else if (*value) { + trackColor = PrimaryVariant(); // Primary at 50% opacity + } else { + trackColor = schema::UI().resolveColor("var(--switch-track-on)", IM_COL32(255, 255, 255, 97)); + } + + drawList->AddRectFilled(trackMin, trackMax, trackColor, trackHeight * 0.5f); + + // Draw thumb + ImVec2 thumbCenter(pos.x + thumbRadius + thumbX, trackY); + + ImU32 thumbColor; + if (disabled) { + thumbColor = schema::UI().resolveColor("var(--switch-thumb-off)", IM_COL32(189, 189, 189, 255)); + } else if (*value) { + thumbColor = Primary(); + } else { + thumbColor = schema::UI().resolveColor("var(--switch-thumb-on)", IM_COL32(250, 250, 250, 255)); + } + + // Thumb shadow + drawList->AddCircleFilled(ImVec2(thumbCenter.x + 1, thumbCenter.y + 2), thumbRadius, schema::UI().resolveColor("var(--control-shadow)", IM_COL32(0, 0, 0, 60))); + drawList->AddCircleFilled(thumbCenter, thumbRadius, thumbColor); + + // Hover ripple effect + if (hovered && !disabled) { + ImU32 ripple = *value ? WithAlpha(Primary(), 25) : schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25)); + drawList->AddCircleFilled(thumbCenter, thumbRadius + 12.0f, ripple); + } + + // Draw label + ImVec2 labelPos(pos.x + trackWidth + spacing::dp(2), pos.y + (totalHeight - ImGui::GetFontSize()) * 0.5f); + ImU32 labelColor = disabled ? OnSurfaceDisabled() : OnSurface(); + drawList->AddText(labelPos, labelColor, label); + + ImGui::PopID(); + + return changed; +} + +inline bool Checkbox(const char* label, bool* value, bool disabled) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + // Checkbox dimensions (18dp box, 48dp touch target) + const float boxSize = 18.0f; + + // Calculate layout + ImVec2 pos = window->DC.CursorPos; + float labelWidth = ImGui::CalcTextSize(label).x; + float totalWidth = boxSize + spacing::dp(2) + labelWidth; + float totalHeight = size::TouchTarget; + + ImRect bb(pos, ImVec2(pos.x + totalWidth, pos.y + totalHeight)); + + // Interaction + ImGuiID id = window->GetID("##checkbox"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held) && !disabled; + + bool changed = false; + if (pressed) { + *value = !*value; + changed = true; + } + + // Draw checkbox + ImDrawList* drawList = window->DrawList; + float centerY = pos.y + totalHeight * 0.5f; + ImVec2 boxMin(pos.x, centerY - boxSize * 0.5f); + ImVec2 boxMax(pos.x + boxSize, centerY + boxSize * 0.5f); + + ImU32 boxColor, checkColor; + if (disabled) { + boxColor = OnSurfaceDisabled(); + checkColor = schema::UI().resolveColor("var(--checkbox-check)", IM_COL32(0, 0, 0, 255)); + } else if (*value) { + boxColor = Primary(); + checkColor = OnPrimary(); + } else { + boxColor = OnSurfaceMedium(); + checkColor = OnPrimary(); + } + + if (*value) { + // Filled checkbox with checkmark + drawList->AddRectFilled(boxMin, boxMax, boxColor, 2.0f); + + // Draw checkmark + ImVec2 checkStart(boxMin.x + 4, centerY); + ImVec2 checkMid(boxMin.x + 7, centerY + 3); + ImVec2 checkEnd(boxMin.x + 14, centerY - 4); + + drawList->AddLine(checkStart, checkMid, checkColor, 2.0f); + drawList->AddLine(checkMid, checkEnd, checkColor, 2.0f); + } else { + // Empty checkbox border + drawList->AddRect(boxMin, boxMax, boxColor, 2.0f, 0, 2.0f); + } + + // Hover ripple + if (hovered && !disabled) { + ImVec2 boxCenter((boxMin.x + boxMax.x) * 0.5f, centerY); + drawList->AddCircleFilled(boxCenter, boxSize, + *value ? WithAlpha(Primary(), 25) : schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25))); + } + + // Draw label + ImVec2 labelPos(pos.x + boxSize + spacing::dp(2), pos.y + (totalHeight - ImGui::GetFontSize()) * 0.5f); + ImU32 labelColor = disabled ? OnSurfaceDisabled() : OnSurface(); + drawList->AddText(labelPos, labelColor, label); + + ImGui::PopID(); + + return changed; +} + +inline bool Checkbox(const char* label, CheckboxState* state, bool disabled) { + bool checked = (*state == CheckboxState::Checked); + bool indeterminate = (*state == CheckboxState::Indeterminate); + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + const float boxSize = 18.0f; + + ImVec2 pos = window->DC.CursorPos; + float labelWidth = ImGui::CalcTextSize(label).x; + float totalWidth = boxSize + spacing::dp(2) + labelWidth; + float totalHeight = size::TouchTarget; + + ImRect bb(pos, ImVec2(pos.x + totalWidth, pos.y + totalHeight)); + + ImGuiID id = window->GetID("##checkbox"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held) && !disabled; + + bool changed = false; + if (pressed) { + // Cycle: Unchecked -> Checked -> Unchecked (indeterminate only set programmatically) + *state = (*state == CheckboxState::Checked) ? CheckboxState::Unchecked : CheckboxState::Checked; + changed = true; + } + + ImDrawList* drawList = window->DrawList; + float centerY = pos.y + totalHeight * 0.5f; + ImVec2 boxMin(pos.x, centerY - boxSize * 0.5f); + ImVec2 boxMax(pos.x + boxSize, centerY + boxSize * 0.5f); + + ImU32 boxColor = disabled ? OnSurfaceDisabled() : (checked || indeterminate) ? Primary() : OnSurfaceMedium(); + + if (checked || indeterminate) { + drawList->AddRectFilled(boxMin, boxMax, boxColor, 2.0f); + + if (indeterminate) { + // Horizontal line for indeterminate + drawList->AddLine( + ImVec2(boxMin.x + 4, centerY), + ImVec2(boxMax.x - 4, centerY), + OnPrimary(), 2.0f + ); + } else { + // Checkmark + ImVec2 checkStart(boxMin.x + 4, centerY); + ImVec2 checkMid(boxMin.x + 7, centerY + 3); + ImVec2 checkEnd(boxMin.x + 14, centerY - 4); + drawList->AddLine(checkStart, checkMid, OnPrimary(), 2.0f); + drawList->AddLine(checkMid, checkEnd, OnPrimary(), 2.0f); + } + } else { + drawList->AddRect(boxMin, boxMax, boxColor, 2.0f, 0, 2.0f); + } + + if (hovered && !disabled) { + ImVec2 boxCenter((boxMin.x + boxMax.x) * 0.5f, centerY); + drawList->AddCircleFilled(boxCenter, boxSize, schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25))); + } + + ImVec2 labelPos(pos.x + boxSize + spacing::dp(2), pos.y + (totalHeight - ImGui::GetFontSize()) * 0.5f); + ImU32 labelColor = disabled ? OnSurfaceDisabled() : OnSurface(); + drawList->AddText(labelPos, labelColor, label); + + ImGui::PopID(); + + return changed; +} + +inline bool RadioButton(const char* label, bool active, bool disabled) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + // Radio button dimensions (20dp outer, 10dp inner when selected) + const float outerRadius = 10.0f; + const float innerRadius = 5.0f; + + ImVec2 pos = window->DC.CursorPos; + float labelWidth = ImGui::CalcTextSize(label).x; + float totalWidth = outerRadius * 2 + spacing::dp(2) + labelWidth; + float totalHeight = size::TouchTarget; + + ImRect bb(pos, ImVec2(pos.x + totalWidth, pos.y + totalHeight)); + + ImGuiID id = window->GetID("##radio"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held) && !disabled; + + ImDrawList* drawList = window->DrawList; + float centerY = pos.y + totalHeight * 0.5f; + ImVec2 center(pos.x + outerRadius, centerY); + + ImU32 ringColor = disabled ? OnSurfaceDisabled() : active ? Primary() : OnSurfaceMedium(); + + // Outer ring + drawList->AddCircle(center, outerRadius, ringColor, 0, 2.0f); + + // Inner dot when active + if (active) { + drawList->AddCircleFilled(center, innerRadius, ringColor); + } + + // Hover ripple + if (hovered && !disabled) { + drawList->AddCircleFilled(center, outerRadius + 12.0f, + active ? WithAlpha(Primary(), 25) : schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25))); + } + + // Label + ImVec2 labelPos(pos.x + outerRadius * 2 + spacing::dp(2), pos.y + (totalHeight - ImGui::GetFontSize()) * 0.5f); + ImU32 labelColor = disabled ? OnSurfaceDisabled() : OnSurface(); + drawList->AddText(labelPos, labelColor, label); + + ImGui::PopID(); + + return pressed; +} + +inline bool RadioButton(const char* label, int* selection, int value, bool disabled) { + bool active = (*selection == value); + if (RadioButton(label, active, disabled)) { + *selection = value; + return true; + } + return false; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/lists.h b/src/ui/material/components/lists.h new file mode 100644 index 0000000..bc578ae --- /dev/null +++ b/src/ui/material/components/lists.h @@ -0,0 +1,306 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design List Component +// ============================================================================ +// Based on https://m2.material.io/components/lists +// +// Lists present content in a way that makes it easy to identify a specific +// item in a collection and act on it. + +/** + * @brief List item configuration + */ +struct ListItemSpec { + const char* leadingIcon = nullptr; // Optional leading icon (text representation) + const char* leadingAvatar = nullptr; // Optional avatar text (for initials) + ImU32 leadingAvatarColor = 0; // Avatar background color (0 = primary) + bool leadingCheckbox = false; // Show checkbox instead of icon + bool checkboxChecked = false; // Checkbox state + const char* primaryText = nullptr; // Main text (required) + const char* secondaryText = nullptr; // Secondary text (optional) + const char* trailingIcon = nullptr; // Optional trailing icon + const char* trailingText = nullptr; // Optional trailing metadata text + bool selected = false; // Selected state (highlight) + bool disabled = false; // Disabled state + bool dividerBelow = false; // Draw divider below item +}; + +/** + * @brief Begin a list container + * + * @param id Unique identifier + * @param withPadding Add top/bottom padding + */ +void BeginList(const char* id, bool withPadding = true); + +/** + * @brief End a list container + */ +void EndList(); + +/** + * @brief Render a list item + * + * @param spec Item configuration + * @return true if clicked + */ +bool ListItem(const ListItemSpec& spec); + +/** + * @brief Simple single-line list item + */ +bool ListItem(const char* text); + +/** + * @brief Two-line list item with primary and secondary text + */ +bool ListItem(const char* primary, const char* secondary); + +/** + * @brief List divider (full width or inset) + * + * @param inset If true, indented to align with text + */ +void ListDivider(bool inset = false); + +/** + * @brief List subheader text + */ +void ListSubheader(const char* text); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void BeginList(const char* id, bool withPadding) { + ImGui::PushID(id); + if (withPadding) { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp top padding + } +} + +inline void EndList() { + ImGui::PopID(); +} + +inline bool ListItem(const ListItemSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Calculate item height based on content + bool hasSecondary = (spec.secondaryText != nullptr); + bool hasLeadingElement = (spec.leadingIcon || spec.leadingAvatar || spec.leadingCheckbox); + + float itemHeight; + if (hasSecondary) { + itemHeight = size::ListItemTwoLineHeight; // 72dp for two-line + } else if (hasLeadingElement) { + itemHeight = size::ListItemHeight; // 56dp with leading element + } else { + itemHeight = 48.0f; // 48dp simple one-line + } + + // Item dimensions + ImVec2 pos = window->DC.CursorPos; + float itemWidth = ImGui::GetContentRegionAvail().x; + ImRect bb(pos, ImVec2(pos.x + itemWidth, pos.y + itemHeight)); + + // Interaction + ImGuiID itemId = window->GetID(spec.primaryText); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, itemId)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, itemId, &hovered, &held) && !spec.disabled; + + // Draw background + ImDrawList* drawList = window->DrawList; + ImU32 bgColor = 0; + + if (spec.selected) { + bgColor = PrimaryContainer(); + } else if (held && !spec.disabled) { + bgColor = schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25)); + } else if (hovered && !spec.disabled) { + bgColor = schema::UI().resolveColor("var(--active-overlay)", IM_COL32(255, 255, 255, 10)); + } + + if (bgColor) { + drawList->AddRectFilled(bb.Min, bb.Max, bgColor); + } + + // Layout positions + float leftPadding = spacing::dp(2); // 16dp left padding + float currentX = bb.Min.x + leftPadding; + float centerY = bb.Min.y + itemHeight * 0.5f; + + // Draw leading element + if (spec.leadingAvatar) { + // Avatar circle with text + float avatarRadius = 20.0f; // 40dp diameter + ImVec2 avatarCenter(currentX + avatarRadius, centerY); + + ImU32 avatarBg = spec.leadingAvatarColor ? spec.leadingAvatarColor : Primary(); + drawList->AddCircleFilled(avatarCenter, avatarRadius, avatarBg); + + // Avatar text (centered) + ImVec2 textSize = ImGui::CalcTextSize(spec.leadingAvatar); + ImVec2 textPos(avatarCenter.x - textSize.x * 0.5f, avatarCenter.y - textSize.y * 0.5f); + drawList->AddText(textPos, OnPrimary(), spec.leadingAvatar); + + currentX += 40.0f + spacing::dp(2); // 40dp avatar + 16dp gap + } else if (spec.leadingIcon) { + // Icon + ImVec2 iconSize = ImGui::CalcTextSize(spec.leadingIcon); + float iconY = centerY - iconSize.y * 0.5f; + ImU32 iconColor = spec.disabled ? OnSurfaceDisabled() : OnSurfaceMedium(); + drawList->AddText(ImVec2(currentX, iconY), iconColor, spec.leadingIcon); + currentX += 24.0f + spacing::dp(2); // 24dp icon + 16dp gap + } else if (spec.leadingCheckbox) { + // Checkbox (simplified visual) + float checkboxSize = 18.0f; + ImVec2 checkMin(currentX, centerY - checkboxSize * 0.5f); + ImVec2 checkMax(currentX + checkboxSize, centerY + checkboxSize * 0.5f); + + if (spec.checkboxChecked) { + drawList->AddRectFilled(checkMin, checkMax, Primary(), 2.0f); + // Checkmark + ImFont* iconFont = Typography::instance().iconSmall(); + ImVec2 chkSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, ICON_MD_CHECK); + drawList->AddText(iconFont, iconFont->LegacySize, + ImVec2(checkMin.x + (checkboxSize - chkSz.x) * 0.5f, checkMin.y + (checkboxSize - chkSz.y) * 0.5f), + OnPrimary(), ICON_MD_CHECK); + } else { + drawList->AddRect(checkMin, checkMax, OnSurfaceMedium(), 2.0f, 0, 2.0f); + } + + currentX += checkboxSize + spacing::dp(2); + } + + // Calculate text area + float rightPadding = spacing::dp(2); // 16dp right padding + float trailingSpace = 0; + if (spec.trailingIcon) trailingSpace += 24.0f + spacing::dp(1); + if (spec.trailingText) trailingSpace += ImGui::CalcTextSize(spec.trailingText).x + spacing::dp(1); + + float textMaxX = bb.Max.x - rightPadding - trailingSpace; + + // Draw text + ImU32 primaryColor = spec.disabled ? OnSurfaceDisabled() : OnSurface(); + ImU32 secondaryColor = spec.disabled ? OnSurfaceDisabled() : OnSurfaceMedium(); + + if (hasSecondary) { + // Two-line layout + float primaryY = bb.Min.y + 16.0f; + float secondaryY = primaryY + 20.0f; + + Typography::instance().pushFont(TypeStyle::Body1); + drawList->AddText(ImVec2(currentX, primaryY), primaryColor, spec.primaryText); + Typography::instance().popFont(); + + Typography::instance().pushFont(TypeStyle::Body2); + drawList->AddText(ImVec2(currentX, secondaryY), secondaryColor, spec.secondaryText); + Typography::instance().popFont(); + } else { + // Single-line layout + Typography::instance().pushFont(TypeStyle::Body1); + float textY = centerY - Typography::instance().getFont(TypeStyle::Body1)->FontSize * 0.5f; + drawList->AddText(ImVec2(currentX, textY), primaryColor, spec.primaryText); + Typography::instance().popFont(); + } + + // Draw trailing elements + float trailingX = bb.Max.x - rightPadding; + + if (spec.trailingText) { + ImVec2 textSize = ImGui::CalcTextSize(spec.trailingText); + trailingX -= textSize.x; + float textY = centerY - textSize.y * 0.5f; + drawList->AddText(ImVec2(trailingX, textY), secondaryColor, spec.trailingText); + trailingX -= spacing::dp(1); + } + + if (spec.trailingIcon) { + ImVec2 iconSize = ImGui::CalcTextSize(spec.trailingIcon); + trailingX -= 24.0f; + float iconY = centerY - iconSize.y * 0.5f; + drawList->AddText(ImVec2(trailingX, iconY), OnSurfaceMedium(), spec.trailingIcon); + } + + // Draw divider + if (spec.dividerBelow) { + float dividerY = bb.Max.y - 0.5f; + drawList->AddLine( + ImVec2(bb.Min.x + leftPadding, dividerY), + ImVec2(bb.Max.x, dividerY), + OnSurfaceDisabled() + ); + } + + return pressed; +} + +inline bool ListItem(const char* text) { + ListItemSpec spec; + spec.primaryText = text; + return ListItem(spec); +} + +inline bool ListItem(const char* primary, const char* secondary) { + ListItemSpec spec; + spec.primaryText = primary; + spec.secondaryText = secondary; + return ListItem(spec); +} + +inline void ListDivider(bool inset) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + float width = ImGui::GetContentRegionAvail().x; + float leftOffset = inset ? 72.0f : 0; // Align with text after avatar/icon + + ImVec2 pos = window->DC.CursorPos; + ImDrawList* drawList = window->DrawList; + + drawList->AddLine( + ImVec2(pos.x + leftOffset, pos.y), + ImVec2(pos.x + width, pos.y), + OnSurfaceDisabled() + ); + + ImGui::Dummy(ImVec2(width, 1.0f)); +} + +inline void ListSubheader(const char* text) { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp top padding + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + spacing::dp(2)); // 16dp left padding + Typography::instance().textColored(TypeStyle::Caption, Primary(), text); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp bottom padding +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/nav_drawer.h b/src/ui/material/components/nav_drawer.h new file mode 100644 index 0000000..83f0c21 --- /dev/null +++ b/src/ui/material/components/nav_drawer.h @@ -0,0 +1,379 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Navigation Drawer Component +// ============================================================================ +// Based on https://m2.material.io/components/navigation-drawer +// +// Navigation drawers provide access to destinations in your app. + +enum class NavDrawerType { + Standard, // Permanent, always visible + Modal, // Overlay with scrim, can be dismissed + Dismissible // Can be shown/hidden, no scrim +}; + +/** + * @brief Navigation drawer configuration + */ +struct NavDrawerSpec { + NavDrawerType type = NavDrawerType::Standard; + float width = 256.0f; // 256dp standard width + bool showDividerBottom = true; // Divider at bottom + const char* headerTitle = nullptr; // Optional header title + const char* headerSubtitle = nullptr; +}; + +/** + * @brief Navigation item configuration + */ +struct NavItemSpec { + const char* icon = nullptr; // Leading icon + const char* label = nullptr; // Item label (required) + bool selected = false; // Selected state + bool disabled = false; + int badgeCount = 0; // Badge (0 = no badge) +}; + +/** + * @brief Begin a navigation drawer + * + * @param id Unique identifier + * @param open Pointer to open state (for modal/dismissible) + * @param spec Drawer configuration + * @return true if drawer is visible + */ +bool BeginNavDrawer(const char* id, bool* open, const NavDrawerSpec& spec = NavDrawerSpec()); + +/** + * @brief Begin standard (always visible) navigation drawer + */ +bool BeginNavDrawer(const char* id, const NavDrawerSpec& spec = NavDrawerSpec()); + +/** + * @brief End navigation drawer + */ +void EndNavDrawer(); + +/** + * @brief Render a navigation item + * + * @param spec Item configuration + * @return true if clicked + */ +bool NavItem(const NavItemSpec& spec); + +/** + * @brief Simple navigation item + */ +bool NavItem(const char* icon, const char* label, bool selected = false); + +/** + * @brief Navigation divider + */ +void NavDivider(); + +/** + * @brief Navigation subheader + */ +void NavSubheader(const char* text); + +// ============================================================================ +// Implementation +// ============================================================================ + +struct NavDrawerState { + float width; + ImVec2 contentMin; + ImVec2 contentMax; + bool isModal; +}; + +static NavDrawerState g_navDrawerState; + +inline bool BeginNavDrawer(const char* id, bool* open, const NavDrawerSpec& spec) { + // For modal drawers, check open state + if (spec.type == NavDrawerType::Modal && !*open) { + return false; + } + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(id); + + g_navDrawerState.width = spec.width; + g_navDrawerState.isModal = (spec.type == NavDrawerType::Modal); + + ImGuiIO& io = ImGui::GetIO(); + ImDrawList* drawList = window->DrawList; + + // For modal, draw scrim and handle dismiss + if (spec.type == NavDrawerType::Modal) { + ImDrawList* bgDrawList = ImGui::GetBackgroundDrawList(); + bgDrawList->AddRectFilled( + ImVec2(0, 0), io.DisplaySize, + schema::UI().resolveColor("var(--scrim)", IM_COL32(0, 0, 0, (int)(0.32f * 255))) + ); + + // Click outside to dismiss + if (ImGui::IsMouseClicked(0)) { + ImVec2 mousePos = io.MousePos; + if (mousePos.x > spec.width) { + *open = false; + } + } + } + + // Drawer position and size + ImVec2 drawerPos(0, 0); + ImVec2 drawerSize(spec.width, io.DisplaySize.y); + + // If not modal, account for app bar + if (spec.type != NavDrawerType::Modal) { + drawerPos.y = size::AppBarHeight; + drawerSize.y = io.DisplaySize.y - size::AppBarHeight; + } + + ImRect drawerBB(drawerPos, ImVec2(drawerPos.x + drawerSize.x, drawerPos.y + drawerSize.y)); + + // Draw drawer background + ImU32 bgColor = Surface(Elevation::Dp16); + drawList->AddRectFilled(drawerBB.Min, drawerBB.Max, bgColor); + + // Store content region + g_navDrawerState.contentMin = ImVec2(drawerBB.Min.x, drawerBB.Min.y); + g_navDrawerState.contentMax = drawerBB.Max; + + // Header + float currentY = drawerBB.Min.y; + + if (spec.headerTitle || spec.headerSubtitle) { + // Header area (optional) + float headerHeight = 64.0f; + + ImVec2 headerMin(drawerBB.Min.x, currentY); + ImVec2 headerMax(drawerBB.Max.x, currentY + headerHeight); + + // Header background (slightly elevated) + drawList->AddRectFilled(headerMin, headerMax, Surface(Elevation::Dp16)); + + // Header title + if (spec.headerTitle) { + ImGui::SetCursorScreenPos(ImVec2(drawerBB.Min.x + spacing::dp(2), currentY + 20.0f)); + Typography::instance().text(TypeStyle::H6, spec.headerTitle); + } + + if (spec.headerSubtitle) { + ImGui::SetCursorScreenPos(ImVec2(drawerBB.Min.x + spacing::dp(2), currentY + 42.0f)); + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), spec.headerSubtitle); + } + + currentY += headerHeight; + + // Divider under header + drawList->AddLine( + ImVec2(drawerBB.Min.x, currentY), + ImVec2(drawerBB.Max.x, currentY), + OnSurfaceDisabled() + ); + } + + // Set cursor for nav items + ImGui::SetCursorScreenPos(ImVec2(drawerBB.Min.x, currentY + spacing::dp(1))); + ImGui::BeginGroup(); + + return true; +} + +inline bool BeginNavDrawer(const char* id, const NavDrawerSpec& spec) { + static bool alwaysOpen = true; + NavDrawerSpec standardSpec = spec; + standardSpec.type = NavDrawerType::Standard; + return BeginNavDrawer(id, &alwaysOpen, standardSpec); +} + +inline void EndNavDrawer() { + ImGui::EndGroup(); + + // Divider at bottom if configured + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImDrawList* drawList = window->DrawList; + + // Right edge divider + drawList->AddLine( + ImVec2(g_navDrawerState.contentMax.x - 1, g_navDrawerState.contentMin.y), + ImVec2(g_navDrawerState.contentMax.x - 1, g_navDrawerState.contentMax.y), + OnSurfaceDisabled() + ); + + ImGui::PopID(); +} + +inline bool NavItem(const NavItemSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(spec.label); + + // Item dimensions + const float itemHeight = 48.0f; + const float iconSize = 24.0f; + const float horizontalPadding = spacing::dp(2); // 16dp + const float iconLabelGap = spacing::dp(4); // 32dp from left edge to label + + float itemWidth = g_navDrawerState.width - spacing::dp(1); // 8dp margin right + + ImVec2 pos = window->DC.CursorPos; + pos.x += spacing::dp(1); // 8dp margin left + + ImRect itemBB(pos, ImVec2(pos.x + itemWidth, pos.y + itemHeight)); + + // Interaction + ImGuiID id = window->GetID("##navitem"); + ImGui::ItemSize(ImRect(window->DC.CursorPos, ImVec2(window->DC.CursorPos.x + g_navDrawerState.width, window->DC.CursorPos.y + itemHeight))); + if (!ImGui::ItemAdd(itemBB, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(itemBB, id, &hovered, &held) && !spec.disabled; + + // Draw background + ImDrawList* drawList = window->DrawList; + + ImU32 bgColor = 0; + if (spec.selected) { + bgColor = WithAlpha(Primary(), 30); // Primary at ~12% + } else if (held && !spec.disabled) { + bgColor = schema::UI().resolveColor("var(--sidebar-hover)", IM_COL32(255, 255, 255, 25)); + } else if (hovered && !spec.disabled) { + bgColor = schema::UI().resolveColor("var(--active-overlay)", IM_COL32(255, 255, 255, 10)); + } + + if (bgColor) { + drawList->AddRectFilled(itemBB.Min, itemBB.Max, bgColor, size::ButtonCornerRadius); + } + + // Selected indicator (left edge) + if (spec.selected) { + drawList->AddRectFilled( + ImVec2(itemBB.Min.x, itemBB.Min.y + 8.0f), + ImVec2(itemBB.Min.x + 4.0f, itemBB.Max.y - 8.0f), + Primary(), 2.0f + ); + } + + // Content + float contentX = pos.x + horizontalPadding; + float centerY = pos.y + itemHeight * 0.5f; + + ImU32 iconColor = spec.disabled ? OnSurfaceDisabled() : + spec.selected ? Primary() : OnSurfaceMedium(); + ImU32 labelColor = spec.disabled ? OnSurfaceDisabled() : + spec.selected ? Primary() : OnSurface(); + + // Icon + if (spec.icon) { + drawList->AddText( + ImVec2(contentX, centerY - iconSize * 0.5f), + iconColor, spec.icon + ); + contentX += iconSize + spacing::dp(2); // 16dp gap after icon + } + + // Label + Typography::instance().pushFont(TypeStyle::Body1); + float labelY = centerY - ImGui::GetFontSize() * 0.5f; + drawList->AddText(ImVec2(contentX, labelY), labelColor, spec.label); + Typography::instance().popFont(); + + // Badge + if (spec.badgeCount > 0) { + char badgeText[8]; + if (spec.badgeCount > 999) { + snprintf(badgeText, sizeof(badgeText), "999+"); + } else { + snprintf(badgeText, sizeof(badgeText), "%d", spec.badgeCount); + } + + ImVec2 badgeSize = ImGui::CalcTextSize(badgeText); + float badgeWidth = ImMax(24.0f, badgeSize.x + 12.0f); + float badgeHeight = 20.0f; + float badgeX = itemBB.Max.x - horizontalPadding - badgeWidth; + float badgeY = centerY - badgeHeight * 0.5f; + + drawList->AddRectFilled( + ImVec2(badgeX, badgeY), + ImVec2(badgeX + badgeWidth, badgeY + badgeHeight), + Primary(), badgeHeight * 0.5f + ); + + Typography::instance().pushFont(TypeStyle::Caption); + ImVec2 textPos(badgeX + (badgeWidth - badgeSize.x) * 0.5f, badgeY + (badgeHeight - badgeSize.y) * 0.5f); + drawList->AddText(textPos, OnPrimary(), badgeText); + Typography::instance().popFont(); + } + + ImGui::PopID(); + + return pressed; +} + +inline bool NavItem(const char* icon, const char* label, bool selected) { + NavItemSpec spec; + spec.icon = icon; + spec.label = label; + spec.selected = selected; + return NavItem(spec); +} + +inline void NavDivider() { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + ImVec2 pos = window->DC.CursorPos; + ImDrawList* drawList = window->DrawList; + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp spacing above + + drawList->AddLine( + ImVec2(pos.x + spacing::dp(2), pos.y + spacing::dp(1)), + ImVec2(pos.x + g_navDrawerState.width - spacing::dp(2), pos.y + spacing::dp(1)), + OnSurfaceDisabled() + ); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp spacing below +} + +inline void NavSubheader(const char* text) { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp above + + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::SetCursorScreenPos(ImVec2(pos.x + spacing::dp(2), pos.y)); + + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), text); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); // 8dp below +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/progress.h b/src/ui/material/components/progress.h new file mode 100644 index 0000000..6948632 --- /dev/null +++ b/src/ui/material/components/progress.h @@ -0,0 +1,303 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Progress Indicators +// ============================================================================ +// Based on https://m2.material.io/components/progress-indicators +// +// Progress indicators express an unspecified wait time or display the length +// of a process. + +// ============================================================================ +// Linear Progress +// ============================================================================ + +/** + * @brief Determinate linear progress bar + * + * @param fraction Progress value 0.0 to 1.0 + * @param width Width of bar (0 = full available width) + */ +void LinearProgress(float fraction, float width = 0); + +/** + * @brief Indeterminate linear progress bar (animated) + * + * @param width Width of bar (0 = full available width) + */ +void LinearProgressIndeterminate(float width = 0); + +/** + * @brief Buffer linear progress bar + * + * @param fraction Primary progress 0.0 to 1.0 + * @param buffer Buffer progress 0.0 to 1.0 + * @param width Width of bar (0 = full available width) + */ +void LinearProgressBuffer(float fraction, float buffer, float width = 0); + +// ============================================================================ +// Circular Progress +// ============================================================================ + +/** + * @brief Determinate circular progress indicator + * + * @param fraction Progress value 0.0 to 1.0 + * @param radius Radius of circle (default 20dp) + */ +void CircularProgress(float fraction, float radius = 20.0f); + +/** + * @brief Indeterminate circular progress (spinner) + * + * @param radius Radius of circle (default 20dp) + */ +void CircularProgressIndeterminate(float radius = 20.0f); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void LinearProgress(float fraction, float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const float barHeight = 4.0f; // Material spec: 4dp height + float barWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + barWidth, pos.y + barHeight)); + + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList* drawList = window->DrawList; + + // Track (background) + ImU32 trackColor = WithAlpha(Primary(), 64); // Primary at 25% + drawList->AddRectFilled(bb.Min, bb.Max, trackColor, 0); + + // Progress indicator + float progressWidth = barWidth * ImClamp(fraction, 0.0f, 1.0f); + if (progressWidth > 0) { + drawList->AddRectFilled( + bb.Min, + ImVec2(bb.Min.x + progressWidth, bb.Max.y), + Primary(), 0 + ); + } +} + +inline void LinearProgressIndeterminate(float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const float barHeight = 4.0f; + float barWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + barWidth, pos.y + barHeight)); + + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList* drawList = window->DrawList; + + // Track + ImU32 trackColor = WithAlpha(Primary(), 64); + drawList->AddRectFilled(bb.Min, bb.Max, trackColor, 0); + + // Animated indicator - sliding back and forth + float time = (float)ImGui::GetTime(); + float cycleTime = fmodf(time, 2.0f); // 2 second cycle + + // Two bars: primary and secondary with different phases + float indicatorWidth = barWidth * 0.3f; // 30% of track + + // Primary indicator + float primaryPhase = fmodf(time * 1.2f, 2.0f); + float primaryPos; + if (primaryPhase < 1.0f) { + // Accelerating from left + primaryPos = primaryPhase * primaryPhase * (barWidth + indicatorWidth) - indicatorWidth; + } else { + // Continue off right (reset happens at 2.0) + primaryPos = (2.0f - primaryPhase) * (2.0f - primaryPhase) * -(barWidth + indicatorWidth) + barWidth; + } + + float primaryStart = ImMax(bb.Min.x, bb.Min.x + primaryPos); + float primaryEnd = ImMin(bb.Max.x, bb.Min.x + primaryPos + indicatorWidth); + + if (primaryEnd > primaryStart) { + drawList->AddRectFilled( + ImVec2(primaryStart, bb.Min.y), + ImVec2(primaryEnd, bb.Max.y), + Primary(), 0 + ); + } +} + +inline void LinearProgressBuffer(float fraction, float buffer, float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const float barHeight = 4.0f; + float barWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + barWidth, pos.y + barHeight)); + + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList* drawList = window->DrawList; + + // Track + ImU32 trackColor = WithAlpha(Primary(), 38); // Primary at 15% + drawList->AddRectFilled(bb.Min, bb.Max, trackColor, 0); + + // Buffer (lighter than progress) + float bufferWidth = barWidth * ImClamp(buffer, 0.0f, 1.0f); + if (bufferWidth > 0) { + drawList->AddRectFilled( + bb.Min, + ImVec2(bb.Min.x + bufferWidth, bb.Max.y), + WithAlpha(Primary(), 102), 0 // Primary at 40% + ); + } + + // Progress + float progressWidth = barWidth * ImClamp(fraction, 0.0f, 1.0f); + if (progressWidth > 0) { + drawList->AddRectFilled( + bb.Min, + ImVec2(bb.Min.x + progressWidth, bb.Max.y), + Primary(), 0 + ); + } +} + +inline void CircularProgress(float fraction, float radius) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const float thickness = 4.0f; // Stroke width + float diameter = radius * 2; + + ImVec2 pos = window->DC.CursorPos; + ImVec2 center(pos.x + radius, pos.y + radius); + ImRect bb(pos, ImVec2(pos.x + diameter, pos.y + diameter)); + + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList* drawList = window->DrawList; + + // Track circle + ImU32 trackColor = WithAlpha(Primary(), 64); + drawList->AddCircle(center, radius - thickness * 0.5f, trackColor, 0, thickness); + + // Progress arc + float clampedFraction = ImClamp(fraction, 0.0f, 1.0f); + if (clampedFraction > 0) { + float startAngle = -IM_PI * 0.5f; // Start at top (12 o'clock) + float endAngle = startAngle + IM_PI * 2.0f * clampedFraction; + + // Draw arc as line segments + const int segments = (int)(32 * clampedFraction) + 1; + float angleStep = (endAngle - startAngle) / segments; + + for (int i = 0; i < segments; i++) { + float a1 = startAngle + angleStep * i; + float a2 = startAngle + angleStep * (i + 1); + + ImVec2 p1(center.x + cosf(a1) * (radius - thickness * 0.5f), + center.y + sinf(a1) * (radius - thickness * 0.5f)); + ImVec2 p2(center.x + cosf(a2) * (radius - thickness * 0.5f), + center.y + sinf(a2) * (radius - thickness * 0.5f)); + + drawList->AddLine(p1, p2, Primary(), thickness); + } + } +} + +inline void CircularProgressIndeterminate(float radius) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const float thickness = 4.0f; + float diameter = radius * 2; + + ImVec2 pos = window->DC.CursorPos; + ImVec2 center(pos.x + radius, pos.y + radius); + ImRect bb(pos, ImVec2(pos.x + diameter, pos.y + diameter)); + + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList* drawList = window->DrawList; + + float time = (float)ImGui::GetTime(); + + // Rotation animation + float rotation = fmodf(time * 2.0f * IM_PI / 1.4f, IM_PI * 2.0f); // ~1.4s rotation + + // Arc length animation (grows and shrinks) + float cycleTime = fmodf(time, 1.333f); // ~1.333s cycle + float arcLength; + if (cycleTime < 0.666f) { + // Growing phase + arcLength = (cycleTime / 0.666f) * 0.75f + 0.1f; // 10% to 85% + } else { + // Shrinking phase + arcLength = ((1.333f - cycleTime) / 0.666f) * 0.75f + 0.1f; + } + + float startAngle = rotation - IM_PI * 0.5f; + float endAngle = startAngle + IM_PI * 2.0f * arcLength; + + // Draw arc + const int segments = (int)(32 * arcLength) + 1; + float angleStep = (endAngle - startAngle) / segments; + + for (int i = 0; i < segments; i++) { + float a1 = startAngle + angleStep * i; + float a2 = startAngle + angleStep * (i + 1); + + ImVec2 p1(center.x + cosf(a1) * (radius - thickness * 0.5f), + center.y + sinf(a1) * (radius - thickness * 0.5f)); + ImVec2 p2(center.x + cosf(a2) * (radius - thickness * 0.5f), + center.y + sinf(a2) * (radius - thickness * 0.5f)); + + drawList->AddLine(p1, p2, Primary(), thickness); + } +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/slider.h b/src/ui/material/components/slider.h new file mode 100644 index 0000000..55a02de --- /dev/null +++ b/src/ui/material/components/slider.h @@ -0,0 +1,402 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Slider Component +// ============================================================================ +// Based on https://m2.material.io/components/sliders +// +// Sliders allow users to make selections from a range of values. + +/** + * @brief Continuous slider + * + * @param label Label for the slider (hidden, used for ID) + * @param value Pointer to current value + * @param minValue Minimum value + * @param maxValue Maximum value + * @param format Printf format for value display (nullptr = no display) + * @param width Slider width (0 = full available) + * @return true if value changed + */ +bool Slider(const char* label, float* value, float minValue, float maxValue, + const char* format = nullptr, float width = 0); + +/** + * @brief Integer slider + */ +bool SliderInt(const char* label, int* value, int minValue, int maxValue, + const char* format = nullptr, float width = 0); + +/** + * @brief Discrete slider with steps + * + * @param label Label for the slider + * @param value Pointer to current value + * @param minValue Minimum value + * @param maxValue Maximum value + * @param step Step size + * @param showTicks Show tick marks + * @return true if value changed + */ +bool SliderDiscrete(const char* label, float* value, float minValue, float maxValue, + float step, bool showTicks = true, float width = 0); + +/** + * @brief Range slider (two thumbs) + * + * @param label Label for the slider + * @param minVal Pointer to range minimum + * @param maxVal Pointer to range maximum + * @param rangeMin Allowed minimum + * @param rangeMax Allowed maximum + * @return true if either value changed + */ +bool SliderRange(const char* label, float* minVal, float* maxVal, + float rangeMin, float rangeMax, float width = 0); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool Slider(const char* label, float* value, float minValue, float maxValue, + const char* format, float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + // Slider dimensions + const float trackHeight = 4.0f; + const float thumbRadius = 10.0f; // 20dp diameter + float sliderWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + float totalHeight = size::TouchTarget; // 48dp touch target + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + sliderWidth, pos.y + totalHeight)); + + // Item interaction + ImGuiID id = window->GetID("##slider"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); + + // Calculate thumb position + float trackLeft = pos.x + thumbRadius; + float trackRight = pos.x + sliderWidth - thumbRadius; + float trackWidth = trackRight - trackLeft; + float centerY = pos.y + totalHeight * 0.5f; + + float fraction = (*value - minValue) / (maxValue - minValue); + fraction = ImClamp(fraction, 0.0f, 1.0f); + float thumbX = trackLeft + trackWidth * fraction; + + // Handle dragging + bool changed = false; + if (held) { + float mouseX = ImGui::GetIO().MousePos.x; + float newFraction = (mouseX - trackLeft) / trackWidth; + newFraction = ImClamp(newFraction, 0.0f, 1.0f); + float newValue = minValue + newFraction * (maxValue - minValue); + + if (newValue != *value) { + *value = newValue; + changed = true; + } + thumbX = trackLeft + trackWidth * newFraction; + } + + // Draw + ImDrawList* drawList = window->DrawList; + + // Track (inactive part) + ImU32 trackInactiveColor = WithAlpha(Primary(), 64); // Primary at 25% + drawList->AddRectFilled( + ImVec2(trackLeft, centerY - trackHeight * 0.5f), + ImVec2(trackRight, centerY + trackHeight * 0.5f), + trackInactiveColor, trackHeight * 0.5f + ); + + // Track (active part) + drawList->AddRectFilled( + ImVec2(trackLeft, centerY - trackHeight * 0.5f), + ImVec2(thumbX, centerY + trackHeight * 0.5f), + Primary(), trackHeight * 0.5f + ); + + // Thumb shadow + drawList->AddCircleFilled(ImVec2(thumbX + 1, centerY + 2), thumbRadius, schema::UI().resolveColor("var(--control-shadow)", IM_COL32(0, 0, 0, 60))); + + // Thumb + drawList->AddCircleFilled(ImVec2(thumbX, centerY), thumbRadius, Primary()); + + // Hover/pressed ripple + if (hovered || held) { + ImU32 rippleColor = WithAlpha(Primary(), held ? 51 : 25); + drawList->AddCircleFilled(ImVec2(thumbX, centerY), thumbRadius + 12.0f, rippleColor); + } + + // Value label (when held) + if (held && format) { + char valueText[64]; + snprintf(valueText, sizeof(valueText), format, *value); + + ImVec2 textSize = ImGui::CalcTextSize(valueText); + float labelY = centerY - thumbRadius - 32.0f; + float labelX = thumbX - textSize.x * 0.5f; + + // Label background (rounded rectangle) + float labelPadX = 8.0f; + float labelPadY = 4.0f; + ImVec2 labelMin(labelX - labelPadX, labelY - labelPadY); + ImVec2 labelMax(labelX + textSize.x + labelPadX, labelY + textSize.y + labelPadY); + + drawList->AddRectFilled(labelMin, labelMax, Primary(), 4.0f); + drawList->AddText(ImVec2(labelX, labelY), OnPrimary(), valueText); + } + + ImGui::PopID(); + + return changed; +} + +inline bool SliderInt(const char* label, int* value, int minValue, int maxValue, + const char* format, float width) { + float floatVal = (float)*value; + bool changed = Slider(label, &floatVal, (float)minValue, (float)maxValue, format, width); + if (changed) { + *value = (int)roundf(floatVal); + } + return changed; +} + +inline bool SliderDiscrete(const char* label, float* value, float minValue, float maxValue, + float step, bool showTicks, float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + const float trackHeight = 4.0f; + const float thumbRadius = 10.0f; + const float tickRadius = 2.0f; + float sliderWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + float totalHeight = size::TouchTarget; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + sliderWidth, pos.y + totalHeight)); + + ImGuiID id = window->GetID("##slider"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + ImGui::ButtonBehavior(bb, id, &hovered, &held); + + float trackLeft = pos.x + thumbRadius; + float trackRight = pos.x + sliderWidth - thumbRadius; + float trackWidth = trackRight - trackLeft; + float centerY = pos.y + totalHeight * 0.5f; + + // Snap to step + float snappedValue = roundf((*value - minValue) / step) * step + minValue; + snappedValue = ImClamp(snappedValue, minValue, maxValue); + + float fraction = (snappedValue - minValue) / (maxValue - minValue); + float thumbX = trackLeft + trackWidth * fraction; + + bool changed = false; + if (held) { + float mouseX = ImGui::GetIO().MousePos.x; + float newFraction = (mouseX - trackLeft) / trackWidth; + newFraction = ImClamp(newFraction, 0.0f, 1.0f); + float rawValue = minValue + newFraction * (maxValue - minValue); + float newValue = roundf((rawValue - minValue) / step) * step + minValue; + newValue = ImClamp(newValue, minValue, maxValue); + + if (newValue != *value) { + *value = newValue; + changed = true; + } + fraction = (newValue - minValue) / (maxValue - minValue); + thumbX = trackLeft + trackWidth * fraction; + } + + ImDrawList* drawList = window->DrawList; + + // Track + drawList->AddRectFilled( + ImVec2(trackLeft, centerY - trackHeight * 0.5f), + ImVec2(trackRight, centerY + trackHeight * 0.5f), + WithAlpha(Primary(), 64), trackHeight * 0.5f + ); + + drawList->AddRectFilled( + ImVec2(trackLeft, centerY - trackHeight * 0.5f), + ImVec2(thumbX, centerY + trackHeight * 0.5f), + Primary(), trackHeight * 0.5f + ); + + // Tick marks + if (showTicks) { + int numSteps = (int)((maxValue - minValue) / step); + for (int i = 0; i <= numSteps; i++) { + float tickFraction = (float)i / numSteps; + float tickX = trackLeft + trackWidth * tickFraction; + + ImU32 tickColor = (tickX <= thumbX) ? OnPrimary() : WithAlpha(Primary(), 128); + drawList->AddCircleFilled(ImVec2(tickX, centerY), tickRadius, tickColor); + } + } + + // Thumb + drawList->AddCircleFilled(ImVec2(thumbX + 1, centerY + 2), thumbRadius, schema::UI().resolveColor("var(--control-shadow)", IM_COL32(0, 0, 0, 60))); + drawList->AddCircleFilled(ImVec2(thumbX, centerY), thumbRadius, Primary()); + + if (hovered || held) { + ImU32 rippleColor = WithAlpha(Primary(), held ? 51 : 25); + drawList->AddCircleFilled(ImVec2(thumbX, centerY), thumbRadius + 12.0f, rippleColor); + } + + ImGui::PopID(); + + return changed; +} + +inline bool SliderRange(const char* label, float* minVal, float* maxVal, + float rangeMin, float rangeMax, float width) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(label); + + const float trackHeight = 4.0f; + const float thumbRadius = 10.0f; + float sliderWidth = width > 0 ? width : ImGui::GetContentRegionAvail().x; + float totalHeight = size::TouchTarget; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + sliderWidth, pos.y + totalHeight)); + + ImGuiID id = window->GetID("##slider"); + ImGui::ItemSize(bb); + if (!ImGui::ItemAdd(bb, id)) + return false; + + float trackLeft = pos.x + thumbRadius; + float trackRight = pos.x + sliderWidth - thumbRadius; + float trackWidth = trackRight - trackLeft; + float centerY = pos.y + totalHeight * 0.5f; + + float minFraction = (*minVal - rangeMin) / (rangeMax - rangeMin); + float maxFraction = (*maxVal - rangeMin) / (rangeMax - rangeMin); + float minThumbX = trackLeft + trackWidth * minFraction; + float maxThumbX = trackLeft + trackWidth * maxFraction; + + // Hit test both thumbs + ImVec2 mousePos = ImGui::GetIO().MousePos; + float distToMin = fabsf(mousePos.x - minThumbX); + float distToMax = fabsf(mousePos.x - maxThumbX); + bool nearMin = distToMin < distToMax; + + ImGuiID minId = window->GetID("##min"); + ImGuiID maxId = window->GetID("##max"); + + bool minHovered, minHeld; + bool maxHovered, maxHeld; + ImRect minHitBox(ImVec2(minThumbX - thumbRadius - 8, centerY - thumbRadius - 8), + ImVec2(minThumbX + thumbRadius + 8, centerY + thumbRadius + 8)); + ImRect maxHitBox(ImVec2(maxThumbX - thumbRadius - 8, centerY - thumbRadius - 8), + ImVec2(maxThumbX + thumbRadius + 8, centerY + thumbRadius + 8)); + + ImGui::ButtonBehavior(nearMin ? minHitBox : maxHitBox, nearMin ? minId : maxId, + nearMin ? &minHovered : &maxHovered, + nearMin ? &minHeld : &maxHeld); + + bool changed = false; + + if (minHeld) { + float newFraction = (mousePos.x - trackLeft) / trackWidth; + newFraction = ImClamp(newFraction, 0.0f, maxFraction - 0.01f); + float newValue = rangeMin + newFraction * (rangeMax - rangeMin); + if (newValue != *minVal) { + *minVal = newValue; + changed = true; + } + minThumbX = trackLeft + trackWidth * newFraction; + } + + if (maxHeld) { + float newFraction = (mousePos.x - trackLeft) / trackWidth; + newFraction = ImClamp(newFraction, minFraction + 0.01f, 1.0f); + float newValue = rangeMin + newFraction * (rangeMax - rangeMin); + if (newValue != *maxVal) { + *maxVal = newValue; + changed = true; + } + maxThumbX = trackLeft + trackWidth * newFraction; + } + + ImDrawList* drawList = window->DrawList; + + // Inactive track + drawList->AddRectFilled( + ImVec2(trackLeft, centerY - trackHeight * 0.5f), + ImVec2(trackRight, centerY + trackHeight * 0.5f), + WithAlpha(Primary(), 64), trackHeight * 0.5f + ); + + // Active track (between thumbs) + drawList->AddRectFilled( + ImVec2(minThumbX, centerY - trackHeight * 0.5f), + ImVec2(maxThumbX, centerY + trackHeight * 0.5f), + Primary(), trackHeight * 0.5f + ); + + // Min thumb + drawList->AddCircleFilled(ImVec2(minThumbX + 1, centerY + 2), thumbRadius, schema::UI().resolveColor("var(--control-shadow)", IM_COL32(0, 0, 0, 60))); + drawList->AddCircleFilled(ImVec2(minThumbX, centerY), thumbRadius, Primary()); + + if (minHovered || minHeld) { + ImU32 rippleColor = WithAlpha(Primary(), minHeld ? 51 : 25); + drawList->AddCircleFilled(ImVec2(minThumbX, centerY), thumbRadius + 12.0f, rippleColor); + } + + // Max thumb + drawList->AddCircleFilled(ImVec2(maxThumbX + 1, centerY + 2), thumbRadius, schema::UI().resolveColor("var(--control-shadow)", IM_COL32(0, 0, 0, 60))); + drawList->AddCircleFilled(ImVec2(maxThumbX, centerY), thumbRadius, Primary()); + + if (maxHovered || maxHeld) { + ImU32 rippleColor = WithAlpha(Primary(), maxHeld ? 51 : 25); + drawList->AddCircleFilled(ImVec2(maxThumbX, centerY), thumbRadius + 12.0f, rippleColor); + } + + ImGui::PopID(); + + return changed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/snackbar.h b/src/ui/material/components/snackbar.h new file mode 100644 index 0000000..b31b425 --- /dev/null +++ b/src/ui/material/components/snackbar.h @@ -0,0 +1,242 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "../draw_helpers.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Snackbar Component +// ============================================================================ +// Based on https://m2.material.io/components/snackbars +// +// Snackbars provide brief messages about app processes at the bottom of the +// screen. They can include a single action. + +/** + * @brief Snackbar configuration + */ +struct SnackbarSpec { + const char* message = nullptr; // Message text + const char* actionText = nullptr; // Optional action button text + float duration = 4.0f; // Duration in seconds (0 = indefinite) + bool multiLine = false; // Allow multi-line message +}; + +/** + * @brief Snackbar manager for showing notifications + */ +class Snackbar { +public: + static Snackbar& instance(); + + /** + * @brief Show a snackbar message + * + * @param message Message text + * @param actionText Optional action text + * @param duration Display duration (0 = until dismissed) + */ + void show(const char* message, const char* actionText = nullptr, float duration = 4.0f); + + /** + * @brief Show a snackbar with full configuration + */ + void show(const SnackbarSpec& spec); + + /** + * @brief Dismiss current snackbar + */ + void dismiss(); + + /** + * @brief Render snackbar (call each frame) + * + * @return true if action was clicked + */ + bool render(); + + /** + * @brief Check if snackbar is visible + */ + bool isVisible() const { return m_visible; } + +private: + Snackbar() = default; + + bool m_visible = false; + SnackbarSpec m_currentSpec; + float m_showTime = 0; + float m_animProgress = 0; // 0 = hidden, 1 = fully shown +}; + +// ============================================================================ +// Convenience Functions +// ============================================================================ + +/** + * @brief Show a snackbar message + */ +inline void ShowSnackbar(const char* message, const char* action = nullptr, float duration = 4.0f) { + Snackbar::instance().show(message, action, duration); +} + +/** + * @brief Dismiss current snackbar + */ +inline void DismissSnackbar() { + Snackbar::instance().dismiss(); +} + +/** + * @brief Render snackbar system (call once per frame in main render loop) + * + * @return true if action was clicked + */ +inline bool RenderSnackbar() { + return Snackbar::instance().render(); +} + +// ============================================================================ +// Implementation +// ============================================================================ + +inline Snackbar& Snackbar::instance() { + static Snackbar s_instance; + return s_instance; +} + +inline void Snackbar::show(const char* message, const char* actionText, float duration) { + SnackbarSpec spec; + spec.message = message; + spec.actionText = actionText; + spec.duration = duration; + show(spec); +} + +inline void Snackbar::show(const SnackbarSpec& spec) { + m_currentSpec = spec; + m_visible = true; + m_showTime = (float)ImGui::GetTime(); + m_animProgress = 0; +} + +inline void Snackbar::dismiss() { + m_visible = false; +} + +inline bool Snackbar::render() { + if (!m_visible && m_animProgress <= 0) + return false; + + bool actionClicked = false; + float currentTime = (float)ImGui::GetTime(); + + // Check auto-dismiss + if (m_visible && m_currentSpec.duration > 0) { + if (currentTime - m_showTime > m_currentSpec.duration) { + m_visible = false; + } + } + + // Animate in/out + float animTarget = m_visible ? 1.0f : 0.0f; + float animSpeed = 8.0f; // Animation speed + if (m_animProgress < animTarget) { + m_animProgress = ImMin(m_animProgress + ImGui::GetIO().DeltaTime * animSpeed, animTarget); + } else if (m_animProgress > animTarget) { + m_animProgress = ImMax(m_animProgress - ImGui::GetIO().DeltaTime * animSpeed, animTarget); + } + + if (m_animProgress <= 0) + return false; + + // Snackbar dimensions + const float snackbarHeight = m_currentSpec.multiLine ? 68.0f : 48.0f; + const float snackbarMinWidth = 344.0f; + const float snackbarMaxWidth = 672.0f; + const float margin = spacing::dp(3); // 24dp from edges + + ImGuiIO& io = ImGui::GetIO(); + + // Calculate width based on content + float messageWidth = ImGui::CalcTextSize(m_currentSpec.message).x; + float actionWidth = m_currentSpec.actionText ? + ImGui::CalcTextSize(m_currentSpec.actionText).x + spacing::dp(2) : 0; + float contentWidth = messageWidth + actionWidth + spacing::dp(4); // 32dp padding + float snackbarWidth = ImClamp(contentWidth, snackbarMinWidth, snackbarMaxWidth); + + // Position at bottom center + float bottomY = io.DisplaySize.y - margin - snackbarHeight; + float slideOffset = (1.0f - m_animProgress) * (snackbarHeight + margin); + + ImVec2 snackbarPos( + (io.DisplaySize.x - snackbarWidth) * 0.5f, + bottomY + slideOffset + ); + + // Draw snackbar + ImDrawList* drawList = ImGui::GetForegroundDrawList(); + + // Background (elevation dp6 equivalent) + ImU32 snackBg = schema::UI().resolveColor("var(--snackbar-bg)", IM_COL32(50, 50, 50, 255)); + ImU32 bgColor = ScaleAlpha(snackBg, m_animProgress); + ImVec2 snackbarMin = snackbarPos; + ImVec2 snackbarMax(snackbarPos.x + snackbarWidth, snackbarPos.y + snackbarHeight); + + drawList->AddRectFilled(snackbarMin, snackbarMax, bgColor, 4.0f); + + // Message text + float textY = snackbarPos.y + (snackbarHeight - ImGui::GetFontSize()) * 0.5f; + float textX = snackbarPos.x + spacing::dp(2); // 16dp left padding + + ImU32 snackText = schema::UI().resolveColor("var(--snackbar-text)", IM_COL32(255, 255, 255, 222)); + ImU32 textColor = ScaleAlpha(snackText, m_animProgress); + drawList->AddText(ImVec2(textX, textY), textColor, m_currentSpec.message); + + // Action button + if (m_currentSpec.actionText) { + float actionX = snackbarMax.x - spacing::dp(2) - actionWidth; + + // Hit test for action + ImVec2 actionMin(actionX, snackbarPos.y); + ImVec2 actionMax(snackbarMax.x, snackbarMax.y); + + ImVec2 mousePos = io.MousePos; + bool hovered = (mousePos.x >= actionMin.x && mousePos.x < actionMax.x && + mousePos.y >= actionMin.y && mousePos.y < actionMax.y); + + // Action text color + ImU32 actionColor; + if (hovered) { + actionColor = ScaleAlpha(schema::UI().resolveColor("var(--snackbar-action-hover)", IM_COL32(255, 213, 79, 255)), m_animProgress); + } else { + actionColor = ScaleAlpha(schema::UI().resolveColor("var(--snackbar-action)", IM_COL32(255, 193, 7, 255)), m_animProgress); + } + + drawList->AddText(ImVec2(actionX, textY), actionColor, m_currentSpec.actionText); + + // Check click + if (hovered && io.MouseClicked[0]) { + actionClicked = true; + dismiss(); + } + } + + return actionClicked; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/tabs.h b/src/ui/material/components/tabs.h new file mode 100644 index 0000000..794c742 --- /dev/null +++ b/src/ui/material/components/tabs.h @@ -0,0 +1,319 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "../../schema/ui_schema.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Tabs Component +// ============================================================================ +// Based on https://m2.material.io/components/tabs +// +// Tabs organize content across different screens, data sets, and other +// interactions. + +/** + * @brief Tab bar configuration + */ +struct TabBarSpec { + bool scrollable = false; // Enable horizontal scrolling + bool fullWidth = true; // Tabs fill available width + bool showIndicator = true; // Show selection indicator + bool centered = false; // Center tabs (when not full width) +}; + +/** + * @brief Individual tab configuration + */ +struct TabSpec { + const char* label = nullptr; + const char* icon = nullptr; // Optional icon (text representation) + bool disabled = false; + int badgeCount = 0; // Badge count (0 = no badge) +}; + +/** + * @brief Begin a tab bar + * + * @param id Unique identifier + * @param selectedIndex Pointer to selected tab index + * @param spec Tab bar configuration + * @return true if tab bar is visible + */ +bool BeginTabBar(const char* id, int* selectedIndex, const TabBarSpec& spec = TabBarSpec()); + +/** + * @brief End a tab bar + */ +void EndTabBar(); + +/** + * @brief Add a tab to current tab bar + * + * @param spec Tab configuration + * @return true if this tab is selected + */ +bool Tab(const TabSpec& spec); + +/** + * @brief Simple tab with just label + */ +bool Tab(const char* label); + +/** + * @brief Simple tab bar - returns selected index + * + * @param id Unique identifier + * @param labels Array of tab labels + * @param count Number of tabs + * @param selectedIndex Current selected index (will be updated) + * @return true if selection changed + */ +bool TabBar(const char* id, const char** labels, int count, int* selectedIndex); + +// ============================================================================ +// Implementation +// ============================================================================ + +// Internal state for tab rendering +struct TabBarState { + int* selectedIndex; + int currentTabIndex; + TabBarSpec spec; + float tabBarWidth; + float tabWidth; + float indicatorX; + float indicatorWidth; + ImVec2 barPos; +}; + +static TabBarState g_tabBarState; + +inline bool BeginTabBar(const char* id, int* selectedIndex, const TabBarSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(id); + + g_tabBarState.selectedIndex = selectedIndex; + g_tabBarState.currentTabIndex = 0; + g_tabBarState.spec = spec; + g_tabBarState.tabBarWidth = ImGui::GetContentRegionAvail().x; + g_tabBarState.tabWidth = 0; // Will be calculated if fullWidth + g_tabBarState.barPos = window->DC.CursorPos; + g_tabBarState.indicatorX = 0; + g_tabBarState.indicatorWidth = 0; + + // Reserve space for tab bar + float barHeight = size::TabBarHeight; + ImRect bb(g_tabBarState.barPos, + ImVec2(g_tabBarState.barPos.x + g_tabBarState.tabBarWidth, + g_tabBarState.barPos.y + barHeight)); + + ImGui::ItemSize(bb); + + // Draw tab bar background + ImDrawList* drawList = window->DrawList; + drawList->AddRectFilled(bb.Min, bb.Max, Surface(Elevation::Dp4)); + + // Begin horizontal layout for tabs + ImGui::SetCursorScreenPos(g_tabBarState.barPos); + ImGui::BeginGroup(); + + return true; +} + +inline void EndTabBar() { + ImGui::EndGroup(); + + // Draw indicator line + if (g_tabBarState.spec.showIndicator && g_tabBarState.indicatorWidth > 0) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImDrawList* drawList = window->DrawList; + + float indicatorY = g_tabBarState.barPos.y + size::TabBarHeight - 2.0f; + drawList->AddRectFilled( + ImVec2(g_tabBarState.indicatorX, indicatorY), + ImVec2(g_tabBarState.indicatorX + g_tabBarState.indicatorWidth, indicatorY + 2.0f), + Primary() + ); + } + + // Add bottom divider + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImDrawList* drawList = window->DrawList; + float dividerY = g_tabBarState.barPos.y + size::TabBarHeight; + drawList->AddLine( + ImVec2(g_tabBarState.barPos.x, dividerY), + ImVec2(g_tabBarState.barPos.x + g_tabBarState.tabBarWidth, dividerY), + OnSurfaceDisabled() + ); + + ImGui::PopID(); +} + +inline bool Tab(const TabSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + int tabIndex = g_tabBarState.currentTabIndex++; + bool isSelected = (*g_tabBarState.selectedIndex == tabIndex); + + // Calculate tab dimensions + float minTabWidth = spec.icon ? 72.0f : 90.0f; // Material min widths + float maxTabWidth = 360.0f; + float labelWidth = ImGui::CalcTextSize(spec.label).x; + float iconWidth = spec.icon ? 24.0f + spacing::dp(1) : 0; + float contentWidth = labelWidth + iconWidth + spacing::dp(4); // 32dp padding + + float tabWidth; + if (g_tabBarState.spec.fullWidth) { + // Divide evenly (assuming we don't know total count here - simplified) + tabWidth = ImMax(minTabWidth, contentWidth); + } else { + tabWidth = ImClamp(contentWidth, minTabWidth, maxTabWidth); + } + + float tabHeight = size::TabBarHeight; + + ImVec2 tabPos = window->DC.CursorPos; + ImRect tabBB(tabPos, ImVec2(tabPos.x + tabWidth, tabPos.y + tabHeight)); + + // Interaction + ImGuiID id = window->GetID(spec.label); + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(tabBB, id, &hovered, &held) && !spec.disabled; + + if (pressed && !isSelected) { + *g_tabBarState.selectedIndex = tabIndex; + } + + // Update indicator position for selected tab + if (isSelected) { + g_tabBarState.indicatorX = tabPos.x; + g_tabBarState.indicatorWidth = tabWidth; + } + + // Draw + ImDrawList* drawList = window->DrawList; + + // Hover/press state overlay + if (!spec.disabled) { + if (held) { + drawList->AddRectFilled(tabBB.Min, tabBB.Max, schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 25))); + } else if (hovered) { + drawList->AddRectFilled(tabBB.Min, tabBB.Max, schema::UI().resolveColor("var(--active-overlay)", IM_COL32(255, 255, 255, 10))); + } + } + + // Content color + ImU32 contentColor; + if (spec.disabled) { + contentColor = OnSurfaceDisabled(); + } else if (isSelected) { + contentColor = Primary(); + } else { + contentColor = OnSurfaceMedium(); + } + + // Draw content (icon and/or label) + float contentX = tabPos.x + (tabWidth - labelWidth - iconWidth) * 0.5f; + float centerY = tabPos.y + tabHeight * 0.5f; + + if (spec.icon) { + ImFont* iconFont = Type().iconMed(); + ImVec2 iconSize = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, spec.icon); + ImVec2 iconPos(contentX, centerY - iconSize.y * 0.5f); + drawList->AddText(iconFont, iconFont->LegacySize, iconPos, contentColor, spec.icon); + contentX += iconSize.x + spacing::Xs; + } + + // Label (uppercase) + Typography::instance().pushFont(TypeStyle::Button); + float labelY = centerY - ImGui::GetFontSize() * 0.5f; + + // Convert to uppercase + char upperLabel[128]; + size_t i = 0; + for (const char* p = spec.label; *p && i < sizeof(upperLabel) - 1; p++, i++) { + upperLabel[i] = (*p >= 'a' && *p <= 'z') ? (*p - 32) : *p; + } + upperLabel[i] = '\0'; + + drawList->AddText(ImVec2(contentX, labelY), contentColor, upperLabel); + Typography::instance().popFont(); + + // Badge + if (spec.badgeCount > 0) { + float badgeX = tabPos.x + tabWidth - 16.0f; + float badgeY = tabPos.y + 8.0f; + float badgeRadius = 8.0f; + + drawList->AddCircleFilled(ImVec2(badgeX, badgeY), badgeRadius, Error()); + + char badgeText[8]; + if (spec.badgeCount > 99) { + snprintf(badgeText, sizeof(badgeText), "99+"); + } else { + snprintf(badgeText, sizeof(badgeText), "%d", spec.badgeCount); + } + + ImVec2 badgeTextSize = ImGui::CalcTextSize(badgeText); + ImVec2 badgeTextPos(badgeX - badgeTextSize.x * 0.5f, badgeY - badgeTextSize.y * 0.5f); + + Typography::instance().pushFont(TypeStyle::Caption); + drawList->AddText(badgeTextPos, OnError(), badgeText); + Typography::instance().popFont(); + } + + // Advance cursor + ImGui::SameLine(0, 0); + ImGui::SetCursorScreenPos(ImVec2(tabPos.x + tabWidth, tabPos.y)); + + return isSelected; +} + +inline bool Tab(const char* label) { + TabSpec spec; + spec.label = label; + return Tab(spec); +} + +inline bool TabBar(const char* id, const char** labels, int count, int* selectedIndex) { + int oldIndex = *selectedIndex; + + TabBarSpec spec; + spec.fullWidth = true; + + if (BeginTabBar(id, selectedIndex, spec)) { + // Calculate tab width for full-width mode + float tabWidth = ImGui::GetContentRegionAvail().x / count; + + for (int i = 0; i < count; i++) { + TabSpec tabSpec; + tabSpec.label = labels[i]; + Tab(tabSpec); + } + + EndTabBar(); + } + + return (*selectedIndex != oldIndex); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/components/text_fields.h b/src/ui/material/components/text_fields.h new file mode 100644 index 0000000..42ef844 --- /dev/null +++ b/src/ui/material/components/text_fields.h @@ -0,0 +1,227 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../colors.h" +#include "../typography.h" +#include "../layout.h" +#include "imgui.h" +#include "imgui_internal.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Text Field Component +// ============================================================================ +// Based on https://m2.material.io/components/text-fields +// +// Two variants: +// - Filled: Background fill with bottom line indicator +// - Outlined: Border around entire field + +enum class TextFieldStyle { + Filled, // Background fill + Outlined // Border only +}; + +/** + * @brief Text field configuration + */ +struct TextFieldSpec { + TextFieldStyle style = TextFieldStyle::Outlined; + const char* label = nullptr; // Floating label text + const char* hint = nullptr; // Placeholder when empty + const char* helperText = nullptr; // Helper text below field + const char* errorText = nullptr; // Error message (shows in error state) + const char* prefix = nullptr; // Prefix text (e.g., "$") + const char* suffix = nullptr; // Suffix text (e.g., "DRGX") + bool password = false; // Mask input + bool readOnly = false; // Read-only field + bool multiline = false; // Multi-line text area + int multilineRows = 3; // Number of rows for multiline + float width = 0; // Width (0 = full available) +}; + +/** + * @brief Render a Material Design text field + * + * @param id Unique identifier + * @param buf Text buffer + * @param bufSize Buffer size + * @param spec Field configuration + * @return true if value changed + */ +bool TextField(const char* id, char* buf, size_t bufSize, const TextFieldSpec& spec = TextFieldSpec()); + +/** + * @brief Render a simple text field with label + */ +inline bool TextField(const char* label, char* buf, size_t bufSize) { + TextFieldSpec spec; + spec.label = label; + return TextField(label, buf, bufSize, spec); +} + +// ============================================================================ +// Implementation +// ============================================================================ + +inline bool TextField(const char* id, char* buf, size_t bufSize, const TextFieldSpec& spec) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGui::PushID(id); + + bool hasError = (spec.errorText != nullptr); + bool hasValue = (buf[0] != '\0'); + + // Calculate dimensions + float fieldWidth = spec.width > 0 ? spec.width : ImGui::GetContentRegionAvail().x; + float fieldHeight = spec.multiline ? + (size::TextFieldHeight + (spec.multilineRows - 1) * Typography::instance().getFont(TypeStyle::Body1)->FontSize * 1.5f) : + size::TextFieldHeight; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, ImVec2(pos.x + fieldWidth, pos.y + fieldHeight)); + + // Interaction + ImGuiID inputId = window->GetID("##input"); + bool focused = (ImGui::GetFocusID() == inputId); + + // Colors + ImU32 bgColor, borderColor, labelColor; + + if (hasError) { + borderColor = Error(); + labelColor = Error(); + } else if (focused) { + borderColor = Primary(); + labelColor = Primary(); + } else { + borderColor = OnSurfaceMedium(); + labelColor = OnSurfaceMedium(); + } + + if (spec.style == TextFieldStyle::Filled) { + bgColor = GetElevatedSurface(GetCurrentColorTheme(), 1); + } else { + bgColor = 0; // Transparent for outlined + } + + // Draw background/border + ImDrawList* drawList = window->DrawList; + + if (spec.style == TextFieldStyle::Filled) { + // Filled style: background with bottom line + drawList->AddRectFilled(bb.Min, bb.Max, bgColor, + size::TextFieldCornerRadius, ImDrawFlags_RoundCornersTop); + + // Bottom indicator line + float lineThickness = focused ? 2.0f : 1.0f; + drawList->AddLine( + ImVec2(bb.Min.x, bb.Max.y - lineThickness), + ImVec2(bb.Max.x, bb.Max.y - lineThickness), + borderColor, lineThickness + ); + } else { + // Outlined style: border around entire field + float lineThickness = focused ? 2.0f : 1.0f; + drawList->AddRect(bb.Min, bb.Max, borderColor, + size::TextFieldCornerRadius, 0, lineThickness); + } + + // Label (floating or inline) + bool labelFloating = focused || hasValue; + if (spec.label) { + ImVec2 labelPos; + TypeStyle labelStyle; + + if (labelFloating) { + // Floating label (smaller, at top) + labelPos.x = bb.Min.x + size::TextFieldPadding; + labelPos.y = bb.Min.y + 4.0f; + labelStyle = TypeStyle::Caption; + } else { + // Inline label (body size, centered) + labelPos.x = bb.Min.x + size::TextFieldPadding; + labelPos.y = bb.Min.y + (fieldHeight - Typography::instance().getFont(TypeStyle::Body1)->FontSize) * 0.5f; + labelStyle = TypeStyle::Body1; + } + + // For outlined style, need to clear background behind floating label + if (spec.style == TextFieldStyle::Outlined && labelFloating) { + ImVec2 labelSize = ImGui::CalcTextSize(spec.label); + ImVec2 clearMin(labelPos.x - 4.0f, bb.Min.y - 1.0f); + ImVec2 clearMax(labelPos.x + labelSize.x + 4.0f, bb.Min.y + Typography::instance().getFont(TypeStyle::Caption)->FontSize); + drawList->AddRectFilled(clearMin, clearMax, Background()); + } + + Typography::instance().pushFont(labelStyle); + drawList->AddText(labelPos, labelColor, spec.label); + Typography::instance().popFont(); + } + + // Input field + float inputY = spec.label && labelFloating ? bb.Min.y + 20.0f : bb.Min.y + 12.0f; + float inputHeight = bb.Max.y - inputY - 8.0f; + + ImGui::SetCursorScreenPos(ImVec2(bb.Min.x + size::TextFieldPadding, inputY)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurface())); + + ImGuiInputTextFlags flags = 0; + if (spec.password) flags |= ImGuiInputTextFlags_Password; + if (spec.readOnly) flags |= ImGuiInputTextFlags_ReadOnly; + + float inputWidth = fieldWidth - size::TextFieldPadding * 2; + if (spec.prefix) { + ImGui::TextUnformatted(spec.prefix); + ImGui::SameLine(); + inputWidth -= ImGui::CalcTextSize(spec.prefix).x + 4.0f; + } + + ImGui::PushItemWidth(inputWidth); + bool changed; + if (spec.multiline) { + changed = ImGui::InputTextMultiline("##input", buf, bufSize, + ImVec2(inputWidth, inputHeight), flags); + } else { + changed = ImGui::InputText("##input", buf, bufSize, flags); + } + ImGui::PopItemWidth(); + + if (spec.suffix) { + ImGui::SameLine(); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium()), "%s", spec.suffix); + } + + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(); + + // Helper/Error text below field + ImGui::SetCursorScreenPos(ImVec2(bb.Min.x, bb.Max.y + 4.0f)); + if (spec.errorText) { + Typography::instance().textColored(TypeStyle::Caption, Error(), spec.errorText); + ImGui::SetCursorScreenPos(ImVec2(bb.Min.x, bb.Max.y + 4.0f + Typography::instance().getFont(TypeStyle::Caption)->FontSize + 4.0f)); + } else if (spec.helperText) { + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), spec.helperText); + ImGui::SetCursorScreenPos(ImVec2(bb.Min.x, bb.Max.y + 4.0f + Typography::instance().getFont(TypeStyle::Caption)->FontSize + 4.0f)); + } + + // Advance cursor + ImGui::SetCursorScreenPos(ImVec2(pos.x, bb.Max.y + (spec.errorText || spec.helperText ? 24.0f : 8.0f))); + + ImGui::PopID(); + + return changed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/draw_helpers.h b/src/ui/material/draw_helpers.h new file mode 100644 index 0000000..cb61413 --- /dev/null +++ b/src/ui/material/draw_helpers.h @@ -0,0 +1,779 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "colors.h" +#include "type.h" +#include "../layout.h" +#include "../schema/element_styles.h" +#include "../schema/color_var_resolver.h" +#include "../schema/ui_schema.h" +#include "../effects/theme_effects.h" +#include "../effects/low_spec.h" +#include "../effects/imgui_acrylic.h" +#include "../theme.h" +#include "../../util/noise_texture.h" +#include "imgui.h" +#include "imgui_internal.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace material { + +// Scale the alpha channel of an ImU32 color by a float factor. +inline ImU32 ScaleAlpha(ImU32 col, float scale) { + int a = static_cast(((col >> IM_COL32_A_SHIFT) & 0xFF) * scale); + if (a > 255) a = 255; + return (col & ~IM_COL32_A_MASK) | (static_cast(a) << IM_COL32_A_SHIFT); +} + +// ============================================================================ +// Text Drop Shadow +// ============================================================================ +// Draw text with a subtle dark shadow behind it for readability on +// translucent / glassy surfaces. The shadow is a 1px offset copy of +// the text in a near-black colour. When the OS backdrop (DWM Acrylic) +// is inactive, the shadow is skipped since opaque backgrounds already +// provide enough contrast. + +inline void DrawTextShadow(ImDrawList* dl, ImFont* font, float fontSize, + const ImVec2& pos, ImU32 col, const char* text, + float offsetX = 1.0f, float offsetY = 1.0f, + ImU32 shadowCol = 0) +{ + if (IsBackdropActive()) { + if (!shadowCol) { + static uint32_t s_gen = 0; + static ImU32 s_shadowCol = 0; + uint32_t g = schema::UI().generation(); + if (g != s_gen) { s_gen = g; s_shadowCol = schema::UI().resolveColor("var(--text-shadow)", IM_COL32(0, 0, 0, 120)); } + shadowCol = s_shadowCol; + } + dl->AddText(font, fontSize, + ImVec2(pos.x + offsetX, pos.y + offsetY), + shadowCol, text); + } + dl->AddText(font, fontSize, pos, col, text); +} + +// Convenience overload that uses the current default font. +inline void DrawTextShadow(ImDrawList* dl, const ImVec2& pos, ImU32 col, + const char* text, + float offsetX = 1.0f, float offsetY = 1.0f, + ImU32 shadowCol = 0) +{ + if (IsBackdropActive()) { + if (!shadowCol) { + static uint32_t s_gen = 0; + static ImU32 s_shadowCol = 0; + uint32_t g = schema::UI().generation(); + if (g != s_gen) { s_gen = g; s_shadowCol = schema::UI().resolveColor("var(--text-shadow)", IM_COL32(0, 0, 0, 120)); } + shadowCol = s_shadowCol; + } + dl->AddText(ImVec2(pos.x + offsetX, pos.y + offsetY), + shadowCol, text); + } + dl->AddText(pos, col, text); +} + +// ============================================================================ +// Modal-Aware Hover Check +// ============================================================================ +// Drop-in replacement for ImGui::IsMouseHoveringRect that also respects +// modal popup blocking. The raw ImGui helper is a pure geometric test +// and will return true even when a modal popup covers the rect, which +// causes background elements to show hover highlights through dialogs. + +inline bool IsRectHovered(const ImVec2& r_min, const ImVec2& r_max, bool clip = true) +{ + if (!ImGui::IsMouseHoveringRect(r_min, r_max, clip)) + return false; + // If a modal popup is open and it is not the current window, treat + // the content as non-hoverable (same logic ImGui uses internally + // inside IsWindowContentHoverable for modal blocking). + // + // We cannot rely solely on GetTopMostAndVisiblePopupModal() because + // it checks Active, which is only set when BeginPopupModal() is + // called in the current frame. Content tabs render BEFORE their + // associated dialogs, so the modal's Active flag is still false at + // this point. Checking WasActive (set from the previous frame) + // covers this render-order gap. + ImGuiContext& g = *ImGui::GetCurrentContext(); + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) { + ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window; + if (popup && (popup->Flags & ImGuiWindowFlags_Modal)) { + if ((popup->Active || popup->WasActive) && !popup->Hidden) { + if (popup != ImGui::GetCurrentWindow()) + return false; + } + } + } + return true; +} + +// ============================================================================ +// Tactile Button Overlay +// ============================================================================ +// Adds a subtle top-edge highlight and bottom-edge shadow to a button rect, +// creating the illusion of a raised physical surface. On active (pressed), +// the highlight/shadow swap to create an inset "pushed" feel. +// Call this AFTER ImGui::Button() using GetItemRectMin()/GetItemRectMax(). + +inline void DrawTactileOverlay(ImDrawList* dl, const ImVec2& bMin, + const ImVec2& bMax, float rounding, + bool active = false) +{ + float h = bMax.y - bMin.y; + float edgeH = std::min(h * 0.38f, 6.0f); // highlight/shadow strip height + + // AddRectFilledMultiColor does not support rounding, so clip to the + // button's rounded rect to prevent sharp corners from poking out. + if (rounding > 0.0f) { + float inset = rounding * 0.29f; // enough to hide corners + dl->PushClipRect( + ImVec2(bMin.x + inset, bMin.y + inset), + ImVec2(bMax.x - inset, bMax.y - inset), true); + } + + ImU32 tHi = schema::UI().resolveColor("var(--tactile-top)", IM_COL32(255, 255, 255, 18)); + ImU32 tHiT = tHi & ~IM_COL32_A_MASK; // transparent version + + if (!active) { + // Raised: bright top edge, dark bottom edge + // Top highlight + dl->AddRectFilledMultiColor( + bMin, ImVec2(bMax.x, bMin.y + edgeH), + tHi, tHi, tHiT, tHiT); + // Bottom shadow + dl->AddRectFilledMultiColor( + ImVec2(bMin.x, bMax.y - edgeH), bMax, + IM_COL32(0, 0, 0, 0), // top-left + IM_COL32(0, 0, 0, 0), // top-right + IM_COL32(0, 0, 0, 22), // bottom-right + IM_COL32(0, 0, 0, 22)); // bottom-left + } else { + // Pressed: dark top edge, bright bottom edge (inset) + // Top shadow + dl->AddRectFilledMultiColor( + bMin, ImVec2(bMax.x, bMin.y + edgeH), + IM_COL32(0, 0, 0, 20), + IM_COL32(0, 0, 0, 20), + IM_COL32(0, 0, 0, 0), + IM_COL32(0, 0, 0, 0)); + // Bottom highlight (dimmer when pressed) + ImU32 pHi = ScaleAlpha(tHi, 0.55f); + ImU32 pHiT = pHi & ~IM_COL32_A_MASK; + dl->AddRectFilledMultiColor( + ImVec2(bMin.x, bMax.y - edgeH), bMax, + pHiT, pHiT, pHi, pHi); + } + + if (rounding > 0.0f) + dl->PopClipRect(); +} + +// Convenience: call right after any ImGui::Button() / SmallButton() call +// to add tactile depth. Uses the last item rect automatically. +inline void ApplyTactile(ImDrawList* dl = nullptr) +{ + if (!dl) dl = ImGui::GetWindowDrawList(); + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + float rounding = ImGui::GetStyle().FrameRounding; + bool active = ImGui::IsItemActive(); + DrawTactileOverlay(dl, bMin, bMax, rounding, active); +} + +// ── Button font tier helper ───────────────────────────────────────────── +// Resolves an int tier (0=sm, 1=md/default, 2=lg) to the matching ImFont*. +// Passing -1 or any out-of-range value returns the default button font. + +inline ImFont* resolveButtonFont(int tier) +{ + switch (tier) { + case 0: return Type().buttonSm(); + case 2: return Type().buttonLg(); + default: return Type().button(); // 1 or any other value + } +} + +// Resolve per-button font: if perButton >= 0 use it, else fall back to sectionDefault +inline ImFont* resolveButtonFont(int perButton, int sectionDefault) +{ + return resolveButtonFont(perButton >= 0 ? perButton : sectionDefault); +} + +// ── Tactile wrappers ──────────────────────────────────────────────────── +// Drop-in replacements for ImGui::Button / SmallButton that automatically +// add the tactile highlight overlay after rendering. + +inline bool TactileButton(const char* label, const ImVec2& size = ImVec2(0, 0), ImFont* font = nullptr) +{ + // Draw button with glass-card styling: translucent fill + border + tactile overlay + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* useFont = font ? font : Type().button(); + + // For icon fonts, use InvisibleButton + manual centered text rendering + // to ensure perfect centering (ImGui::Button alignment can be off for icons) + bool isIconFont = font && (font == Type().iconSmall() || font == Type().iconMed() || + font == Type().iconLarge() || font == Type().iconXL()); + + bool pressed; + if (isIconFont && size.x > 0 && size.y > 0) { + pressed = ImGui::InvisibleButton(label, size); + } else { + ImGui::PushFont(useFont); + pressed = ImGui::Button(label, size); + ImGui::PopFont(); + } + // Glass overlay on the button rect + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + + // For icon fonts, manually draw centered icon after getting button rect + if (isIconFont && size.x > 0 && size.y > 0) { + ImVec2 textSz = useFont->CalcTextSizeA(useFont->LegacySize, FLT_MAX, 0, label); + ImVec2 textPos(bMin.x + (size.x - textSz.x) * 0.5f, bMin.y + (size.y - textSz.y) * 0.5f); + dl->AddText(useFont, useFont->LegacySize, textPos, ImGui::GetColorU32(ImGuiCol_Text), label); + } + + float rounding = ImGui::GetStyle().FrameRounding; + bool active = ImGui::IsItemActive(); + bool hovered = ImGui::IsItemHovered(); + // Frosted glass highlight — subtle fill on top + if (!active) { + ImU32 col = hovered + ? schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 12)) + : schema::UI().resolveColor("var(--glass-fill)", IM_COL32(255, 255, 255, 6)); + dl->AddRectFilled(bMin, bMax, col, rounding); + } + // Rim light + ImU32 rim = schema::UI().resolveColor("var(--rim-light)", IM_COL32(255, 255, 255, 25)); + dl->AddRect(bMin, bMax, + active ? ScaleAlpha(rim, 0.6f) : rim, + rounding, 0, 1.0f); + // Tactile depth + DrawTactileOverlay(dl, bMin, bMax, rounding, active); + return pressed; +} + +inline bool TactileSmallButton(const char* label, ImFont* font = nullptr) +{ + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImGui::PushFont(font ? font : Type().button()); + bool pressed = ImGui::SmallButton(label); + ImGui::PopFont(); + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + float rounding = ImGui::GetStyle().FrameRounding; + bool active = ImGui::IsItemActive(); + bool hovered = ImGui::IsItemHovered(); + if (!active) { + ImU32 col = hovered + ? schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 12)) + : schema::UI().resolveColor("var(--glass-fill)", IM_COL32(255, 255, 255, 6)); + dl->AddRectFilled(bMin, bMax, col, rounding); + } + ImU32 rim = schema::UI().resolveColor("var(--rim-light)", IM_COL32(255, 255, 255, 25)); + dl->AddRect(bMin, bMax, + active ? ScaleAlpha(rim, 0.6f) : rim, + rounding, 0, 1.0f); + DrawTactileOverlay(dl, bMin, bMax, rounding, active); + return pressed; +} + +// ============================================================================ +// Glass Panel (glassmorphism card) +// ============================================================================ +// Draws a frosted-glass style panel: a semi-transparent fill with a +// subtle light border. Used for card/panel containers that sit above +// the blurred background. When the backdrop is inactive the fill is +// simply the normal surface colour (fully opaque). + +struct GlassPanelSpec { + float rounding = 6.0f; + int fillAlpha = 18; // fill brightness (white, 0-255) + int borderAlpha = 30; // border brightness (white, 0-255) + float borderWidth = 1.0f; +}; + +inline void DrawGlassPanel(ImDrawList* dl, const ImVec2& pMin, + const ImVec2& pMax, + const GlassPanelSpec& spec = GlassPanelSpec()) +{ + if (IsBackdropActive() && !dragonx::ui::effects::isLowSpecMode()) { + // --- Cached color lookups (invalidated on theme change) --- + // These 3 resolveColor() calls do string parsing + map lookup + // each time. Cache them per-frame using the schema generation + // counter so they resolve at most once per theme load. + static uint32_t s_gen = 0; + static ImU32 s_glassFill = 0; + static ImU32 s_glassNoiseTint = 0; + static ImU32 s_glassBorder = 0; + uint32_t curGen = schema::UI().generation(); + if (curGen != s_gen) { + s_gen = curGen; + s_glassFill = schema::UI().resolveColor("var(--glass-fill)", IM_COL32(255, 255, 255, 18)); + s_glassNoiseTint = schema::UI().resolveColor("var(--glass-noise-tint)", IM_COL32(255, 255, 255, 10)); + s_glassBorder = schema::UI().resolveColor("var(--glass-border)", IM_COL32(255, 255, 255, 30)); + } + + float uiOp = effects::ImGuiAcrylic::GetUIOpacity(); + bool useAcrylic = effects::ImGuiAcrylic::IsEnabled() + && effects::ImGuiAcrylic::IsAvailable(); + + // Glass / acrylic layer — only rendered when not fully opaque + // (skip the blur pass at 100% for performance) + if (uiOp < 0.99f) { + if (useAcrylic) { + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + effects::ImGuiAcrylic::DrawAcrylicRect(dl, pMin, pMax, + acrylicTheme.card, spec.rounding); + } else { + // Lightweight fake-glass: translucent fill + ImU32 fill = (spec.fillAlpha == 18) ? s_glassFill : ScaleAlpha(s_glassFill, spec.fillAlpha / 18.0f); + dl->AddRectFilled(pMin, pMax, fill, spec.rounding); + } + } + + // Surface overlay — provides smooth transition from glass to opaque. + // At uiOp=1.0 this fully covers the panel (opaque card). + // As uiOp decreases, glass/blur progressively shows through. + dl->AddRectFilled(pMin, pMax, + WithAlphaF(GetElevatedSurface(GetCurrentColorTheme(), 1), uiOp), + spec.rounding); + + // Noise grain overlay — drawn OVER the surface overlay so card + // opacity doesn't hide it. Gives cards a tactile paper feel. + { + float noiseMul = dragonx::ui::effects::ImGuiAcrylic::GetNoiseOpacity(); + if (noiseMul > 0.0f) { + uint8_t origAlpha = (s_glassNoiseTint >> IM_COL32_A_SHIFT) & 0xFF; + uint8_t scaledAlpha = static_cast(std::min(255.0f, origAlpha * noiseMul)); + ImU32 noiseTint = (s_glassNoiseTint & ~(0xFFu << IM_COL32_A_SHIFT)) | (scaledAlpha << IM_COL32_A_SHIFT); + float inset = spec.rounding * 0.3f; + ImVec2 clipMin(pMin.x + inset, pMin.y + inset); + ImVec2 clipMax(pMax.x - inset, pMax.y - inset); + dl->PushClipRect(clipMin, clipMax, true); + dragonx::util::DrawTiledNoiseRect(dl, clipMin, clipMax, noiseTint); + dl->PopClipRect(); + } + } + + // Border — fades with UI opacity + ImU32 border = (spec.borderAlpha == 30) ? s_glassBorder : ScaleAlpha(s_glassBorder, spec.borderAlpha / 30.0f); + if (uiOp < 0.99f) border = ScaleAlpha(border, uiOp); + dl->AddRect(pMin, pMax, border, + spec.rounding, 0, spec.borderWidth); + + // Theme visual effects drawn on ForegroundDrawList so they + // render above card content (text, values, etc.), not below. + auto& fx = effects::ThemeEffects::instance(); + ImDrawList* fxDl = ImGui::GetForegroundDrawList(); + if (fx.hasRainbowBorder()) { + fx.drawRainbowBorder(fxDl, pMin, pMax, spec.rounding, spec.borderWidth); + } + if (fx.hasShimmer()) { + fx.drawShimmer(fxDl, pMin, pMax, spec.rounding); + } + if (fx.hasSpecularGlare()) { + fx.drawSpecularGlare(fxDl, pMin, pMax, spec.rounding); + } + // Per-panel theme effects: edge trace + ember rise + fx.drawPanelEffects(fxDl, pMin, pMax, spec.rounding); + } else { + // Low-spec opaque fallback + dl->AddRectFilled(pMin, pMax, + GetElevatedSurface(GetCurrentColorTheme(), 1), spec.rounding); + } +} + +// ============================================================================ +// Stat Card — reusable card with overline / value / subtitle + accent stripe +// ============================================================================ + +struct StatCardSpec { + const char* overline = nullptr; // small label at top (e.g. "LOCAL HASHRATE") + const char* value = nullptr; // main value text (e.g. "1.23 kH/s") + const char* subtitle = nullptr; // optional small line (e.g. "3 blocks") + ImU32 valueCol = 0; // value text colour (0 = OnSurface) + ImU32 accentCol = 0; // left-stripe colour (0 = no stripe) + bool centered = true; // centre text horizontally + bool hovered = false; // draw hover glow border +}; + +/// Compute a generous stat-card height with breathing room. +inline float StatCardHeight(float vs, float minH = 56.0f) { + float padV = Layout::spacingLg() * 2; // top + bottom + float content = Type().overline()->LegacySize + + Layout::spacingMd() + + Type().subtitle1()->LegacySize; + return std::max(minH, (content + padV) * std::max(vs, 0.85f)); +} + +inline void DrawStatCard(ImDrawList* dl, + const ImVec2& cMin, const ImVec2& cMax, + const StatCardSpec& card, + const GlassPanelSpec& glass = GlassPanelSpec()) +{ + float cardW = cMax.x - cMin.x; + float cardH = cMax.y - cMin.y; + float rnd = glass.rounding; + + // 1. Glass background + DrawGlassPanel(dl, cMin, cMax, glass); + + // 2. Accent stripe (left edge, clipped to card rounded corners). + // Draw a full-height rounded rect with card rounding (left corners) + // and clip to stripe width so the shape follows the corner radius. + if ((card.accentCol & IM_COL32_A_MASK) != 0) { + float stripeW = 4.0f; + dl->PushClipRect(cMin, ImVec2(cMin.x + stripeW, cMax.y), true); + dl->AddRectFilled(cMin, cMax, card.accentCol, rnd, + ImDrawFlags_RoundCornersLeft); + dl->PopClipRect(); + } + + // 3. Compute content block height + ImFont* ovFont = Type().overline(); + ImFont* valFont = Type().subtitle1(); + ImFont* subFont = Type().caption(); + + float blockH = 0; + if (card.overline) blockH += ovFont->LegacySize; + if (card.overline && card.value) blockH += Layout::spacingMd(); + if (card.value) blockH += valFont->LegacySize; + if (card.subtitle) blockH += Layout::spacingSm() + subFont->LegacySize; + + // 4. Vertically centre + float topY = cMin.y + (cardH - blockH) * 0.5f; + float padX = Layout::spacingLg(); + float cy = topY; + + // 5. Overline + if (card.overline) { + ImVec2 sz = ovFont->CalcTextSizeA(ovFont->LegacySize, 10000, 0, card.overline); + float tx = card.centered ? cMin.x + (cardW - sz.x) * 0.5f : cMin.x + padX; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(tx, cy), OnSurfaceMedium(), card.overline); + cy += ovFont->LegacySize + Layout::spacingMd(); + } + + // 6. Value (with text shadow) + if (card.value) { + ImU32 col = card.valueCol ? card.valueCol : OnSurface(); + ImVec2 sz = valFont->CalcTextSizeA(valFont->LegacySize, 10000, 0, card.value); + float tx = card.centered ? cMin.x + (cardW - sz.x) * 0.5f : cMin.x + padX; + DrawTextShadow(dl, valFont, valFont->LegacySize, ImVec2(tx, cy), col, card.value); + cy += valFont->LegacySize; + } + + // 7. Subtitle + if (card.subtitle) { + cy += Layout::spacingSm(); + ImVec2 sz = subFont->CalcTextSizeA(subFont->LegacySize, 10000, 0, card.subtitle); + float tx = card.centered ? cMin.x + (cardW - sz.x) * 0.5f : cMin.x + padX; + dl->AddText(subFont, subFont->LegacySize, ImVec2(tx, cy), OnSurfaceDisabled(), card.subtitle); + } + + // 8. Hover glow + if (card.hovered) { + dl->AddRect(cMin, cMax, + schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 20)), + rnd, 0, 1.5f); + } +} + +// ── Styled Button (font-only wrapper) ─────────────────────────────────── +// Drop-in replacement for ImGui::Button that pushes the Button font style +// (from JSON config) without adding tactile visual effects. + +inline bool StyledButton(const char* label, const ImVec2& size = ImVec2(0, 0), ImFont* font = nullptr) +{ + ImGui::PushFont(font ? font : Type().button()); + bool pressed = ImGui::Button(label, size); + ImGui::PopFont(); + return pressed; +} + +inline bool StyledSmallButton(const char* label, ImFont* font = nullptr) +{ + ImGui::PushFont(font ? font : Type().button()); + bool pressed = ImGui::SmallButton(label); + ImGui::PopFont(); + return pressed; +} + +// ============================================================================ +// ButtonStyle-driven overloads (unified UI schema) +// ============================================================================ +// These accept a ButtonStyle + ColorVarResolver to push font, colors, +// and size from the schema. Existing call sites are unaffected. + +inline bool StyledButton(const char* label, const schema::ButtonStyle& style, + const schema::ColorVarResolver& colors) +{ + // Resolve font + ImFont* font = nullptr; + if (!style.font.empty()) { + font = Type().resolveByName(style.font); + } + ImGui::PushFont(font ? font : Type().button()); + + // Push color overrides + int colorCount = 0; + if (!style.colors.background.empty()) { + ImGui::PushStyleColor(ImGuiCol_Button, + colors.resolve(style.colors.background)); + colorCount++; + } + if (!style.colors.backgroundHover.empty()) { + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + colors.resolve(style.colors.backgroundHover)); + colorCount++; + } + if (!style.colors.backgroundActive.empty()) { + ImGui::PushStyleColor(ImGuiCol_ButtonActive, + colors.resolve(style.colors.backgroundActive)); + colorCount++; + } + if (!style.colors.color.empty()) { + ImGui::PushStyleColor(ImGuiCol_Text, + colors.resolve(style.colors.color)); + colorCount++; + } + + // Push style overrides + int styleCount = 0; + if (style.borderRadius >= 0) { + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, style.borderRadius); + styleCount++; + } + + ImVec2 size(style.width > 0 ? style.width : 0, + style.height > 0 ? style.height : 0); + bool pressed = ImGui::Button(label, size); + + ImGui::PopStyleVar(styleCount); + ImGui::PopStyleColor(colorCount); + ImGui::PopFont(); + return pressed; +} + +inline bool TactileButton(const char* label, const schema::ButtonStyle& style, + const schema::ColorVarResolver& colors) +{ + // Resolve font + ImFont* font = nullptr; + if (!style.font.empty()) { + font = Type().resolveByName(style.font); + } + ImGui::PushFont(font ? font : Type().button()); + + // Push color overrides + int colorCount = 0; + if (!style.colors.background.empty()) { + ImGui::PushStyleColor(ImGuiCol_Button, + colors.resolve(style.colors.background)); + colorCount++; + } + if (!style.colors.backgroundHover.empty()) { + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + colors.resolve(style.colors.backgroundHover)); + colorCount++; + } + if (!style.colors.backgroundActive.empty()) { + ImGui::PushStyleColor(ImGuiCol_ButtonActive, + colors.resolve(style.colors.backgroundActive)); + colorCount++; + } + if (!style.colors.color.empty()) { + ImGui::PushStyleColor(ImGuiCol_Text, + colors.resolve(style.colors.color)); + colorCount++; + } + + // Push style overrides + int styleCount = 0; + if (style.borderRadius >= 0) { + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, style.borderRadius); + styleCount++; + } + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 size(style.width > 0 ? style.width : 0, + style.height > 0 ? style.height : 0); + bool pressed = ImGui::Button(label, size); + + // Glass overlay on the button rect + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + float rounding = ImGui::GetStyle().FrameRounding; + bool active = ImGui::IsItemActive(); + bool hovered = ImGui::IsItemHovered(); + if (!active) { + ImU32 col = hovered + ? schema::UI().resolveColor("var(--hover-overlay)", IM_COL32(255, 255, 255, 12)) + : schema::UI().resolveColor("var(--glass-fill)", IM_COL32(255, 255, 255, 6)); + dl->AddRectFilled(bMin, bMax, col, rounding); + } + ImU32 rim = schema::UI().resolveColor("var(--rim-light)", IM_COL32(255, 255, 255, 25)); + dl->AddRect(bMin, bMax, + active ? ScaleAlpha(rim, 0.6f) : rim, + rounding, 0, 1.0f); + DrawTactileOverlay(dl, bMin, bMax, rounding, active); + + ImGui::PopStyleVar(styleCount); + ImGui::PopStyleColor(colorCount); + ImGui::PopFont(); + return pressed; +} + +} // namespace material +} // namespace ui +} // namespace dragonx + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Scroll-edge clipping mask — CSS mask-image style vertex alpha fade. +// Call ApplyScrollEdgeMask after EndChild() to fade content at the +// top/bottom edges of a scrollable panel. Works by walking vertices +// added during rendering and scaling their alpha based on distance +// to the panel edges. No opaque overlay rectangles — content becomes +// truly transparent, revealing whatever is behind the panel. +// +// Usage pattern: +// float scrollY = 0, scrollMaxY = 0; +// int parentVtx = parentDL->VtxBuffer.Size; +// ImGui::BeginChild(...); +// ImDrawList* childDL = ImGui::GetWindowDrawList(); +// int childVtx = childDL->VtxBuffer.Size; +// { ... scrollY = GetScrollY(); scrollMaxY = GetScrollMaxY(); ... } +// ImGui::EndChild(); +// ApplyScrollEdgeMask(parentDL, parentVtx, childDL, childVtx, +// panelMin.y, panelMax.y, fadeZone, scrollY, scrollMaxY); +// ============================================================================ +inline void ApplyScrollEdgeMask(ImDrawList* parentDL, int parentVtxStart, + ImDrawList* childDL, int childVtxStart, + float topEdge, float bottomEdge, + float fadeZone, + float scrollY, float scrollMaxY) +{ + auto mask = [&](ImDrawList* dl, int startIdx) { + for (int vi = startIdx; vi < dl->VtxBuffer.Size; vi++) { + ImDrawVert& v = dl->VtxBuffer[vi]; + float alpha = 1.0f; + + // Top fade — only when scrolled down + if (scrollY > 1.0f) { + float d = v.pos.y - topEdge; + if (d < fadeZone) + alpha = std::min(alpha, std::max(0.0f, d / fadeZone)); + } + // Bottom fade — only when not at scroll bottom + if (scrollMaxY > 0 && scrollY < scrollMaxY - 1.0f) { + float d = bottomEdge - v.pos.y; + if (d < fadeZone) + alpha = std::min(alpha, std::max(0.0f, d / fadeZone)); + } + + if (alpha < 1.0f) { + int a = (v.col >> IM_COL32_A_SHIFT) & 0xFF; + a = static_cast(a * alpha); + v.col = (v.col & ~IM_COL32_A_MASK) | (static_cast(a) << IM_COL32_A_SHIFT); + } + } + }; + + if (parentDL) mask(parentDL, parentVtxStart); + if (childDL) mask(childDL, childVtxStart); +} + +// ============================================================================ +// Smooth scrolling — exponential decay interpolation for mouse wheel. +// Call immediately after BeginChild() on a child that was created with +// ImGuiWindowFlags_NoScrollWithMouse. Captures wheel input and lerps +// scroll position each frame for a smooth feel. +// +// Usage: +// ImGui::BeginChild("##List", size, false, +// ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); +// ApplySmoothScroll(); +// ... render content ... +// ImGui::EndChild(); +// ============================================================================ + +/// Returns true when any smooth-scroll child is still interpolating toward +/// its target. Checked by the idle-rendering logic in main.cpp to keep +/// rendering frames until the animation settles. +inline bool& SmoothScrollAnimating() { + static bool sAnimating = false; + return sAnimating; +} + +inline void ApplySmoothScroll(float speed = 12.0f) +{ + struct ScrollState { + float target = 0.0f; + float current = 0.0f; + bool init = false; + }; + static std::unordered_map sStates; + + ImGuiWindow* win = ImGui::GetCurrentWindow(); + if (!win) return; + + ScrollState& s = sStates[win->ID]; + float scrollMaxY = ImGui::GetScrollMaxY(); + + if (!s.init) { + s.target = ImGui::GetScrollY(); + s.current = s.target; + s.init = true; + } + + // If something external set scroll position (e.g. SetScrollHereY for + // auto-scroll), sync our state so the next wheel-up starts from the + // actual current position rather than an old remembered target. + float actualY = ImGui::GetScrollY(); + if (std::abs(s.current - actualY) > 1.0f) { + s.target = actualY; + s.current = actualY; + } + + // Capture mouse wheel when hovered + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows)) { + float wheel = ImGui::GetIO().MouseWheel; + if (wheel != 0.0f) { + float step = ImGui::GetTextLineHeightWithSpacing() * 3.0f; + s.target -= wheel * step; + s.target = ImClamp(s.target, 0.0f, scrollMaxY); + } + } + + // Clamp target if scrollMax changed (e.g., content resized) + if (s.target > scrollMaxY) s.target = scrollMaxY; + + // Exponential decay lerp + float dt = ImGui::GetIO().DeltaTime; + s.current += (s.target - s.current) * (1.0f - expf(-speed * dt)); + + // Snap when close + if (std::abs(s.current - s.target) < 0.5f) + s.current = s.target; + else + SmoothScrollAnimating() = true; // still interpolating — keep rendering + + ImGui::SetScrollY(s.current); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/elevation.h b/src/ui/material/elevation.h new file mode 100644 index 0000000..e883b4a --- /dev/null +++ b/src/ui/material/elevation.h @@ -0,0 +1,345 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "colors.h" +#include "../effects/low_spec.h" +#include "../schema/ui_schema.h" +#include "imgui.h" +#include "imgui_internal.h" +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Elevation and Shadow System +// ============================================================================ +// Based on https://m2.material.io/design/environment/elevation.html +// +// Material Design uses two light sources to create shadows: +// - Key light: Creates sharper, directional shadows +// - Ambient light: Creates softer, omnidirectional shadows +// +// In dark themes, elevation is primarily shown through surface color overlays +// rather than shadows. However, shadows can still enhance depth perception. + +// ============================================================================ +// Shadow Specifications +// ============================================================================ + +/** + * @brief Individual shadow layer specification + * + * Material shadows are composed of multiple layers with different + * blur radii and offsets to simulate real-world lighting. + */ +struct ShadowLayer { + float offsetX; // Horizontal offset (typically 0) + float offsetY; // Vertical offset (key light from above) + float blurRadius; // Blur spread + float spreadRadius; // Size adjustment + float opacity; // Alpha 0.0-1.0 +}; + +/** + * @brief Complete shadow specification for an elevation level + */ +struct ShadowSpec { + ShadowLayer umbra; // Darkest part, sharp edge + ShadowLayer penumbra; // Mid-tone, softer + ShadowLayer ambient; // Lightest, most diffuse +}; + +/** + * @brief Get shadow specification for elevation level + * + * @param elevationDp Elevation in dp (0, 1, 2, 3, 4, 6, 8, 12, 16, 24) + * @return ShadowSpec for the elevation + */ +ShadowSpec GetShadowSpec(int elevationDp); + +// ============================================================================ +// Shadow Rendering +// ============================================================================ + +/** + * @brief Draw Material Design shadow for a rectangle + * + * Uses multi-layer soft shadow rendering to approximate Material shadows. + * + * @param drawList ImGui draw list + * @param rect Rectangle bounds + * @param elevationDp Elevation in dp + * @param cornerRadius Corner radius for rounded rectangles + */ +void DrawShadow(ImDrawList* drawList, const ImRect& rect, int elevationDp, float cornerRadius = 0); + +/** + * @brief Draw shadow with position/size parameters + */ +void DrawShadow(ImDrawList* drawList, const ImVec2& pos, const ImVec2& size, + int elevationDp, float cornerRadius = 0); + +/** + * @brief Draw soft shadow (single layer, for custom effects) + * + * @param drawList ImGui draw list + * @param rect Rectangle bounds + * @param color Shadow color with alpha + * @param blurRadius Blur amount + * @param offset Shadow offset + * @param cornerRadius Corner radius + */ +void DrawSoftShadow(ImDrawList* drawList, const ImRect& rect, ImU32 color, + float blurRadius, const ImVec2& offset = ImVec2(0, 0), + float cornerRadius = 0); + +// ============================================================================ +// Elevation Transition Helper +// ============================================================================ + +/** + * @brief Animated elevation value + * + * Use this to smoothly transition between elevation levels (e.g., card hover) + */ +class ElevationAnimator { +public: + ElevationAnimator(int initialElevation = 0); + + /** + * @brief Set target elevation (will animate towards it) + */ + void setTarget(int targetElevation); + + /** + * @brief Update animation (call each frame) + * @param deltaTime Frame delta time + */ + void update(float deltaTime); + + /** + * @brief Get current animated elevation value + */ + float getCurrent() const { return m_current; } + + /** + * @brief Get current elevation as integer (for shadow lookup) + */ + int getCurrentInt() const { return static_cast(m_current + 0.5f); } + + /** + * @brief Check if currently animating + */ + bool isAnimating() const { return m_current != m_target; } + +private: + float m_current; + float m_target; + float m_animationSpeed = 16.0f; // dp per second +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline ShadowSpec GetShadowSpec(int elevationDp) { + // Material Design shadow values adapted from the spec + // These approximate the CSS box-shadow values from material.io + + switch (elevationDp) { + case 0: + return { + {0, 0, 0, 0, 0}, // No shadow + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0} + }; + case 1: + return { + {0, 2, 1, -1, 0.2f}, // Umbra + {0, 1, 1, 0, 0.14f}, // Penumbra + {0, 1, 3, 0, 0.12f} // Ambient + }; + case 2: + return { + {0, 3, 1, -2, 0.2f}, + {0, 2, 2, 0, 0.14f}, + {0, 1, 5, 0, 0.12f} + }; + case 3: + return { + {0, 3, 3, -2, 0.2f}, + {0, 3, 4, 0, 0.14f}, + {0, 1, 8, 0, 0.12f} + }; + case 4: + return { + {0, 2, 4, -1, 0.2f}, + {0, 4, 5, 0, 0.14f}, + {0, 1, 10, 0, 0.12f} + }; + case 6: + return { + {0, 3, 5, -1, 0.2f}, + {0, 6, 10, 0, 0.14f}, + {0, 1, 18, 0, 0.12f} + }; + case 8: + return { + {0, 5, 5, -3, 0.2f}, + {0, 8, 10, 1, 0.14f}, + {0, 3, 14, 2, 0.12f} + }; + case 12: + return { + {0, 7, 8, -4, 0.2f}, + {0, 12, 17, 2, 0.14f}, + {0, 5, 22, 4, 0.12f} + }; + case 16: + return { + {0, 8, 10, -5, 0.2f}, + {0, 16, 24, 2, 0.14f}, + {0, 6, 30, 5, 0.12f} + }; + case 24: + return { + {0, 11, 15, -7, 0.2f}, + {0, 24, 38, 3, 0.14f}, + {0, 9, 46, 8, 0.12f} + }; + default: + // Interpolate for non-standard elevations + if (elevationDp < 0) return GetShadowSpec(0); + if (elevationDp > 24) return GetShadowSpec(24); + + // Find nearest standard elevation + int lower = 0, upper = 1; + int standards[] = {0, 1, 2, 3, 4, 6, 8, 12, 16, 24}; + for (int i = 0; i < 9; i++) { + if (standards[i] <= elevationDp && standards[i + 1] >= elevationDp) { + lower = standards[i]; + upper = standards[i + 1]; + break; + } + } + + // Use nearest + return GetShadowSpec((elevationDp - lower < upper - elevationDp) ? lower : upper); + } +} + +inline void DrawSoftShadow(ImDrawList* drawList, const ImRect& rect, ImU32 color, + float blurRadius, const ImVec2& offset, float cornerRadius) { + if (blurRadius <= 0 || (color & IM_COL32_A_MASK) == 0) + return; + + // For ImGui, we'll simulate soft shadows using multiple semi-transparent layers + // This is a performance-friendly approximation + + // In low-spec mode use only 1 layer instead of up to 8 + const int numLayers = dragonx::ui::effects::isLowSpecMode() + ? 1 + : ImClamp((int)(blurRadius / 2), 2, 8); + const float layerStep = blurRadius / numLayers; + + // Extract base alpha + float baseAlpha = ((color >> IM_COL32_A_SHIFT) & 0xFF) / 255.0f; + ImU32 baseColor = color & ~IM_COL32_A_MASK; + + for (int i = numLayers - 1; i >= 0; i--) { + float expansion = layerStep * (i + 1); + float alpha = baseAlpha * (1.0f - (float)i / numLayers) / numLayers; + + ImU32 layerColor = baseColor | (((ImU32)(alpha * 255)) << IM_COL32_A_SHIFT); + + ImRect expandedRect( + rect.Min.x - expansion + offset.x, + rect.Min.y - expansion + offset.y, + rect.Max.x + expansion + offset.x, + rect.Max.y + expansion + offset.y + ); + + drawList->AddRectFilled(expandedRect.Min, expandedRect.Max, layerColor, + cornerRadius + expansion * 0.5f); + } +} + +inline void DrawShadow(ImDrawList* drawList, const ImRect& rect, int elevationDp, float cornerRadius) { + if (elevationDp <= 0) + return; + + ShadowSpec spec = GetShadowSpec(elevationDp); + + // Shadow multiplier: light themes need stronger shadows for card depth, + // dark themes rely more on surface color overlay for elevation. + // Configurable via ui.toml [style] shadow-multiplier / shadow-multiplier-light. + const float shadowMultiplier = schema::UI().isDarkTheme() + ? schema::UI().drawElement("style", "shadow-multiplier").sizeOr(0.6f) + : schema::UI().drawElement("style", "shadow-multiplier-light").sizeOr(1.0f); + + // Draw ambient shadow (largest, most diffuse) + if (spec.ambient.opacity > 0) { + ImU32 ambientColor = IM_COL32(0, 0, 0, (int)(spec.ambient.opacity * shadowMultiplier * 255)); + ImRect ambientRect = rect; + ambientRect.Expand(spec.ambient.spreadRadius); + DrawSoftShadow(drawList, ambientRect, ambientColor, spec.ambient.blurRadius, + ImVec2(spec.ambient.offsetX, spec.ambient.offsetY), cornerRadius); + } + + // Draw penumbra (medium) + if (spec.penumbra.opacity > 0) { + ImU32 penumbraColor = IM_COL32(0, 0, 0, (int)(spec.penumbra.opacity * shadowMultiplier * 255)); + ImRect penumbraRect = rect; + penumbraRect.Expand(spec.penumbra.spreadRadius); + DrawSoftShadow(drawList, penumbraRect, penumbraColor, spec.penumbra.blurRadius, + ImVec2(spec.penumbra.offsetX, spec.penumbra.offsetY), cornerRadius); + } + + // Draw umbra (sharpest, darkest) + if (spec.umbra.opacity > 0) { + ImU32 umbraColor = IM_COL32(0, 0, 0, (int)(spec.umbra.opacity * shadowMultiplier * 255)); + ImRect umbraRect = rect; + umbraRect.Expand(spec.umbra.spreadRadius); + DrawSoftShadow(drawList, umbraRect, umbraColor, spec.umbra.blurRadius, + ImVec2(spec.umbra.offsetX, spec.umbra.offsetY), cornerRadius); + } +} + +inline void DrawShadow(ImDrawList* drawList, const ImVec2& pos, const ImVec2& size, + int elevationDp, float cornerRadius) { + ImRect rect(pos, ImVec2(pos.x + size.x, pos.y + size.y)); + DrawShadow(drawList, rect, elevationDp, cornerRadius); +} + +inline ElevationAnimator::ElevationAnimator(int initialElevation) + : m_current(static_cast(initialElevation)) + , m_target(static_cast(initialElevation)) +{ +} + +inline void ElevationAnimator::setTarget(int targetElevation) { + m_target = static_cast(targetElevation); +} + +inline void ElevationAnimator::update(float deltaTime) { + if (m_current == m_target) + return; + + float diff = m_target - m_current; + float change = m_animationSpeed * deltaTime; + + if (std::abs(diff) <= change) { + m_current = m_target; + } else { + m_current += (diff > 0 ? 1 : -1) * change; + } +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/gpu_mask.h b/src/ui/material/gpu_mask.h new file mode 100644 index 0000000..0def428 --- /dev/null +++ b/src/ui/material/gpu_mask.h @@ -0,0 +1,190 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// GPU alpha mask — the ImGui equivalent of CSS mask-image: linear-gradient(). +// Uses AddCallback to switch the GPU blend mode so that gradient quads +// multiply the framebuffer's alpha (and RGB) by the source alpha, producing +// a smooth per-pixel fade without vertex-spacing artefacts. + +#pragma once + +#include "imgui.h" + +#ifdef DRAGONX_USE_DX11 + #include +#else + #ifdef DRAGONX_HAS_GLAD + #include + #else + #include + #endif + #include // for SDL_GL_GetProcAddress +#endif + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Blend-mode callbacks — called by ImGui's backend during draw list rendering +// ============================================================================ + +#ifdef DRAGONX_USE_DX11 + +// Cached DX11 blend state for the mask pass +inline ID3D11BlendState* GetMaskBlendState() { + static ID3D11BlendState* s_maskBlend = nullptr; + if (!s_maskBlend) { + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return nullptr; + ID3D11Device* dev = *reinterpret_cast(io.BackendRendererUserData); + if (!dev) return nullptr; + + D3D11_BLEND_DESC desc = {}; + desc.RenderTarget[0].BlendEnable = TRUE; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_SRC_ALPHA; + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_SRC_ALPHA; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + dev->CreateBlendState(&desc, &s_maskBlend); + } + return s_maskBlend; +} + +// Switch to mask blend: dst *= srcAlpha (both RGB and A) +inline void MaskBlendCallback(const ImDrawList*, const ImDrawCmd*) { + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return; + // The ImGui DX11 backend stores the device as the first pointer + ID3D11Device* dev = *reinterpret_cast(io.BackendRendererUserData); + if (!dev) return; + ID3D11DeviceContext* ctx = nullptr; + dev->GetImmediateContext(&ctx); + if (!ctx) return; + + ID3D11BlendState* bs = GetMaskBlendState(); + if (bs) { + float blendFactor[4] = {0, 0, 0, 0}; + ctx->OMSetBlendState(bs, blendFactor, 0xFFFFFFFF); + } + ctx->Release(); +} + +// Restore normal ImGui blend: src*srcA + dst*(1-srcA) +inline void RestoreBlendCallback(const ImDrawList*, const ImDrawCmd*) { + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return; + ID3D11Device* dev = *reinterpret_cast(io.BackendRendererUserData); + if (!dev) return; + ID3D11DeviceContext* ctx = nullptr; + dev->GetImmediateContext(&ctx); + if (!ctx) return; + // Setting nullptr restores the default blend state that ImGui's DX11 + // backend configures at the start of each frame. + ctx->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF); + ctx->Release(); +} + +#else // OpenGL + +// glBlendFuncSeparate may not be in the GLAD profile — load it once via SDL. +typedef void (*PFN_glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum); +inline PFN_glBlendFuncSeparate GetBlendFuncSeparate() { + static PFN_glBlendFuncSeparate fn = nullptr; + static bool resolved = false; + if (!resolved) { + resolved = true; + fn = (PFN_glBlendFuncSeparate)(void*)SDL_GL_GetProcAddress("glBlendFuncSeparate"); + } + return fn; +} + +inline void MaskBlendCallback(const ImDrawList*, const ImDrawCmd*) { + // dst.rgb = dst.rgb * srcAlpha (erase content where mask alpha < 1) + // dst.a = dst.a * srcAlpha (match alpha channel) + auto fn = GetBlendFuncSeparate(); + if (fn) + fn(GL_ZERO, GL_SRC_ALPHA, GL_ZERO, GL_SRC_ALPHA); + else + glBlendFunc(GL_ZERO, GL_SRC_ALPHA); +} + +inline void RestoreBlendCallback(const ImDrawList*, const ImDrawCmd*) { + // Restore ImGui's exact blend state: + // RGB: src*srcA + dst*(1-srcA) + // Alpha: src*1 + dst*(1-srcA) + auto fn = GetBlendFuncSeparate(); + if (fn) + fn(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + else + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +} + +#endif + +// ============================================================================ +// DrawScrollFadeMask — draw gradient quads that mask the top/bottom edges +// of a scrollable child region, producing a smooth per-pixel fade. +// +// Call this on the child's draw list BEFORE EndChild(). +// The gradient quads use the mask blend mode to multiply the existing +// framebuffer content by their alpha, so alpha=1 means "keep" and +// alpha=0 means "erase to transparent/black". +// +// Parameters: +// dl — the child window's draw list (ImGui::GetWindowDrawList()) +// clipMin/Max — the child window's visible area (screen coords) +// fadeH — the height of the fade zone in pixels +// scrollY — current scroll offset (ImGui::GetScrollY()) +// scrollMaxY — maximum scroll offset (ImGui::GetScrollMaxY()) +// ============================================================================ +inline void DrawScrollFadeMask(ImDrawList* dl, + const ImVec2& clipMin, const ImVec2& clipMax, + float fadeH, + float scrollY, float scrollMaxY) +{ + if (fadeH <= 0.0f) return; + + bool needTop = scrollY > 1.0f; + bool needBottom = scrollMaxY > 0 && scrollY < scrollMaxY - 1.0f; + if (!needTop && !needBottom) return; + + float left = clipMin.x; + float right = clipMax.x; + + // Switch to mask blend mode + dl->AddCallback(MaskBlendCallback, nullptr); + + if (needTop) { + // Top gradient: alpha=0 at top edge (erase) → alpha=1 at top+fadeH (keep) + ImVec2 tMin(left, clipMin.y); + ImVec2 tMax(right, clipMin.y + fadeH); + ImU32 transparent = IM_COL32(0, 0, 0, 0); + ImU32 opaque = IM_COL32(0, 0, 0, 255); + dl->AddRectFilledMultiColor(tMin, tMax, + transparent, transparent, // top-left, top-right + opaque, opaque); // bottom-left, bottom-right + } + + if (needBottom) { + // Bottom gradient: alpha=1 at bottom-fadeH (keep) → alpha=0 at bottom (erase) + ImVec2 bMin(left, clipMax.y - fadeH); + ImVec2 bMax(right, clipMax.y); + ImU32 opaque = IM_COL32(0, 0, 0, 255); + ImU32 transparent = IM_COL32(0, 0, 0, 0); + dl->AddRectFilledMultiColor(bMin, bMax, + opaque, opaque, // top-left, top-right + transparent, transparent); // bottom-left, bottom-right + } + + // Restore normal blend mode + dl->AddCallback(RestoreBlendCallback, nullptr); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/layout.h b/src/ui/material/layout.h new file mode 100644 index 0000000..8bf2620 --- /dev/null +++ b/src/ui/material/layout.h @@ -0,0 +1,351 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design 8dp Grid System +// ============================================================================ +// All spacing in Material Design is based on an 8dp grid. +// https://m2.material.io/design/layout/spacing-methods.html + +constexpr float kGridUnit = 8.0f; // Base unit in dp (device-independent pixels) + +// ============================================================================ +// Spacing Scale +// ============================================================================ +// Use these values for all margins, padding, and gaps + +namespace spacing { + +constexpr float Xxs = 2.0f; // 0.25x - Very tight spacing +constexpr float Xs = 4.0f; // 0.5x - Extra small +constexpr float Sm = 8.0f; // 1x - Small (default minimum) +constexpr float Md = 16.0f; // 2x - Medium (default standard) +constexpr float Lg = 24.0f; // 3x - Large +constexpr float Xl = 32.0f; // 4x - Extra large +constexpr float Xxl = 40.0f; // 5x - Double extra large +constexpr float Xxxl = 48.0f; // 6x - Triple extra large + +// Multiplier helpers +constexpr float Grid(float multiplier) { return kGridUnit * multiplier; } + +} // namespace spacing + +// ============================================================================ +// Component Dimensions +// ============================================================================ +// Standard sizes for Material Design components + +namespace size { + +// Buttons +constexpr float ButtonHeight = 36.0f; +constexpr float ButtonMinWidth = 64.0f; +constexpr float ButtonPaddingH = 16.0f; +constexpr float ButtonPaddingV = 8.0f; +constexpr float ButtonIconGap = 8.0f; // Gap between icon and label +constexpr float ButtonCornerRadius = 4.0f; + +// FAB (Floating Action Button) +constexpr float FabSize = 56.0f; +constexpr float FabMiniSize = 40.0f; +constexpr float FabExtendedHeight = 48.0f; +constexpr float FabExtendedPadding = 16.0f; +constexpr float FabCornerRadius = 16.0f; // Half of mini size for circle + +// Icons +constexpr float IconSize = 24.0f; +constexpr float IconSizeSm = 18.0f; +constexpr float IconSizeLg = 36.0f; +constexpr float IconButtonSize = 48.0f; // Touch target for icon buttons + +// App Bar / Toolbar +constexpr float AppBarHeight = 56.0f; // Mobile +constexpr float AppBarHeightLarge = 64.0f; // Desktop +constexpr float AppBarPadding = 16.0f; + +// Navigation +constexpr float NavDrawerWidth = 256.0f; +constexpr float NavRailWidth = 72.0f; +constexpr float NavItemHeight = 48.0f; +constexpr float NavItemPadding = 12.0f; +constexpr float NavSectionPadding = 8.0f; + +// Cards +constexpr float CardCornerRadius = 4.0f; +constexpr float CardPadding = 16.0f; +constexpr float CardElevation = 1.0f; // Default elevation in dp + +// Dialogs +constexpr float DialogMinWidth = 280.0f; +constexpr float DialogMaxWidth = 560.0f; +constexpr float DialogPadding = 24.0f; +constexpr float DialogTitlePadding = 20.0f; +constexpr float DialogActionGap = 8.0f; +constexpr float DialogCornerRadius = 4.0f; + +// Lists +constexpr float ListItemHeight = 48.0f; // Single line +constexpr float ListItemHeightTwoLine = 64.0f; +constexpr float ListItemHeightThreeLine = 88.0f; +constexpr float ListItemPaddingH = 16.0f; +constexpr float ListAvatarSize = 40.0f; +constexpr float ListIconMargin = 32.0f; + +// Text Fields +constexpr float TextFieldHeight = 56.0f; +constexpr float TextFieldPadding = 16.0f; +constexpr float TextFieldDenseHeight = 40.0f; +constexpr float TextFieldCornerRadius = 4.0f; + +// Chips +constexpr float ChipHeight = 32.0f; +constexpr float ChipPaddingH = 12.0f; +constexpr float ChipCornerRadius = 16.0f; + +// Tabs +constexpr float TabHeight = 48.0f; +constexpr float TabMinWidth = 90.0f; +constexpr float TabMaxWidth = 360.0f; +constexpr float TabPaddingH = 16.0f; +constexpr float TabIndicatorHeight = 2.0f; + +// Snackbar +constexpr float SnackbarMinWidth = 288.0f; +constexpr float SnackbarMaxWidth = 568.0f; +constexpr float SnackbarHeight = 48.0f; +constexpr float SnackbarPadding = 8.0f; +constexpr float SnackbarMargin = 8.0f; + +// Dividers +constexpr float DividerThickness = 1.0f; +constexpr float DividerInset = 16.0f; // For inset dividers + +} // namespace size + +// ============================================================================ +// Responsive Breakpoints +// ============================================================================ +// Based on Material Design responsive layout grid + +namespace breakpoint { + +constexpr float Xs = 0.0f; // Extra small: 0-599dp +constexpr float Sm = 600.0f; // Small: 600-904dp +constexpr float Md = 905.0f; // Medium: 905-1239dp +constexpr float Lg = 1240.0f; // Large: 1240-1439dp +constexpr float Xl = 1440.0f; // Extra large: 1440dp+ + +// Returns the current breakpoint category +enum class Category { Xs, Sm, Md, Lg, Xl }; + +inline Category GetCategory(float windowWidth) { + if (windowWidth >= Xl) return Category::Xl; + if (windowWidth >= Lg) return Category::Lg; + if (windowWidth >= Md) return Category::Md; + if (windowWidth >= Sm) return Category::Sm; + return Category::Xs; +} + +// Margin values for each breakpoint +inline float GetMargin(Category cat) { + switch (cat) { + case Category::Xs: return 16.0f; + case Category::Sm: return 32.0f; + case Category::Md: return 32.0f; // Or fluid centering + case Category::Lg: return 200.0f; + case Category::Xl: return 200.0f; // Or fluid centering + } + return 16.0f; +} + +// Column count for each breakpoint +inline int GetColumns(Category cat) { + switch (cat) { + case Category::Xs: return 4; + case Category::Sm: return 8; + default: return 12; + } +} + +// Recommended navigation style +enum class NavStyle { BottomNav, NavRail, NavDrawer }; + +inline NavStyle GetNavStyle(Category cat) { + switch (cat) { + case Category::Xs: return NavStyle::BottomNav; + case Category::Sm: + case Category::Md: return NavStyle::NavRail; + default: return NavStyle::NavDrawer; + } +} + +} // namespace breakpoint + +// ============================================================================ +// Layout Helpers +// ============================================================================ + +/** + * @brief Get current window's breakpoint category + */ +inline breakpoint::Category GetCurrentBreakpoint() { + ImVec2 windowSize = ImGui::GetWindowSize(); + return breakpoint::GetCategory(windowSize.x); +} + +/** + * @brief Get recommended margin for current window + */ +inline float GetCurrentMargin() { + return breakpoint::GetMargin(GetCurrentBreakpoint()); +} + +/** + * @brief Add horizontal spacing (uses 8dp grid) + * @param units Number of 8dp units (default 1) + */ +inline void HSpace(float units = 1.0f) { + ImGui::SameLine(0, kGridUnit * units); +} + +/** + * @brief Add vertical spacing (uses 8dp grid) + * @param units Number of 8dp units (default 1) + */ +inline void VSpace(float units = 1.0f) { + ImGui::Dummy(ImVec2(0, kGridUnit * units)); +} + +/** + * @brief Begin a padded region + * @param padding Padding in pixels (use spacing:: constants) + */ +inline void BeginPadding(float padding) { + ImGui::BeginGroup(); + ImGui::Dummy(ImVec2(0, padding)); + ImGui::Indent(padding); +} + +/** + * @brief End a padded region + * @param padding Same padding used in BeginPadding + */ +inline void EndPadding(float padding) { + ImGui::Unindent(padding); + ImGui::Dummy(ImVec2(0, padding)); + ImGui::EndGroup(); +} + +/** + * @brief Center the next item horizontally within available width + * @param itemWidth Width of the item to center + */ +inline void CenterHorizontally(float itemWidth) { + float availWidth = ImGui::GetContentRegionAvail().x; + float offset = (availWidth - itemWidth) * 0.5f; + if (offset > 0) { + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offset); + } +} + +/** + * @brief Calculate column width for responsive grid + * @param numColumns Number of columns to span + * @param gutterWidth Gap between columns (default 16dp) + */ +inline float GetColumnWidth(int numColumns = 1, float gutterWidth = spacing::Md) { + float availWidth = ImGui::GetContentRegionAvail().x; + auto cat = GetCurrentBreakpoint(); + int totalColumns = breakpoint::GetColumns(cat); + + float totalGutter = gutterWidth * (totalColumns - 1); + float columnWidth = (availWidth - totalGutter) / totalColumns; + + return columnWidth * numColumns + gutterWidth * (numColumns - 1); +} + +// ============================================================================ +// Card Layout Helper +// ============================================================================ + +struct CardLayout { + float width; + float minHeight; + float padding; + float cornerRadius; + int elevation; + + CardLayout() + : width(0) // 0 = auto width + , minHeight(0) + , padding(size::CardPadding) + , cornerRadius(size::CardCornerRadius) + , elevation(1) + {} + + CardLayout& Width(float w) { width = w; return *this; } + CardLayout& MinHeight(float h) { minHeight = h; return *this; } + CardLayout& Padding(float p) { padding = p; return *this; } + CardLayout& CornerRadius(float r) { cornerRadius = r; return *this; } + CardLayout& Elevation(int e) { elevation = e; return *this; } +}; + +// ============================================================================ +// Navigation Drawer Item +// ============================================================================ + +struct NavItem { + const char* label; + const char* icon; // Icon font glyph or nullptr + bool selected; + bool enabled; + + NavItem(const char* lbl, const char* ico = nullptr) + : label(lbl), icon(ico), selected(false), enabled(true) + {} + + NavItem& Selected(bool s) { selected = s; return *this; } + NavItem& Enabled(bool e) { enabled = e; return *this; } +}; + +// ============================================================================ +// Alignment Helpers +// ============================================================================ + +/** + * @brief Align item to right edge of available space + * @param itemWidth Width of the item + */ +inline void AlignRight(float itemWidth) { + float availWidth = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - itemWidth); +} + +/** + * @brief Push items to start from right side (call before group of items) + */ +inline void BeginRightAlign() { + ImGui::BeginGroup(); +} + +/** + * @brief End right-aligned group and position it + */ +inline void EndRightAlign() { + ImGui::EndGroup(); + float groupWidth = ImGui::GetItemRectSize().x; + AlignRight(groupWidth); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/material.h b/src/ui/material/material.h new file mode 100644 index 0000000..32bc329 --- /dev/null +++ b/src/ui/material/material.h @@ -0,0 +1,160 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +// ============================================================================ +// Material Design 2 - Complete UI System +// ============================================================================ +// Based on https://m2.material.io/design/foundation-overview +// +// This header provides the complete Material Design 2 implementation for +// the DragonX Wallet ImGui interface. +// +// Namespace: dragonx::ui::material + +// Foundation +#include "color_theme.h" // ColorTheme struct, theme presets +#include "colors.h" // Color accessor functions +#include "typography.h" // Typography system, type scale +#include "layout.h" // Spacing grid, breakpoints, sizes + +// Effects +#include "elevation.h" // Shadow rendering, elevation animation +#include "ripple.h" // Touch ripple effect +#include "draw_helpers.h" // DrawTextShadow, DrawGlassPanel + +// Motion +#include "motion.h" // Easing curves, AnimatedValue, StaggerAnimation +#include "transitions.h" // View transitions, FadeTransition, ExpandableSection + +// Layout +#include "app_layout.h" // Application layout manager + +// Components +#include "components/components.h" // All Material components + +// ============================================================================ +// Quick Start Guide +// ============================================================================ +// +// 1. INITIALIZATION +// In your app startup, initialize the material system: +// +// ```cpp +// using namespace dragonx::ui::material; +// +// // Initialize color theme (creates global theme) +// SetDragonXTheme(); // or SetHushTheme() for HUSH variant +// +// // Initialize typography (load fonts) +// Typography::instance().initialize(io); +// ``` +// +// 2. FRAME SETUP +// At the start of each frame: +// +// ```cpp +// // Update ripple animations +// UpdateRipples(); +// ``` +// +// 3. USING COLORS +// Access theme colors with helper functions: +// +// ```cpp +// ImU32 bg = Background(); // App background +// ImU32 primary = Primary(); // Brand color +// ImU32 cardBg = Surface(Elevation::Dp4); // Elevated surface +// ImU32 text = OnSurface(); // Text on surfaces +// ``` +// +// 4. USING TYPOGRAPHY +// Render text with the type scale: +// +// ```cpp +// Typography::instance().text(TypeStyle::H6, "Section Title"); +// Typography::instance().text(TypeStyle::Body1, "Body text here..."); +// Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), "Hint"); +// ``` +// +// 5. USING COMPONENTS +// Components follow Material Design patterns: +// +// ```cpp +// // Buttons +// if (ContainedButton("Send")) { ... } +// if (OutlinedButton("Cancel")) { ... } +// if (TextButton("Learn More")) { ... } +// +// // Cards +// BeginCard(myCardSpec); +// CardHeader("Card Title", "Subtitle"); +// CardContent("Card body content..."); +// CardActions(); +// TextButton("Action 1"); +// TextButton("Action 2"); +// CardActionsEnd(); +// EndCard(); +// +// // Lists +// BeginList("myList"); +// if (ListItem("Item 1")) { ... } +// if (ListItem("Item 2", "Secondary text")) { ... } +// ListDivider(); +// if (ListItem("Item 3")) { ... } +// EndList(); +// +// // Dialogs +// static bool showDialog = false; +// if (ContainedButton("Open Dialog")) showDialog = true; +// int result = ConfirmDialog("confirm", &showDialog, "Confirm", +// "Are you sure?", "Yes", "No"); +// ``` +// +// 6. LAYOUT +// Use the spacing system for consistent layouts: +// +// ```cpp +// ImGui::Dummy(ImVec2(0, spacing::dp(2))); // 16dp vertical space +// ImGui::SetCursorPosX(spacing::dp(3)); // 24dp indent +// ``` +// +// ============================================================================ +// Module Reference +// ============================================================================ +// +// COLORS (colors.h) +// Primary(), PrimaryVariant(), PrimaryContainer() +// Secondary(), SecondaryVariant() +// Background(), Surface(elevation), SurfaceVariant() +// OnPrimary(), OnSecondary(), OnBackground(), OnSurface() +// OnSurfaceMedium(), OnSurfaceDisabled() +// Error(), OnError() +// StateHover(), StateFocus(), StatePressed(), StateSelected() +// +// TYPOGRAPHY (typography.h) +// TypeStyle: H1-H6, Subtitle1-2, Body1-2, Button, Caption, Overline +// Typography::text(style, text) +// Typography::textColored(style, color, text) +// Typography::textWrapped(style, text) +// Typography::pushFont(style) / popFont() +// +// LAYOUT (layout.h) +// spacing::dp(n) - n * 8dp +// spacing::Unit - 8dp +// size::TouchTarget - 48dp +// size::ButtonHeight - 36dp +// breakpoint::current() - Get current breakpoint +// +// ELEVATION (elevation.h) +// DrawShadow(drawList, rect, elevationDp, cornerRadius) +// ElevationAnimator - Smooth elevation transitions +// +// RIPPLE (ripple.h) +// DrawRippleEffect(drawList, rect, id, cornerRadius, hovered, held) +// UpdateRipples() - Call each frame +// +// COMPONENTS (components/components.h) +// See components.h for full component reference diff --git a/src/ui/material/motion.h b/src/ui/material/motion.h new file mode 100644 index 0000000..ab35e09 --- /dev/null +++ b/src/ui/material/motion.h @@ -0,0 +1,452 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Motion System +// ============================================================================ +// Based on https://m2.material.io/design/motion/speed.html +// and https://m2.material.io/design/motion/customization.html +// +// Material motion uses specific easing curves and durations to create +// natural, responsive animations that feel connected to user input. + +// ============================================================================ +// Standard Durations (in seconds) +// ============================================================================ + +namespace duration { + // Simple transitions (toggle, fade) + constexpr float Instant = 0.0f; + constexpr float VeryFast = 0.05f; // 50ms + constexpr float Fast = 0.1f; // 100ms - simple toggles + constexpr float Short = 0.15f; // 150ms + + // Standard transitions + constexpr float Medium = 0.2f; // 200ms - collapse, simple move + constexpr float Standard = 0.25f; // 250ms - expand, standard + constexpr float Long = 0.3f; // 300ms - large transforms + + // Complex transitions + constexpr float Complex = 0.375f; // 375ms + constexpr float VeryLong = 0.5f; // 500ms - elaborate sequences + + // Screen transitions + constexpr float EnterScreen = 0.225f; // Entering screen + constexpr float ExitScreen = 0.195f; // Leaving screen + constexpr float ScreenChange = 0.3f; // Full screen transition +} + +// ============================================================================ +// Easing Curves +// ============================================================================ + +/** + * @brief Cubic bezier curve evaluation + * + * Evaluates a cubic bezier curve defined by control points (0,0), (x1,y1), (x2,y2), (1,1) + * + * @param t Progress 0.0-1.0 + * @param x1 First control point X + * @param y1 First control point Y + * @param x2 Second control point X + * @param y2 Second control point Y + * @return Eased value + */ +float CubicBezier(float t, float x1, float y1, float x2, float y2); + +/** + * @brief Standard easing - for objects moving between on-screen positions + * + * CSS: cubic-bezier(0.4, 0.0, 0.2, 1.0) + * Starts quickly, slows down to rest + */ +float EaseStandard(float t); + +/** + * @brief Deceleration easing - for objects entering the screen + * + * CSS: cubic-bezier(0.0, 0.0, 0.2, 1.0) + * Starts at full velocity, decelerates to rest + */ +float EaseDecelerate(float t); + +/** + * @brief Acceleration easing - for objects leaving the screen + * + * CSS: cubic-bezier(0.4, 0.0, 1.0, 1.0) + * Accelerates from rest, exits at full speed + */ +float EaseAccelerate(float t); + +/** + * @brief Sharp easing - for objects that may return to screen + * + * CSS: cubic-bezier(0.4, 0.0, 0.6, 1.0) + * Quicker than standard, maintains connection + */ +float EaseSharp(float t); + +/** + * @brief Linear interpolation (no easing) + */ +float EaseLinear(float t); + +/** + * @brief Overshoot easing - goes past target then settles + * + * Good for bouncy, playful animations + */ +float EaseOvershoot(float t, float overshoot = 1.70158f); + +/** + * @brief Elastic easing - springy oscillation + */ +float EaseElastic(float t); + +// ============================================================================ +// Easing Function Type +// ============================================================================ + +using EasingFunction = float(*)(float); + +// ============================================================================ +// Animated Value +// ============================================================================ + +/** + * @brief Animated value with automatic interpolation + * + * Template class for smooth value transitions. + */ +template +class AnimatedValue { +public: + AnimatedValue(const T& initialValue = T()) + : m_current(initialValue) + , m_target(initialValue) + , m_start(initialValue) + , m_duration(duration::Standard) + , m_elapsed(0) + , m_easingFunc(EaseStandard) + , m_animating(false) + {} + + /** + * @brief Set target value with animation + */ + void animateTo(const T& target, float dur = duration::Standard, + EasingFunction easing = EaseStandard) { + if (target == m_target && m_animating) + return; // Already animating to this target + + m_start = m_current; + m_target = target; + m_duration = dur; + m_elapsed = 0; + m_easingFunc = easing; + m_animating = true; + } + + /** + * @brief Set value immediately (no animation) + */ + void set(const T& value) { + m_current = value; + m_target = value; + m_start = value; + m_animating = false; + } + + /** + * @brief Update animation (call each frame) + * @param deltaTime Frame delta time in seconds + */ + void update(float deltaTime) { + if (!m_animating) + return; + + m_elapsed += deltaTime; + + if (m_elapsed >= m_duration) { + m_current = m_target; + m_animating = false; + } else { + float t = m_elapsed / m_duration; + float eased = m_easingFunc(t); + m_current = lerp(m_start, m_target, eased); + } + } + + /** + * @brief Get current value + */ + const T& get() const { return m_current; } + + /** + * @brief Get target value + */ + const T& getTarget() const { return m_target; } + + /** + * @brief Check if currently animating + */ + bool isAnimating() const { return m_animating; } + + /** + * @brief Get animation progress (0-1) + */ + float getProgress() const { + if (!m_animating) return 1.0f; + return m_elapsed / m_duration; + } + + /** + * @brief Implicit conversion to value type + */ + operator const T&() const { return m_current; } + +private: + T m_current; + T m_target; + T m_start; + float m_duration; + float m_elapsed; + EasingFunction m_easingFunc; + bool m_animating; + + // Lerp specializations + static T lerp(const T& a, const T& b, float t) { + return a + (b - a) * t; + } +}; + +// Specialization for ImVec2 +template<> +inline ImVec2 AnimatedValue::lerp(const ImVec2& a, const ImVec2& b, float t) { + return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); +} + +// Specialization for ImVec4/color +template<> +inline ImVec4 AnimatedValue::lerp(const ImVec4& a, const ImVec4& b, float t) { + return ImVec4( + a.x + (b.x - a.x) * t, + a.y + (b.y - a.y) * t, + a.z + (b.z - a.z) * t, + a.w + (b.w - a.w) * t + ); +} + +// ============================================================================ +// Animation Sequencer +// ============================================================================ + +/** + * @brief Staggered animation for lists + * + * Creates staggered entrance animations for list items. + */ +class StaggerAnimation { +public: + StaggerAnimation(int itemCount, float staggerDelay = 0.05f, + float itemDuration = duration::EnterScreen) + : m_itemCount(itemCount) + , m_staggerDelay(staggerDelay) + , m_itemDuration(itemDuration) + , m_elapsed(0) + , m_running(false) + {} + + /** + * @brief Start the stagger animation + */ + void start() { + m_elapsed = 0; + m_running = true; + } + + /** + * @brief Update animation + */ + void update(float deltaTime) { + if (!m_running) return; + m_elapsed += deltaTime; + + // Check if all items have finished + float totalDuration = m_staggerDelay * (m_itemCount - 1) + m_itemDuration; + if (m_elapsed >= totalDuration) { + m_running = false; + } + } + + /** + * @brief Get animation progress for a specific item + * + * @param itemIndex Item index (0-based) + * @return Progress 0.0-1.0 (clamped) + */ + float getItemProgress(int itemIndex) const { + if (!m_running && m_elapsed > 0) + return 1.0f; // Animation complete + if (itemIndex < 0 || itemIndex >= m_itemCount) + return 0.0f; + + float itemStart = m_staggerDelay * itemIndex; + float itemElapsed = m_elapsed - itemStart; + + if (itemElapsed <= 0) return 0.0f; + if (itemElapsed >= m_itemDuration) return 1.0f; + + return EaseDecelerate(itemElapsed / m_itemDuration); + } + + /** + * @brief Get eased alpha for item (for fade-in) + */ + float getItemAlpha(int itemIndex) const { + return getItemProgress(itemIndex); + } + + /** + * @brief Get Y offset for item (for slide-in from bottom) + */ + float getItemYOffset(int itemIndex, float maxOffset = 20.0f) const { + float progress = getItemProgress(itemIndex); + return maxOffset * (1.0f - progress); + } + + bool isRunning() const { return m_running; } + +private: + int m_itemCount; + float m_staggerDelay; + float m_itemDuration; + float m_elapsed; + bool m_running; +}; + +// ============================================================================ +// Container Transform +// ============================================================================ + +/** + * @brief Container transform animation state + * + * For hero-style transitions where a card expands into a full dialog/page. + */ +struct ContainerTransform { + ImRect startRect; // Starting bounds (e.g., card) + ImRect endRect; // Ending bounds (e.g., dialog) + float progress; // 0 = start, 1 = end + bool expanding; // Direction + + ContainerTransform() + : progress(0) + , expanding(true) + {} + + /** + * @brief Get interpolated bounds at current progress + */ + ImRect getCurrentRect() const { + float t = expanding ? progress : (1.0f - progress); + float eased = EaseStandard(t); + + return ImRect( + ImLerp(startRect.Min, endRect.Min, eased), + ImLerp(startRect.Max, endRect.Max, eased) + ); + } + + /** + * @brief Get corner radius (shrinks as container expands) + */ + float getCornerRadius(float startRadius, float endRadius) const { + float t = expanding ? progress : (1.0f - progress); + float eased = EaseStandard(t); + return startRadius + (endRadius - startRadius) * eased; + } +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline float CubicBezier(float t, float x1, float y1, float x2, float y2) { + // Attempt to find t value for given x (Newton-Raphson approximation) + // This is needed because CSS bezier curves are defined in terms of x + + // For simplicity, we'll use a direct parametric approach + // which is accurate enough for UI animations + + float cx = 3.0f * x1; + float bx = 3.0f * (x2 - x1) - cx; + float ax = 1.0f - cx - bx; + + float cy = 3.0f * y1; + float by = 3.0f * (y2 - y1) - cy; + float ay = 1.0f - cy - by; + + // Sample y at parameter t + // Note: This assumes t directly maps to time, which is an approximation + // For more accuracy, we'd need to solve for the bezier parameter given x=t + + float t2 = t * t; + float t3 = t2 * t; + + return ay * t3 + by * t2 + cy * t; +} + +inline float EaseStandard(float t) { + // cubic-bezier(0.4, 0.0, 0.2, 1.0) + return CubicBezier(t, 0.4f, 0.0f, 0.2f, 1.0f); +} + +inline float EaseDecelerate(float t) { + // cubic-bezier(0.0, 0.0, 0.2, 1.0) + return CubicBezier(t, 0.0f, 0.0f, 0.2f, 1.0f); +} + +inline float EaseAccelerate(float t) { + // cubic-bezier(0.4, 0.0, 1.0, 1.0) + return CubicBezier(t, 0.4f, 0.0f, 1.0f, 1.0f); +} + +inline float EaseSharp(float t) { + // cubic-bezier(0.4, 0.0, 0.6, 1.0) + return CubicBezier(t, 0.4f, 0.0f, 0.6f, 1.0f); +} + +inline float EaseLinear(float t) { + return t; +} + +inline float EaseOvershoot(float t, float overshoot) { + // Back ease out + t = t - 1.0f; + return t * t * ((overshoot + 1.0f) * t + overshoot) + 1.0f; +} + +inline float EaseElastic(float t) { + if (t == 0.0f || t == 1.0f) return t; + + float p = 0.3f; + float s = p / 4.0f; + + return std::pow(2.0f, -10.0f * t) * std::sin((t - s) * (2.0f * IM_PI) / p) + 1.0f; +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/ripple.h b/src/ui/material/ripple.h new file mode 100644 index 0000000..b6a2542 --- /dev/null +++ b/src/ui/material/ripple.h @@ -0,0 +1,290 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "colors.h" +#include "../effects/low_spec.h" +#include "imgui.h" +#include "imgui_internal.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Ripple Effect +// ============================================================================ +// Based on https://m2.material.io/design/motion/customization.html +// +// Ripple effects provide visual feedback when users touch interactive elements. +// The ripple emanates from the touch point and expands outward. + +/** + * @brief Individual ripple instance + */ +struct Ripple { + ImVec2 center; // Ripple center point + float startTime; // When ripple started + float maxRadius; // Maximum expansion radius + ImU32 color; // Ripple color + bool releasing; // True when finger lifted + float releaseTime; // When release started + + Ripple(const ImVec2& center, float maxRadius, ImU32 color, float currentTime) + : center(center) + , startTime(currentTime) + , maxRadius(maxRadius) + , color(color) + , releasing(false) + , releaseTime(0) + {} +}; + +/** + * @brief Ripple effect manager + * + * Manages ripple animations for interactive elements. + */ +class RippleManager { +public: + static RippleManager& instance(); + + /** + * @brief Start a new ripple + * + * @param id Widget ID + * @param center Ripple center (touch point) + * @param maxRadius Maximum ripple radius + * @param color Ripple color (typically primary with low alpha) + */ + void startRipple(ImGuiID id, const ImVec2& center, float maxRadius, ImU32 color); + + /** + * @brief Release current ripple (finger lifted) + */ + void releaseRipple(ImGuiID id); + + /** + * @brief Draw ripple effect for a widget + * + * @param drawList Draw list to use + * @param id Widget ID + * @param clipRect Clip rectangle for the ripple + * @param cornerRadius Corner radius for clip shape + */ + void drawRipple(ImDrawList* drawList, ImGuiID id, const ImRect& clipRect, + float cornerRadius = 0); + + /** + * @brief Update all ripples (call once per frame) + */ + void update(); + + /** + * @brief Clear all ripples + */ + void clear(); + +private: + RippleManager() = default; + + struct RippleEntry { + ImGuiID id; + Ripple ripple; + }; + + std::vector m_ripples; + + static constexpr float kExpandDuration = 0.3f; // 300ms to full size + static constexpr float kFadeDuration = 0.2f; // 200ms fade out + static constexpr float kMaxOpacity = 0.12f; // 12% max opacity +}; + +// ============================================================================ +// Convenience Functions +// ============================================================================ + +/** + * @brief Draw ripple effect for a button/interactive element + * + * Call this after drawing the element background but before text/content. + * + * @param drawList Draw list + * @param rect Element bounds + * @param id Element ID + * @param cornerRadius Corner radius + * @param hovered Is element hovered + * @param held Is element being pressed + * @param color Optional ripple color (default: white for dark theme) + */ +void DrawRippleEffect(ImDrawList* drawList, const ImRect& rect, ImGuiID id, + float cornerRadius = 0, bool hovered = false, bool held = false, + ImU32 color = IM_COL32(255, 255, 255, 255)); + +/** + * @brief Update ripple system (call once per frame in main loop) + */ +void UpdateRipples(); + +// ============================================================================ +// Implementation +// ============================================================================ + +inline RippleManager& RippleManager::instance() { + static RippleManager s_instance; + return s_instance; +} + +inline void RippleManager::startRipple(ImGuiID id, const ImVec2& center, + float maxRadius, ImU32 color) { + float currentTime = (float)ImGui::GetTime(); + + // Check if ripple already exists for this ID + for (auto& entry : m_ripples) { + if (entry.id == id) { + // Reset existing ripple + entry.ripple = Ripple(center, maxRadius, color, currentTime); + return; + } + } + + // Add new ripple + m_ripples.push_back({id, Ripple(center, maxRadius, color, currentTime)}); +} + +inline void RippleManager::releaseRipple(ImGuiID id) { + float currentTime = (float)ImGui::GetTime(); + + for (auto& entry : m_ripples) { + if (entry.id == id && !entry.ripple.releasing) { + entry.ripple.releasing = true; + entry.ripple.releaseTime = currentTime; + } + } +} + +inline void RippleManager::drawRipple(ImDrawList* drawList, ImGuiID id, + const ImRect& clipRect, float cornerRadius) { + float currentTime = (float)ImGui::GetTime(); + + for (const auto& entry : m_ripples) { + if (entry.id != id) + continue; + + const Ripple& ripple = entry.ripple; + + // Calculate expansion progress + float expandProgress = (currentTime - ripple.startTime) / kExpandDuration; + expandProgress = ImClamp(expandProgress, 0.0f, 1.0f); + + // Deceleration easing for expansion + expandProgress = 1.0f - (1.0f - expandProgress) * (1.0f - expandProgress); + + float currentRadius = ripple.maxRadius * expandProgress; + + // Calculate opacity + float opacity = kMaxOpacity; + + if (ripple.releasing) { + float fadeProgress = (currentTime - ripple.releaseTime) / kFadeDuration; + fadeProgress = ImClamp(fadeProgress, 0.0f, 1.0f); + opacity *= (1.0f - fadeProgress); + } + + if (opacity <= 0.001f) + continue; + + // Extract color components + float r = ((ripple.color >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float g = ((ripple.color >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float b = ((ripple.color >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + ImU32 rippleColor = ImGui::ColorConvertFloat4ToU32(ImVec4(r, g, b, opacity)); + + // Push clip rect for rounded corners + if (cornerRadius > 0) { + // For rounded rectangles, we approximate with the clip rect + // A perfect solution would require custom clipping + drawList->PushClipRect(clipRect.Min, clipRect.Max, true); + } + + // Draw ripple circle (skip expanding animation in low-spec mode) + if (!dragonx::ui::effects::isLowSpecMode()) + drawList->AddCircleFilled(ripple.center, currentRadius, rippleColor, 32); + + if (cornerRadius > 0) { + drawList->PopClipRect(); + } + + break; // Only one ripple per ID + } +} + +inline void RippleManager::update() { + float currentTime = (float)ImGui::GetTime(); + + // Remove completed ripples + m_ripples.erase( + std::remove_if(m_ripples.begin(), m_ripples.end(), + [currentTime](const RippleEntry& entry) { + if (!entry.ripple.releasing) + return false; + float fadeProgress = (currentTime - entry.ripple.releaseTime) / kFadeDuration; + return fadeProgress >= 1.0f; + } + ), + m_ripples.end() + ); +} + +inline void RippleManager::clear() { + m_ripples.clear(); +} + +inline void DrawRippleEffect(ImDrawList* drawList, const ImRect& rect, ImGuiID id, + float cornerRadius, bool hovered, bool held, ImU32 color) { + RippleManager& manager = RippleManager::instance(); + + // Start ripple on press + if (held && ImGui::IsMouseClicked(0)) { + ImVec2 mousePos = ImGui::GetIO().MousePos; + // Calculate max radius (distance from click to farthest corner) + float dx1 = mousePos.x - rect.Min.x; + float dy1 = mousePos.y - rect.Min.y; + float dx2 = rect.Max.x - mousePos.x; + float dy2 = rect.Max.y - mousePos.y; + float maxDx = ImMax(dx1, dx2); + float maxDy = ImMax(dy1, dy2); + float maxRadius = std::sqrt(maxDx * maxDx + maxDy * maxDy) * 1.2f; + + manager.startRipple(id, mousePos, maxRadius, color); + } + + // Release ripple when mouse released + if (!held && !ImGui::IsMouseDown(0)) { + manager.releaseRipple(id); + } + + // Draw the ripple + manager.drawRipple(drawList, id, rect, cornerRadius); + + // Also draw hover state overlay + if (hovered && !held) { + float r = ((color >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float g = ((color >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float b = ((color >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + ImU32 hoverColor = ImGui::ColorConvertFloat4ToU32(ImVec4(r, g, b, 0.04f)); // 4% overlay + drawList->AddRectFilled(rect.Min, rect.Max, hoverColor, cornerRadius); + } +} + +inline void UpdateRipples() { + RippleManager::instance().update(); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/transitions.h b/src/ui/material/transitions.h new file mode 100644 index 0000000..10e4aca --- /dev/null +++ b/src/ui/material/transitions.h @@ -0,0 +1,467 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "motion.h" +#include "colors.h" +#include "imgui.h" +#include "imgui_internal.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Transitions +// ============================================================================ +// Based on https://m2.material.io/design/motion/the-motion-system.html +// +// Transition patterns for navigating between views and states. + +// ============================================================================ +// Transition Types +// ============================================================================ + +enum class TransitionType { + None, // Instant switch + Fade, // Cross-fade + SlideLeft, // Slide from right to left (forward navigation) + SlideRight, // Slide from left to right (back navigation) + SlideUp, // Slide from bottom (modal entry) + SlideDown, // Slide to bottom (modal exit) + Scale, // Scale up/down + SharedAxis, // Material shared axis transition + ContainerTransform // Card to full-screen +}; + +// ============================================================================ +// View Transition Manager +// ============================================================================ + +/** + * @brief Manages transitions between views/screens + */ +class TransitionManager { +public: + static TransitionManager& instance(); + + /** + * @brief Start a transition to a new view + * + * @param newViewId Identifier for the new view + * @param type Transition type + * @param duration Transition duration (default from motion.h) + */ + void transitionTo(const std::string& newViewId, + TransitionType type = TransitionType::Fade, + float duration = duration::ScreenChange); + + /** + * @brief Go back with reverse transition + */ + void goBack(TransitionType type = TransitionType::SlideRight, + float duration = duration::ExitScreen); + + /** + * @brief Update transition state (call each frame) + */ + void update(float deltaTime); + + /** + * @brief Get current view ID + */ + const std::string& getCurrentView() const { return m_currentView; } + + /** + * @brief Get previous view ID (during transition) + */ + const std::string& getPreviousView() const { return m_previousView; } + + /** + * @brief Check if transition is in progress + */ + bool isTransitioning() const { return m_transitioning; } + + /** + * @brief Get transition progress (0-1) + */ + float getProgress() const { return m_progress; } + + /** + * @brief Get current transition type + */ + TransitionType getType() const { return m_type; } + + /** + * @brief Apply transition effect to outgoing content + * + * Call before rendering the previous view content. + * Returns false if outgoing content should be skipped. + */ + bool beginOutgoingTransition(); + + /** + * @brief End outgoing content transition + */ + void endOutgoingTransition(); + + /** + * @brief Apply transition effect to incoming content + * + * Call before rendering the new view content. + * Returns false if incoming content should be skipped. + */ + bool beginIncomingTransition(); + + /** + * @brief End incoming content transition + */ + void endIncomingTransition(); + + /** + * @brief Get alpha for fading effects + */ + float getOutgoingAlpha() const; + float getIncomingAlpha() const; + + /** + * @brief Get offset for sliding effects + */ + ImVec2 getOutgoingOffset() const; + ImVec2 getIncomingOffset() const; + +private: + TransitionManager() = default; + + std::string m_currentView; + std::string m_previousView; + TransitionType m_type = TransitionType::None; + float m_duration = 0; + float m_elapsed = 0; + float m_progress = 0; + bool m_transitioning = false; +}; + +// ============================================================================ +// Fade Transition Helper +// ============================================================================ + +/** + * @brief Simple fade transition between two states + */ +class FadeTransition { +public: + FadeTransition() : m_alpha(1.0f) {} + + /** + * @brief Fade out + */ + void fadeOut(float duration = duration::Fast) { + m_alpha.animateTo(0.0f, duration, EaseAccelerate); + } + + /** + * @brief Fade in + */ + void fadeIn(float duration = duration::Fast) { + m_alpha.animateTo(1.0f, duration, EaseDecelerate); + } + + /** + * @brief Update (call each frame) + */ + void update(float deltaTime) { + m_alpha.update(deltaTime); + } + + /** + * @brief Get current alpha + */ + float getAlpha() const { return m_alpha.get(); } + + /** + * @brief Check if visible (alpha > 0) + */ + bool isVisible() const { return m_alpha.get() > 0.001f; } + + /** + * @brief Check if animating + */ + bool isAnimating() const { return m_alpha.isAnimating(); } + + /** + * @brief Push alpha to ImGui + */ + void pushAlpha() const { + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, m_alpha.get()); + } + + /** + * @brief Pop alpha from ImGui + */ + void popAlpha() const { + ImGui::PopStyleVar(); + } + +private: + AnimatedValue m_alpha; +}; + +// ============================================================================ +// Expandable/Collapsible Section +// ============================================================================ + +/** + * @brief Animated expandable section + */ +class ExpandableSection { +public: + ExpandableSection(bool initiallyExpanded = false) + : m_expanded(initiallyExpanded) + , m_height(initiallyExpanded ? 1.0f : 0.0f) + {} + + /** + * @brief Toggle expansion state + */ + void toggle() { + setExpanded(!m_expanded); + } + + /** + * @brief Set expansion state + */ + void setExpanded(bool expanded) { + m_expanded = expanded; + m_height.animateTo(expanded ? 1.0f : 0.0f, + expanded ? duration::Standard : duration::Medium, + EaseStandard); + } + + /** + * @brief Update animation + */ + void update(float deltaTime) { + m_height.update(deltaTime); + } + + /** + * @brief Check if expanded + */ + bool isExpanded() const { return m_expanded; } + + /** + * @brief Get height multiplier (0-1) + */ + float getHeightMultiplier() const { return m_height.get(); } + + /** + * @brief Check if animating + */ + bool isAnimating() const { return m_height.isAnimating(); } + + /** + * @brief Begin expandable content (applies clipping) + * + * @param maxHeight Maximum content height when fully expanded + * @return true if content should be rendered + */ + bool beginContent(float maxHeight) { + float currentHeight = maxHeight * m_height.get(); + + if (currentHeight < 1.0f) + return false; + + ImGui::BeginChild("##expandable", ImVec2(0, currentHeight), false, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + return true; + } + + /** + * @brief End expandable content + */ + void endContent() { + ImGui::EndChild(); + } + +private: + bool m_expanded; + AnimatedValue m_height; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline TransitionManager& TransitionManager::instance() { + static TransitionManager s_instance; + return s_instance; +} + +inline void TransitionManager::transitionTo(const std::string& newViewId, + TransitionType type, float duration) { + if (m_transitioning) + return; // Don't interrupt ongoing transition + + m_previousView = m_currentView; + m_currentView = newViewId; + m_type = type; + m_duration = duration; + m_elapsed = 0; + m_progress = 0; + m_transitioning = true; +} + +inline void TransitionManager::goBack(TransitionType type, float duration) { + if (m_transitioning || m_previousView.empty()) + return; + + std::string temp = m_currentView; + m_currentView = m_previousView; + m_previousView = temp; + m_type = type; + m_duration = duration; + m_elapsed = 0; + m_progress = 0; + m_transitioning = true; +} + +inline void TransitionManager::update(float deltaTime) { + if (!m_transitioning) + return; + + m_elapsed += deltaTime; + m_progress = m_elapsed / m_duration; + + if (m_progress >= 1.0f) { + m_progress = 1.0f; + m_transitioning = false; + m_previousView.clear(); + } +} + +inline bool TransitionManager::beginOutgoingTransition() { + if (!m_transitioning || m_type == TransitionType::None) + return false; + + float alpha = getOutgoingAlpha(); + if (alpha < 0.001f) + return false; + + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha); + + ImVec2 offset = getOutgoingOffset(); + if (offset.x != 0 || offset.y != 0) { + ImVec2 cursor = ImGui::GetCursorPos(); + ImGui::SetCursorPos(ImVec2(cursor.x + offset.x, cursor.y + offset.y)); + } + + return true; +} + +inline void TransitionManager::endOutgoingTransition() { + ImGui::PopStyleVar(); +} + +inline bool TransitionManager::beginIncomingTransition() { + if (!m_transitioning && m_progress >= 1.0f) + return true; // No transition, just render normally + + if (m_type == TransitionType::None) + return true; + + float alpha = getIncomingAlpha(); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha); + + ImVec2 offset = getIncomingOffset(); + if (offset.x != 0 || offset.y != 0) { + ImVec2 cursor = ImGui::GetCursorPos(); + ImGui::SetCursorPos(ImVec2(cursor.x + offset.x, cursor.y + offset.y)); + } + + return true; +} + +inline void TransitionManager::endIncomingTransition() { + if (m_transitioning || m_type != TransitionType::None) { + ImGui::PopStyleVar(); + } +} + +inline float TransitionManager::getOutgoingAlpha() const { + float eased = EaseAccelerate(m_progress); + + switch (m_type) { + case TransitionType::Fade: + return 1.0f - eased; + case TransitionType::Scale: + return 1.0f - eased; + default: + // For slides, fade quickly in first half + return m_progress < 0.5f ? 1.0f - eased * 2.0f : 0.0f; + } +} + +inline float TransitionManager::getIncomingAlpha() const { + float eased = EaseDecelerate(m_progress); + + switch (m_type) { + case TransitionType::Fade: + return eased; + case TransitionType::Scale: + return eased; + default: + // For slides, fade in during second half + return m_progress > 0.5f ? (eased - 0.5f) * 2.0f : 0.0f; + } +} + +inline ImVec2 TransitionManager::getOutgoingOffset() const { + ImGuiIO& io = ImGui::GetIO(); + float eased = EaseAccelerate(m_progress); + float slideDistance = 100.0f; // Pixels to slide + + switch (m_type) { + case TransitionType::SlideLeft: + return ImVec2(-slideDistance * eased, 0); + case TransitionType::SlideRight: + return ImVec2(slideDistance * eased, 0); + case TransitionType::SlideUp: + return ImVec2(0, -slideDistance * eased); + case TransitionType::SlideDown: + return ImVec2(0, slideDistance * eased); + case TransitionType::SharedAxis: + return ImVec2(-slideDistance * 0.3f * eased, 0); + default: + return ImVec2(0, 0); + } +} + +inline ImVec2 TransitionManager::getIncomingOffset() const { + float eased = EaseDecelerate(m_progress); + float slideDistance = 100.0f; + float remaining = 1.0f - eased; + + switch (m_type) { + case TransitionType::SlideLeft: + return ImVec2(slideDistance * remaining, 0); + case TransitionType::SlideRight: + return ImVec2(-slideDistance * remaining, 0); + case TransitionType::SlideUp: + return ImVec2(0, slideDistance * remaining); + case TransitionType::SlideDown: + return ImVec2(0, -slideDistance * remaining); + case TransitionType::SharedAxis: + return ImVec2(slideDistance * 0.3f * remaining, 0); + default: + return ImVec2(0, 0); + } +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/type.h b/src/ui/material/type.h new file mode 100644 index 0000000..aec5062 --- /dev/null +++ b/src/ui/material/type.h @@ -0,0 +1,144 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +// ============================================================================ +// Material Design Typography Quick Reference +// ============================================================================ +// +// Include this header for convenient access to the typography system. +// +// Usage: +// #include "ui/material/type.h" +// +// // Access fonts directly +// ImGui::PushFont(Type().h5()); +// ImGui::Text("Card Title"); +// ImGui::PopFont(); +// +// // Use text helpers +// Type().text(TypeStyle::H5, "Card Title"); +// Type().textColored(TypeStyle::Caption, OnSurfaceMedium(), "Timestamp"); +// +// // Scoped font (RAII) +// MATERIAL_FONT(Body1) { +// ImGui::TextWrapped("Body text goes here..."); +// } + +#pragma once + +#include "typography.h" +#include "colors.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Convenience Accessor +// ============================================================================ + +/** + * @brief Quick access to Typography singleton + * + * Usage: + * ImFont* title = Type().h5(); + * Type().text(TypeStyle::Body1, "Hello"); + */ +inline Typography& Type() { + return Typography::instance(); +} + +// ============================================================================ +// Text Style Constants for Quick Reference +// ============================================================================ + +// Headers (Large display text) +// H1: 96px Light - Rare, used for massive display numbers +// H2: 60px Light - Section banners +// H3: 48px Regular - Major section titles +// H4: 34px Regular - Page titles +// H5: 24px Regular - Card titles, dialog titles +// H6: 20px Medium - Section headers, sidebar items + +// Body (Primary content) +// Subtitle1: 16px Regular - Secondary information, list item primary text +// Subtitle2: 14px Medium - List item secondary text, menu items +// Body1: 16px Regular - Primary body text (default for content) +// Body2: 14px Regular - Secondary body text + +// UI Elements +// Button: 14px Medium, UPPERCASE - Button labels +// Caption: 12px Regular - Timestamps, hints, helper text +// Overline: 10px Regular, UPPERCASE - Section labels, tabs + +// ============================================================================ +// Common Typography Patterns +// ============================================================================ + +/** + * @brief Render a card header with title and optional subtitle + */ +inline void CardHeader(const char* title, const char* subtitle = nullptr) +{ + Type().text(TypeStyle::H5, title); + if (subtitle) { + Type().textColored(TypeStyle::Caption, OnSurfaceMedium(), subtitle); + } +} + +/** + * @brief Render an overline label (uppercase section marker) + */ +inline void OverlineLabel(const char* text) +{ + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), text); +} + +/** + * @brief Render body text + */ +inline void BodyText(const char* text, bool secondary = false) +{ + Type().text(secondary ? TypeStyle::Body2 : TypeStyle::Body1, text); +} + +/** + * @brief Render caption/helper text + */ +inline void Caption(const char* text) +{ + Type().textColored(TypeStyle::Caption, OnSurfaceMedium(), text); +} + +/** + * @brief Render error text + */ +inline void ErrorText(const char* text) +{ + Type().textColored(TypeStyle::Body2, Error(), text); +} + +/** + * @brief Render success text + */ +inline void SuccessText(const char* text) +{ + Type().textColored(TypeStyle::Body2, Success(), text); +} + +/** + * @brief Render a balance/amount display (large number) + */ +inline void AmountDisplay(const char* amount, const char* unit = nullptr) +{ + Type().text(TypeStyle::H4, amount); + if (unit) { + ImGui::SameLine(); + Type().textColored(TypeStyle::H6, OnSurfaceMedium(), unit); + } +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/typography.cpp b/src/ui/material/typography.cpp new file mode 100644 index 0000000..ec28ae5 --- /dev/null +++ b/src/ui/material/typography.cpp @@ -0,0 +1,401 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "typography.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include +#include +#include +#include + +// Embedded font data (via INCBIN – assembler .incbin directive) +#include "../embedded/embedded_fonts.h" // g_ubuntu_*_data/size, g_material_icons_* +#include "../embedded/IconsMaterialDesign.h" // Icon codepoint defines +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Type Scale Specifications +// ============================================================================ +// Font sizes are configured in ui/layout.h for easy global adjustment. +// Letter spacing, line height and text-transform are loaded from ui.toml +// via the UISchema typography section. +// Font sizes come from UISchema (JSON-configurable) via Layout:: accessors. + +const TypeSpec* Typography::getTypeSpecs() +{ + // Rebuild each call to pick up hot-reloaded values + static TypeSpec specs[kNumStyles]; + + // Helper: read typography entry from UISchema + auto& S = schema::UI(); + auto tspec = [&](const char* key, float defLS, float defLH, bool defUpper) -> TypeSpec { + auto e = S.drawElement("typography", key); + float ls = e.getFloat("letter-spacing", defLS); + float lh = e.getFloat("line-height", defLH); + // text-transform stored as extraColors (string map) + bool upper = defUpper; + auto it = e.extraColors.find("text-transform"); + if (it != e.extraColors.end()) { + upper = (it->second == "uppercase"); + } + return TypeSpec{0.0f, ls, lh, upper}; + }; + + // Font size comes from Layout:: accessors; typography from UISchema + auto ts0 = tspec("h1", -1.0f, 1.167f, false); + auto ts1 = tspec("h2", -0.5f, 1.2f, false); + auto ts2 = tspec("h3", 0.0f, 1.167f, false); + auto ts3 = tspec("h4", 0.25f, 1.235f, false); + auto ts4 = tspec("h5", 0.0f, 1.334f, false); + auto ts5 = tspec("h6", 0.15f, 1.6f, false); + auto ts6 = tspec("subtitle1", 0.15f, 1.75f, false); + auto ts7 = tspec("subtitle2", 0.1f, 1.57f, false); + auto ts8 = tspec("body1", 0.5f, 1.5f, false); + auto ts9 = tspec("body2", 0.25f, 1.43f, false); + auto ts10 = tspec("button", 1.25f, 1.75f, true); + auto ts11 = tspec("caption", 0.4f, 1.66f, false); + auto ts12 = tspec("overline", 1.5f, 2.66f, true); + + specs[0] = { Layout::kFontH1(), ts0.letterSpacing, ts0.lineHeight, ts0.uppercase }; + specs[1] = { Layout::kFontH2(), ts1.letterSpacing, ts1.lineHeight, ts1.uppercase }; + specs[2] = { Layout::kFontH3(), ts2.letterSpacing, ts2.lineHeight, ts2.uppercase }; + specs[3] = { Layout::kFontH4(), ts3.letterSpacing, ts3.lineHeight, ts3.uppercase }; + specs[4] = { Layout::kFontH5(), ts4.letterSpacing, ts4.lineHeight, ts4.uppercase }; + specs[5] = { Layout::kFontH6(), ts5.letterSpacing, ts5.lineHeight, ts5.uppercase }; + specs[6] = { Layout::kFontSubtitle1(), ts6.letterSpacing, ts6.lineHeight, ts6.uppercase }; + specs[7] = { Layout::kFontSubtitle2(), ts7.letterSpacing, ts7.lineHeight, ts7.uppercase }; + specs[8] = { Layout::kFontBody1(), ts8.letterSpacing, ts8.lineHeight, ts8.uppercase }; + specs[9] = { Layout::kFontBody2(), ts9.letterSpacing, ts9.lineHeight, ts9.uppercase }; + specs[10] = { Layout::kFontButton(), ts10.letterSpacing, ts10.lineHeight, ts10.uppercase }; + specs[11] = { Layout::kFontCaption(), ts11.letterSpacing, ts11.lineHeight, ts11.uppercase }; + specs[12] = { Layout::kFontOverline(), ts12.letterSpacing, ts12.lineHeight, ts12.uppercase }; + specs[13] = { Layout::kFontButtonSm(), ts10.letterSpacing, ts10.lineHeight, ts10.uppercase }; + specs[14] = { Layout::kFontButtonLg(), ts10.letterSpacing, ts10.lineHeight, ts10.uppercase }; + return specs; +} + +// ============================================================================ +// Typography Implementation +// ============================================================================ + +Typography& Typography::instance() +{ + static Typography s_instance; + return s_instance; +} + +bool Typography::reload(ImGuiIO& io, float dpiScale) +{ + if (!loaded_) { + return load(io, dpiScale); + } + DEBUG_LOGF("Typography: Reloading fonts for DPI scale %.2f\n", dpiScale); + // Clear existing fonts and reload + io.Fonts->Clear(); + loaded_ = false; + for (int i = 0; i < kNumStyles; ++i) fonts_[i] = nullptr; + for (int i = 0; i < kNumIconSizes; ++i) iconFonts_[i] = nullptr; + return load(io, dpiScale); +} + +bool Typography::load(ImGuiIO& io, float dpiScale) +{ + if (loaded_) { + DEBUG_LOGF("Typography: Already loaded\n"); + return true; + } + + dpiScale_ = dpiScale; + + // Multiply by dpiScale so fonts are the correct physical size. + // On Windows Per-Monitor DPI v2, SDL3 coordinates are physical pixels + // and DisplayFramebufferScale is 1.0 (no automatic upscaling). + // The window is resized by dpiScale in main.cpp so that fonts at + // size*dpiScale fit proportionally (no overflow). + float scale = dpiScale * Layout::kFontScale(); + DEBUG_LOGF("Typography: Loading Material Design type scale (DPI: %.2f, fontScale: %.2f, combined: %.2f)\n", dpiScale, Layout::kFontScale(), scale); + + // For ImGui, we need to load fonts at specific pixel sizes. + // Font sizes come from Layout:: accessors (backed by UISchema JSON) + + // Load fonts in order of TypeStyle enum + + // H1: Light + fonts_[0] = loadFont(io, kWeightLight, Layout::kFontH1() * scale, "H1"); + + // H2: Light + fonts_[1] = loadFont(io, kWeightLight, Layout::kFontH2() * scale, "H2"); + + // H3: Regular + fonts_[2] = loadFont(io, kWeightRegular, Layout::kFontH3() * scale, "H3"); + + // H4: Regular + fonts_[3] = loadFont(io, kWeightRegular, Layout::kFontH4() * scale, "H4"); + + // H5: Regular + fonts_[4] = loadFont(io, kWeightRegular, Layout::kFontH5() * scale, "H5"); + + // H6: Medium + fonts_[5] = loadFont(io, kWeightMedium, Layout::kFontH6() * scale, "H6"); + + // Subtitle1: Regular + fonts_[6] = loadFont(io, kWeightRegular, Layout::kFontSubtitle1() * scale, "Subtitle1"); + + // Subtitle2: Medium + fonts_[7] = loadFont(io, kWeightMedium, Layout::kFontSubtitle2() * scale, "Subtitle2"); + + // Body1: Regular (shares with Subtitle1 if same size) + if (Layout::kFontBody1() == Layout::kFontSubtitle1()) { + fonts_[8] = fonts_[6]; // Reuse Subtitle1 font + } else { + fonts_[8] = loadFont(io, kWeightRegular, Layout::kFontBody1() * scale, "Body1"); + } + + // Body2: Regular + fonts_[9] = loadFont(io, kWeightRegular, Layout::kFontBody2() * scale, "Body2"); + + // Button: Medium (shares with Subtitle2 if same size) + if (Layout::kFontButton() == Layout::kFontSubtitle2()) { + fonts_[10] = fonts_[7]; // Reuse Subtitle2 font + } else { + fonts_[10] = loadFont(io, kWeightMedium, Layout::kFontButton() * scale, "Button"); + } + + // Caption: Regular + fonts_[11] = loadFont(io, kWeightRegular, Layout::kFontCaption() * scale, "Caption"); + + // Overline: Regular + fonts_[12] = loadFont(io, kWeightRegular, Layout::kFontOverline() * scale, "Overline"); + + // ButtonSm: Medium + fonts_[13] = loadFont(io, kWeightMedium, Layout::kFontButtonSm() * scale, "ButtonSm"); + + // ButtonLg: Medium + fonts_[14] = loadFont(io, kWeightMedium, Layout::kFontButtonLg() * scale, "ButtonLg"); + + // --- Icon fonts at multiple sizes --- + // These are standalone fonts (not merged) so we can PushFont(iconXxx) for icon rendering. + iconFonts_[0] = loadIconFont(io, 14.0f * scale, "IconSmall"); + iconFonts_[1] = loadIconFont(io, 18.0f * scale, "IconMed"); + iconFonts_[2] = loadIconFont(io, 24.0f * scale, "IconLarge"); + iconFonts_[3] = loadIconFont(io, 40.0f * scale, "IconXL"); + + // Verify all fonts loaded + bool allLoaded = true; + for (int i = 0; i < kNumStyles; ++i) { + if (!fonts_[i]) { + DEBUG_LOGF("Typography: Warning - Font for style %d not loaded\n", i); + fonts_[i] = io.Fonts->Fonts.Size > 0 ? io.Fonts->Fonts[0] : nullptr; + allLoaded = false; + } + } + + // Set Body1 as the default font so that bare ImGui::Text() calls + // (status bar, dialogs, notifications, etc.) render at Body1 size + // instead of H1 (the first font loaded). + io.FontDefault = fonts_[static_cast(TypeStyle::Body1)]; + + loaded_ = true; + DEBUG_LOGF("Typography: Loaded %d font styles (default=Body1)\n", allLoaded ? kNumStyles : -1); + + return allLoaded; +} + +ImFont* Typography::loadFont(ImGuiIO& io, int weight, float size, const char* name) +{ + // Select font data based on weight + const unsigned char* fontData = nullptr; + unsigned int fontDataLen = 0; + + switch (weight) { + case kWeightLight: + fontData = g_ubuntu_light_data; + fontDataLen = g_ubuntu_light_size; + break; + case kWeightMedium: + fontData = g_ubuntu_medium_data; + fontDataLen = g_ubuntu_medium_size; + break; + case kWeightRegular: + default: + fontData = g_ubuntu_regular_data; + fontDataLen = g_ubuntu_regular_size; + break; + } + + // ImGui needs to own a copy of the font data + void* fontDataCopy = IM_ALLOC(fontDataLen); + memcpy(fontDataCopy, fontData, fontDataLen); + + ImFontConfig cfg; + cfg.FontDataOwnedByAtlas = true; // ImGui will free this + cfg.OversampleH = 2; + cfg.OversampleV = 1; + cfg.PixelSnapH = true; + + // Include default ASCII + Latin, Latin Extended (for Spanish/multilingual), + // plus arrows (⇄ U+21C4), math (≈ U+2248), + // general punctuation (— U+2014, … U+2026, etc.) + static const ImWchar glyphRanges[] = { + 0x0020, 0x00FF, // Basic Latin + Latin-1 Supplement + 0x0100, 0x024F, // Latin Extended-A + Latin Extended-B (Spanish, etc.) + 0x2000, 0x206F, // General Punctuation (em dash, ellipsis, etc.) + 0x2190, 0x21FF, // Arrows (includes ⇄ U+21C4, ↻ U+21BB) + 0x2200, 0x22FF, // Mathematical Operators (includes ≈ U+2248) + 0x2600, 0x26FF, // Miscellaneous Symbols (includes ⛏ U+26CF) + 0, + }; + cfg.GlyphRanges = glyphRanges; + + // Create a unique name for this font variant + snprintf(cfg.Name, sizeof(cfg.Name), "Ubuntu %s %.0fpx", + weight == kWeightLight ? "Light" : + weight == kWeightMedium ? "Medium" : "Regular", + size); + + ImFont* font = io.Fonts->AddFontFromMemoryTTF(fontDataCopy, fontDataLen, size, &cfg); + + if (font) { + DEBUG_LOGF("Typography: Loaded %s (%.0fpx) as '%s'\n", name, size, cfg.Name); + } else { + DEBUG_LOGF("Typography: Failed to load %s\n", name); + IM_FREE(fontDataCopy); + } + + return font; +} + +ImFont* Typography::loadIconFont(ImGuiIO& io, float size, const char* name) +{ + // ImGui needs to own a copy of the font data + void* fontDataCopy = IM_ALLOC(g_material_icons_size); + memcpy(fontDataCopy, g_material_icons_data, g_material_icons_size); + + ImFontConfig cfg; + cfg.FontDataOwnedByAtlas = true; + cfg.OversampleH = 2; + cfg.OversampleV = 1; + cfg.PixelSnapH = true; + cfg.MergeMode = false; // standalone icon font + cfg.GlyphMinAdvanceX = size; // monospace icons + + static const ImWchar iconRanges[] = { ICON_MIN_MD, ICON_MAX_16_MD, 0 }; + cfg.GlyphRanges = iconRanges; + + snprintf(cfg.Name, sizeof(cfg.Name), "MDIcons %.0fpx", size); + + ImFont* font = io.Fonts->AddFontFromMemoryTTF(fontDataCopy, g_material_icons_size, size, &cfg); + if (font) { + DEBUG_LOGF("Typography: Loaded icon font %s (%.0fpx)\n", name, size); + } else { + DEBUG_LOGF("Typography: Failed to load icon font %s\n", name); + IM_FREE(fontDataCopy); + } + return font; +} + +ImFont* Typography::getFont(TypeStyle style) const +{ + int index = static_cast(style); + if (index >= 0 && index < kNumStyles && fonts_[index]) { + return fonts_[index]; + } + // Return default font if not found + return ImGui::GetIO().Fonts->Fonts.Size > 0 ? + ImGui::GetIO().Fonts->Fonts[0] : nullptr; +} + +const TypeSpec& Typography::getSpec(TypeStyle style) const +{ + const TypeSpec* specs = getTypeSpecs(); + int index = static_cast(style); + if (index >= 0 && index < kNumStyles) { + return specs[index]; + } + // Return Body1 as default + return specs[static_cast(TypeStyle::Body1)]; +} + +void Typography::pushFont(TypeStyle style) const +{ + ImGui::PushFont(getFont(style)); +} + +void Typography::popFont() const +{ + ImGui::PopFont(); +} + +// ============================================================================ +// Text Rendering Helpers +// ============================================================================ + +void Typography::text(TypeStyle style, const char* text) const +{ + const TypeSpec& spec = getSpec(style); + pushFont(style); + + if (spec.uppercase) { + // Convert to uppercase + std::string upper; + upper.reserve(strlen(text)); + for (const char* p = text; *p; ++p) { + upper += static_cast(std::toupper(static_cast(*p))); + } + ImGui::TextUnformatted(upper.c_str()); + } else { + ImGui::TextUnformatted(text); + } + + popFont(); +} + +void Typography::textWrapped(TypeStyle style, const char* text) const +{ + const TypeSpec& spec = getSpec(style); + pushFont(style); + + if (spec.uppercase) { + std::string upper; + upper.reserve(strlen(text)); + for (const char* p = text; *p; ++p) { + upper += static_cast(std::toupper(static_cast(*p))); + } + ImGui::TextWrapped("%s", upper.c_str()); + } else { + ImGui::TextWrapped("%s", text); + } + + popFont(); +} + +void Typography::textColored(TypeStyle style, ImU32 color, const char* text) const +{ + const TypeSpec& spec = getSpec(style); + pushFont(style); + + ImVec4 colorVec = ImGui::ColorConvertU32ToFloat4(color); + + if (spec.uppercase) { + std::string upper; + upper.reserve(strlen(text)); + for (const char* p = text; *p; ++p) { + upper += static_cast(std::toupper(static_cast(*p))); + } + ImGui::TextColored(colorVec, "%s", upper.c_str()); + } else { + ImGui::TextColored(colorVec, "%s", text); + } + + popFont(); +} + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/material/typography.h b/src/ui/material/typography.h new file mode 100644 index 0000000..a22a4fb --- /dev/null +++ b/src/ui/material/typography.h @@ -0,0 +1,288 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include + +namespace dragonx { +namespace ui { +namespace material { + +// ============================================================================ +// Material Design Type Scale +// ============================================================================ +// Based on https://m2.material.io/design/typography/the-type-system.html +// +// The type scale is a combination of 13 styles that are supported by the +// type system. It contains reusable categories of text, each with an +// intended application and meaning. + +/** + * @brief Material Design typography style identifiers + */ +enum class TypeStyle { + H1, // 96sp Light - Large display headers + H2, // 60sp Light - Display headers + H3, // 48sp Regular - Section titles + H4, // 34sp Regular - Section titles + H5, // 24sp Regular - Card titles, dialog titles + H6, // 20sp Medium - Section headers, subtitles + Subtitle1, // 16sp Regular - Secondary information + Subtitle2, // 14sp Medium - Secondary information + Body1, // 16sp Regular - Primary body text + Body2, // 14sp Regular - Secondary body text + Button, // 14sp Medium - Button labels (uppercase) + Caption, // 12sp Regular - Timestamps, labels + Overline, // 10sp Regular - Overline labels (uppercase) + ButtonSm, // Small button labels + ButtonLg // Large button labels +}; + +/** + * @brief Typography specification for a type style + */ +struct TypeSpec { + float size; // Font size in sp (scaled pixels) + float letterSpacing; // Letter spacing in px (applied after scaling) + float lineHeight; // Line height multiplier + bool uppercase; // Whether text should be uppercase + + // Font weight is handled by which font is used (Light/Regular/Medium) +}; + +/** + * @brief Typography system managing Material Design fonts + * + * Loads Ubuntu fonts in Light, Regular, and Medium weights at multiple + * sizes to implement the Material Design type scale. + * + * Usage: + * // Initialize during startup (after ImGui context) + * dragonx::ui::material::Typography::instance().load(io); + * + * // Use fonts throughout the application + * ImGui::PushFont(Typography::instance().getFont(TypeStyle::H5)); + * ImGui::Text("Card Title"); + * ImGui::PopFont(); + * + * // Or use convenience functions + * Typography::instance().pushFont(TypeStyle::Body1); + * ImGui::TextWrapped("Body text here..."); + * Typography::instance().popFont(); + */ +class Typography { +public: + /** + * @brief Get the singleton instance + */ + static Typography& instance(); + + /** + * @brief Load all fonts for the type scale + * + * Must be called after ImGui context is created but before first frame. + * + * @param io ImGui IO reference + * @param dpiScale DPI scale factor (default 1.0) + * @return true if fonts loaded successfully + */ + bool load(ImGuiIO& io, float dpiScale = 1.0f); + + /** + * @brief Reload fonts at a new DPI scale + * + * Call when the display scale changes (e.g., window moved to a different + * DPI monitor). Clears the existing font atlas and reloads all fonts. + * + * @param io ImGui IO reference + * @param dpiScale New DPI scale factor + * @return true if fonts reloaded successfully + */ + bool reload(ImGuiIO& io, float dpiScale); + + /** + * @brief Check if typography system is loaded + */ + bool isLoaded() const { return loaded_; } + + /** + * @brief Get the current DPI scale + */ + float getDpiScale() const { return dpiScale_; } + + /** + * @brief Get font for a type style + * + * @param style The Material Design type style + * @return ImFont pointer (never null, returns default if not loaded) + */ + ImFont* getFont(TypeStyle style) const; + + /** + * @brief Get the spec for a type style + * + * @param style The Material Design type style + * @return TypeSpec with size, spacing, and line height + */ + const TypeSpec& getSpec(TypeStyle style) const; + + /** + * @brief Push font for a type style + * + * Convenience wrapper around ImGui::PushFont(getFont(style)) + */ + void pushFont(TypeStyle style) const; + + /** + * @brief Pop the current font + * + * Convenience wrapper around ImGui::PopFont() + */ + void popFont() const; + + // ======================================================================== + // Font Accessors (for common cases) + // ======================================================================== + + // Headers + ImFont* h1() const { return getFont(TypeStyle::H1); } + ImFont* h2() const { return getFont(TypeStyle::H2); } + ImFont* h3() const { return getFont(TypeStyle::H3); } + ImFont* h4() const { return getFont(TypeStyle::H4); } + ImFont* h5() const { return getFont(TypeStyle::H5); } + ImFont* h6() const { return getFont(TypeStyle::H6); } + + // Body text + ImFont* subtitle1() const { return getFont(TypeStyle::Subtitle1); } + ImFont* subtitle2() const { return getFont(TypeStyle::Subtitle2); } + ImFont* body1() const { return getFont(TypeStyle::Body1); } + ImFont* body2() const { return getFont(TypeStyle::Body2); } + + // UI elements + ImFont* button() const { return getFont(TypeStyle::Button); } + ImFont* buttonSm() const { return getFont(TypeStyle::ButtonSm); } + ImFont* buttonLg() const { return getFont(TypeStyle::ButtonLg); } + ImFont* caption() const { return getFont(TypeStyle::Caption); } + ImFont* overline() const { return getFont(TypeStyle::Overline); } + + // Icon fonts — Material Design Icons merged at specific pixel sizes + // Use these when you need to render an icon at a specific size via AddText/ImGui::Text. + // Common sizes: iconSmall (14px), iconMed (18px), iconLarge (24px). + ImFont* iconSmall() const { return iconFonts_[0] ? iconFonts_[0] : getFont(TypeStyle::Body2); } + ImFont* iconMed() const { return iconFonts_[1] ? iconFonts_[1] : getFont(TypeStyle::Body1); } + ImFont* iconLarge() const { return iconFonts_[2] ? iconFonts_[2] : getFont(TypeStyle::H5); } + ImFont* iconXL() const { return iconFonts_[3] ? iconFonts_[3] : getFont(TypeStyle::H3); } + + /** + * @brief Resolve a font name string to ImFont* + * @param name Font name like "button", "button-sm", "button-lg", "h4", "body1" + * @return ImFont* pointer, or nullptr if name is empty/unknown + */ + ImFont* resolveByName(const std::string& name) const { + if (name.empty()) return nullptr; + if (name == "h1") return h1(); + if (name == "h2") return h2(); + if (name == "h3") return h3(); + if (name == "h4") return h4(); + if (name == "h5") return h5(); + if (name == "h6") return h6(); + if (name == "subtitle1") return subtitle1(); + if (name == "subtitle2") return subtitle2(); + if (name == "body1") return body1(); + if (name == "body2") return body2(); + if (name == "button") return button(); + if (name == "button-sm") return buttonSm(); + if (name == "button-lg") return buttonLg(); + if (name == "caption") return caption(); + if (name == "overline") return overline(); + return nullptr; + } + + // ======================================================================== + // Text Rendering Helpers + // ======================================================================== + + /** + * @brief Render text with a specific type style + * + * Handles font push/pop and optional uppercase transformation. + * + * @param style The type style to use + * @param text The text to render + */ + void text(TypeStyle style, const char* text) const; + + /** + * @brief Render wrapped text with a specific type style + * + * @param style The type style to use + * @param text The text to render + */ + void textWrapped(TypeStyle style, const char* text) const; + + /** + * @brief Render colored text with a specific type style + * + * @param style The type style to use + * @param color Text color + * @param text The text to render + */ + void textColored(TypeStyle style, ImU32 color, const char* text) const; + +private: + Typography() = default; + ~Typography() = default; + Typography(const Typography&) = delete; + Typography& operator=(const Typography&) = delete; + + // Load fonts at a specific size with a specific weight + ImFont* loadFont(ImGuiIO& io, int weight, float size, const char* name); + + // Font weight constants + static constexpr int kWeightLight = 300; + static constexpr int kWeightRegular = 400; + static constexpr int kWeightMedium = 500; + + bool loaded_ = false; + float dpiScale_ = 1.0f; + + // Fonts for each type style + ImFont* fonts_[15] = {}; + + // Icon fonts at different sizes: [0]=small(14), [1]=med(18), [2]=large(24), [3]=xl(40) + ImFont* iconFonts_[4] = {}; + static constexpr int kNumIconSizes = 4; + + // Load an icon-only font at a specific pixel size + ImFont* loadIconFont(ImGuiIO& io, float size, const char* name); + + // Type specifications + static const TypeSpec* getTypeSpecs(); + static constexpr int kNumStyles = 15; +}; + +// ============================================================================ +// Convenience Macros (Optional) +// ============================================================================ + +// Scoped font push/pop using RAII +class ScopedFont { +public: + explicit ScopedFont(TypeStyle style) { + Typography::instance().pushFont(style); + } + ~ScopedFont() { + Typography::instance().popFont(); + } +}; + +// Usage: MATERIAL_FONT(H5) { ImGui::Text("Title"); } +#define MATERIAL_FONT(style) \ + if (dragonx::ui::material::ScopedFont _font{dragonx::ui::material::TypeStyle::style}; true) + +} // namespace material +} // namespace ui +} // namespace dragonx diff --git a/src/ui/notifications.cpp b/src/ui/notifications.cpp new file mode 100644 index 0000000..7f0b012 --- /dev/null +++ b/src/ui/notifications.cpp @@ -0,0 +1,156 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "notifications.h" +#include "schema/ui_schema.h" +#include "material/type.h" +#include "material/draw_helpers.h" +#include "../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +void Notifications::render() +{ + // Remove expired notifications + while (!notifications_.empty() && notifications_.front().isExpired()) { + notifications_.pop_front(); + } + + if (notifications_.empty()) { + return; + } + + // Only show the most recent (last) notification as a compact status-bar pill + const auto& notif = notifications_.back(); + + const auto& S = schema::UI(); + auto nde = [&](const char* key, float fb) { + float v = S.drawElement("components.notifications", key).size; + return v >= 0 ? v : fb; + }; + + // Status bar geometry + float sbHeight = S.window("components.status-bar").height; + if (sbHeight <= 0.0f) sbHeight = 30.0f; + + ImGuiViewport* viewport = ImGui::GetMainViewport(); + float viewBottom = viewport->WorkPos.y + viewport->WorkSize.y; + float viewCenterX = viewport->WorkPos.x + viewport->WorkSize.x * 0.5f; + + // Toast pill sizing — fit inside status bar with margin + float pillMarginY = nde("pill-margin-y", 3.0f); + float pillHeight = sbHeight - pillMarginY * 2.0f; + float pillPadX = nde("padding-x", 12.0f); + float pillRounding = nde("pill-rounding", 12.0f); + + // Get accent color based on type — resolved from theme palette + ImVec4 accent_color, text_color; + const char* icon = ""; + + switch (notif.type) { + case NotificationType::Success: + accent_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-success-accent)", IM_COL32(50, 180, 80, 255))); + text_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-success-text)", IM_COL32(180, 255, 180, 255))); + icon = ICON_MD_CHECK_CIRCLE; + break; + case NotificationType::Warning: + accent_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-warning-accent)", IM_COL32(204, 166, 50, 255))); + text_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-warning-text)", IM_COL32(255, 230, 130, 255))); + icon = ICON_MD_WARNING; + break; + case NotificationType::Error: + accent_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-error-accent)", IM_COL32(204, 64, 64, 255))); + text_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-error-text)", IM_COL32(255, 153, 153, 255))); + icon = ICON_MD_ERROR; + break; + case NotificationType::Info: + default: + accent_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-info-accent)", IM_COL32(100, 160, 220, 255))); + text_color = ImGui::ColorConvertU32ToFloat4(S.resolveColor("var(--toast-info-text)", IM_COL32(215, 235, 255, 255))); + icon = ICON_MD_INFO; + break; + } + + // Calculate fade based on progress + float progress = notif.getProgress(); + float alpha = 1.0f; + if (progress > 0.7f) { + // Fade out in last 30% + alpha = (1.0f - progress) / 0.3f; + } + + accent_color.w *= alpha; + text_color.w *= alpha; + + // Measure text width to auto-size the pill + ImFont* textFont = material::Type().caption(); + ImFont* iconFont = material::Type().iconSmall(); + float iconW = iconFont ? iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0.0f, icon).x : 0.0f; + float iconGap = 4.0f; + float msgW = textFont ? textFont->CalcTextSizeA(textFont->LegacySize, FLT_MAX, 0.0f, notif.message.c_str()).x : 100.0f; + float pillWidth = pillPadX + iconW + iconGap + msgW + pillPadX; + // Clamp to reasonable bounds + float maxPillW = viewport->WorkSize.x * 0.5f; + if (pillWidth > maxPillW) pillWidth = maxPillW; + + // Position: centered horizontally, inside status bar vertically + float pillX = viewCenterX - pillWidth * 0.5f; + float pillY = viewBottom - sbHeight + pillMarginY; + + // Draw directly on foreground draw list (no ImGui window overhead) + ImDrawList* dl = ImGui::GetForegroundDrawList(); + ImVec2 pMin(pillX, pillY); + ImVec2 pMax(pillX + pillWidth, pillY + pillHeight); + + // Glass card background — translucent white fill + noise grain + light border + int glassAlpha = (int)(nde("glass-fill-alpha", 18.0f) * alpha); + int glassBorderAlpha = (int)(nde("glass-border-alpha", 35.0f) * alpha); + material::GlassPanelSpec glassSpec; + glassSpec.rounding = pillRounding; + glassSpec.fillAlpha = glassAlpha; + glassSpec.borderAlpha = glassBorderAlpha; + glassSpec.borderWidth = 1.0f; + material::DrawGlassPanel(dl, pMin, pMax, glassSpec); + + // Colored accent border on top of the glass border for type indication + ImU32 accentCol = ImGui::ColorConvertFloat4ToU32(accent_color); + dl->AddRect(pMin, pMax, accentCol, pillRounding, 0, 1.0f); + + // Progress bar at bottom of pill (accent-colored), clipped to pill rounded + // corners. Draw a full-pill-size rounded rect and clip it to just the + // bottom-left progress strip so both bottom corners are respected. + float progH = nde("progress-bar-height", 2.0f); + float progW = pillWidth * (1.0f - progress); + if (progW > 0.0f) { + ImVec2 clipMin(pillX, pMax.y - progH); + ImVec2 clipMax(pillX + progW, pMax.y); + dl->PushClipRect(clipMin, clipMax, true); + dl->AddRectFilled(pMin, pMax, accentCol, pillRounding); + dl->PopClipRect(); + } + + // Icon + text vertically centered + float contentY = pillY + (pillHeight - (textFont ? textFont->LegacySize : 14.0f)) * 0.5f; + float cursorX = pillX + pillPadX; + + // Icon (accent colored) + if (iconFont) { + float iconY = pillY + (pillHeight - iconFont->LegacySize) * 0.5f; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cursorX, iconY), accentCol, icon); + cursorX += iconW + iconGap; + } + + // Message text (clipped to pill bounds) + if (textFont) { + ImU32 textCol = ImGui::ColorConvertFloat4ToU32(text_color); + dl->PushClipRect(ImVec2(cursorX, pillY), ImVec2(pMax.x - pillPadX, pMax.y), true); + dl->AddText(textFont, textFont->LegacySize, ImVec2(cursorX, contentY), textCol, notif.message.c_str()); + dl->PopClipRect(); + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/notifications.h b/src/ui/notifications.h new file mode 100644 index 0000000..3b3c77c --- /dev/null +++ b/src/ui/notifications.h @@ -0,0 +1,147 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include +#include "../util/logger.h" +#include "schema/ui_schema.h" + +namespace dragonx { +namespace ui { + +enum class NotificationType { + Info, + Success, + Warning, + Error +}; + +struct Notification { + std::string message; + NotificationType type; + std::chrono::steady_clock::time_point created_at; + float duration_seconds; + + Notification(const std::string& msg, NotificationType t, float duration = 5.0f) + : message(msg) + , type(t) + , created_at(std::chrono::steady_clock::now()) + , duration_seconds(duration) + {} + + bool isExpired() const { + auto now = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration(now - created_at).count(); + return elapsed >= duration_seconds; + } + + float getProgress() const { + auto now = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration(now - created_at).count(); + return std::min(1.0f, elapsed / duration_seconds); + } +}; + +/** + * @brief Simple notification manager for user feedback + * + * Usage: + * Notifications::instance().info("Transaction sent!"); + * Notifications::instance().error("Connection failed"); + */ +class Notifications { +public: + static Notifications& instance() { + static Notifications inst; + return inst; + } + + void info(const std::string& message, float duration = -1.0f) { + if (duration < 0.0f) duration = schemaDuration("duration-info", 1.0f); + push(message, NotificationType::Info, duration); + } + + void success(const std::string& message, float duration = -1.0f) { + if (duration < 0.0f) duration = schemaDuration("duration-success", 2.5f); + push(message, NotificationType::Success, duration); + } + + void warning(const std::string& message, float duration = -1.0f) { + if (duration < 0.0f) duration = schemaDuration("duration-warning", 3.5f); + push(message, NotificationType::Warning, duration); + } + + void error(const std::string& message, float duration = -1.0f) { + if (duration < 0.0f) duration = schemaDuration("duration-error", 4.0f); + push(message, NotificationType::Error, duration); + } + + void push(const std::string& message, NotificationType type, float duration = 5.0f) { + notifications_.emplace_back(message, type, duration); + + // Log errors and warnings (debug-only output) + if (type == NotificationType::Error) { + DEBUG_LOGF("[ERROR] Notification: %s\n", message.c_str()); + } else if (type == NotificationType::Warning) { + DEBUG_LOGF("[WARN] Notification: %s\n", message.c_str()); + } + + // Forward errors and warnings to console callback + if (console_callback_ && (type == NotificationType::Error || type == NotificationType::Warning)) { + const char* prefix = (type == NotificationType::Error) ? "[ERROR] " : "[WARN] "; + console_callback_(prefix + message, type == NotificationType::Error); + } + + // Limit max notifications + while (notifications_.size() > max_notifications_) { + notifications_.pop_front(); + } + } + + /// Set a callback that receives error/warning messages (e.g. console tab) + void setConsoleCallback(std::function cb) { + console_callback_ = std::move(cb); + } + + void render(); + + /// @brief Check if there are non-expired notifications (needs continuous frames for animation) + bool hasActive() const { + for (const auto& n : notifications_) { + if (!n.isExpired()) return true; + } + return false; + } + + void clear() { + notifications_.clear(); + } + + void setMaxNotifications(size_t max) { + max_notifications_ = max; + } + +private: + Notifications() = default; + ~Notifications() = default; + Notifications(const Notifications&) = delete; + Notifications& operator=(const Notifications&) = delete; + + std::deque notifications_; + size_t max_notifications_ = 5; + std::function console_callback_; + + static float schemaDuration(const char* key, float fallback) { + float v = schema::UI().drawElement("components.notifications", key).size; + return v > 0.0f ? v : fallback; + } +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/pages/settings_page.cpp b/src/ui/pages/settings_page.cpp new file mode 100644 index 0000000..8360e0a --- /dev/null +++ b/src/ui/pages/settings_page.cpp @@ -0,0 +1,1805 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "settings_page.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../config/settings.h" +#include "../windows/balance_tab.h" +#include "../windows/console_tab.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../theme.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../schema/skin_manager.h" +#include "../notifications.h" +#include "../effects/imgui_acrylic.h" +#include "../effects/theme_effects.h" +#include "../effects/low_spec.h" +#include "../effects/scroll_fade_shader.h" +#include "../material/draw_helpers.h" +#include "../material/type.h" +#include "../material/colors.h" +#include "../windows/validate_address_dialog.h" +#include "../windows/address_book_dialog.h" +#include "../windows/shield_dialog.h" +#include "../windows/request_payment_dialog.h" +#include "../windows/block_info_dialog.h" +#include "../windows/export_all_keys_dialog.h" +#include "../windows/export_transactions_dialog.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ============================================================================ +// Settings state — loaded from config::Settings on first render +// ============================================================================ +static bool sp_initialized = false; +static int sp_language_index = 0; +static bool sp_save_ztxs = true; +static bool sp_allow_custom_fees = false; +static bool sp_auto_shield = false; +static bool sp_fetch_prices = true; +static bool sp_use_tor = false; +static char sp_rpc_host[128] = DRAGONX_DEFAULT_RPC_HOST; +static char sp_rpc_port[16] = DRAGONX_DEFAULT_RPC_PORT; +static char sp_rpc_user[64] = ""; +static char sp_rpc_password[64] = ""; +static char sp_tx_explorer[256] = "https://explorer.dragonx.is/tx/"; +static char sp_addr_explorer[256] = "https://explorer.dragonx.is/address/"; + +// Acrylic settings +static bool sp_acrylic_enabled = true; +static float sp_blur_amount = 1.5f; // 0.0=Off, 0.01–4.0 continuous blur multiplier +static float sp_noise_opacity = 0.5f; // 0.0–1.0 multiplier +static float sp_ui_opacity = 1.0f; // 0.3–1.0 card/sidebar opacity +static float sp_window_opacity = 1.0f; // 0.3–1.0 background alpha + +// Balance layout (string ID) +static std::string sp_balance_layout = "classic"; + +// Console scanline +static bool sp_scanline_enabled = true; + +// Theme effects +static bool sp_theme_effects_enabled = true; + +// Gradient background mode +static bool sp_gradient_background = false; + +// Low-spec mode +static bool sp_low_spec_mode = false; + +// Snapshot of effect settings saved when low-spec is toggled ON, +// restored when toggled OFF so user state isn't lost. +struct LowSpecSnapshot { + bool valid = false; + bool acrylic_enabled; + float blur_amount; + float ui_opacity; + float window_opacity; + bool theme_effects_enabled; + bool scanline_enabled; +}; +static LowSpecSnapshot s_lowSpecSnap; + +// Daemon — keep running on close +static bool sp_keep_daemon_running = false; +static bool sp_stop_external_daemon = false; + +// Debug logging categories +static std::set sp_debug_categories; +static bool sp_debug_cats_dirty = false; // true when changed but daemon not yet restarted +static bool sp_debug_expanded = false; // collapsible card state + +// (APPEARANCE card now uses ChannelsSplit like all other cards) + +// Shader-based scroll-edge fade (per-pixel alpha mask via custom fragment shader) +static effects::ScrollFadeShader s_fadeShader; + + + +static void loadSettingsPageState(config::Settings* settings) { + if (!settings) return; + + sp_save_ztxs = settings->getSaveZtxs(); + sp_allow_custom_fees = settings->getAllowCustomFees(); + sp_auto_shield = settings->getAutoShield(); + sp_fetch_prices = settings->getFetchPrices(); + sp_use_tor = settings->getUseTor(); + + strncpy(sp_tx_explorer, settings->getTxExplorerUrl().c_str(), sizeof(sp_tx_explorer) - 1); + strncpy(sp_addr_explorer, settings->getAddressExplorerUrl().c_str(), sizeof(sp_addr_explorer) - 1); + + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::string current_lang = settings->getLanguage(); + if (current_lang.empty()) current_lang = "en"; + + sp_language_index = 0; + int idx = 0; + for (const auto& lang : languages) { + if (lang.first == current_lang) { + sp_language_index = idx; + break; + } + idx++; + } + + // Load blur amount directly from saved multiplier + sp_blur_amount = settings->getBlurMultiplier(); + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + sp_ui_opacity = settings->getUIOpacity(); + sp_window_opacity = settings->getWindowOpacity(); + sp_noise_opacity = settings->getNoiseOpacity(); + + sp_gradient_background = settings->getGradientBackground(); + + sp_balance_layout = settings->getBalanceLayout(); + sp_scanline_enabled = settings->getScanlineEnabled(); + ConsoleTab::s_scanline_enabled = sp_scanline_enabled; + sp_theme_effects_enabled = settings->getThemeEffectsEnabled(); + sp_low_spec_mode = settings->getLowSpecMode(); + effects::setLowSpecMode(sp_low_spec_mode); + sp_keep_daemon_running = settings->getKeepDaemonRunning(); + sp_stop_external_daemon = settings->getStopExternalDaemon(); + sp_debug_categories = settings->getDebugCategories(); + sp_debug_cats_dirty = false; + + // Apply loaded visual effects settings + effects::ImGuiAcrylic::ApplyBlurAmount(sp_blur_amount); + effects::ImGuiAcrylic::SetUIOpacity(sp_ui_opacity); + effects::ImGuiAcrylic::SetNoiseOpacity(sp_noise_opacity); + effects::ThemeEffects::instance().setEnabled(sp_theme_effects_enabled); + + sp_initialized = true; +} + +static void saveSettingsPageState(config::Settings* settings) { + if (!settings) return; + + settings->setTheme(settings->getSkinId()); + settings->setSaveZtxs(sp_save_ztxs); + settings->setAllowCustomFees(sp_allow_custom_fees); + settings->setAutoShield(sp_auto_shield); + settings->setFetchPrices(sp_fetch_prices); + settings->setUseTor(sp_use_tor); + settings->setTxExplorerUrl(sp_tx_explorer); + settings->setAddressExplorerUrl(sp_addr_explorer); + + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + auto it = languages.begin(); + std::advance(it, sp_language_index); + if (it != languages.end()) { + settings->setLanguage(it->first); + } + + // Visual effects settings + settings->setAcrylicEnabled(sp_acrylic_enabled); + settings->setAcrylicQuality(sp_blur_amount > 0.001f ? static_cast(effects::AcrylicQuality::Low) : static_cast(effects::AcrylicQuality::Off)); + settings->setBlurMultiplier(sp_blur_amount); + settings->setUIOpacity(sp_ui_opacity); + settings->setWindowOpacity(sp_window_opacity); + settings->setNoiseOpacity(sp_noise_opacity); + settings->setGradientBackground(sp_gradient_background); + settings->setScanlineEnabled(sp_scanline_enabled); + settings->setThemeEffectsEnabled(sp_theme_effects_enabled); + settings->setLowSpecMode(sp_low_spec_mode); + settings->setKeepDaemonRunning(sp_keep_daemon_running); + settings->setStopExternalDaemon(sp_stop_external_daemon); + settings->setDebugCategories(sp_debug_categories); + + settings->save(); +} + +// ============================================================================ +// Settings Page Renderer +// ============================================================================ + +void RenderSettingsPage(App* app) { + // Load settings state on first render + if (!sp_initialized && app->settings()) { + loadSettingsPageState(app->settings()); + } + + // Sync low-spec / theme-effects state from runtime each frame + // so that hotkey toggles are reflected in the checkboxes. + { + bool runtimeLowSpec = effects::isLowSpecMode(); + if (sp_low_spec_mode != runtimeLowSpec) { + if (runtimeLowSpec) { + // Hotkey turned low-spec ON — save snapshot, override statics + s_lowSpecSnap.valid = true; + s_lowSpecSnap.acrylic_enabled = sp_acrylic_enabled; + s_lowSpecSnap.blur_amount = sp_blur_amount; + s_lowSpecSnap.ui_opacity = sp_ui_opacity; + s_lowSpecSnap.window_opacity = sp_window_opacity; + s_lowSpecSnap.theme_effects_enabled = sp_theme_effects_enabled; + s_lowSpecSnap.scanline_enabled = sp_scanline_enabled; + sp_acrylic_enabled = false; + sp_blur_amount = 0.0f; + sp_ui_opacity = 1.0f; + sp_window_opacity = 1.0f; + sp_theme_effects_enabled = false; + sp_scanline_enabled = false; + } else if (s_lowSpecSnap.valid) { + // Hotkey turned low-spec OFF — restore snapshot + sp_blur_amount = s_lowSpecSnap.blur_amount; + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + sp_ui_opacity = s_lowSpecSnap.ui_opacity; + sp_window_opacity = s_lowSpecSnap.window_opacity; + sp_theme_effects_enabled = s_lowSpecSnap.theme_effects_enabled; + sp_scanline_enabled = s_lowSpecSnap.scanline_enabled; + s_lowSpecSnap.valid = false; + } else if (app->settings()) { + // No snapshot — read prefs from settings file + sp_blur_amount = app->settings()->getBlurMultiplier(); + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + sp_ui_opacity = app->settings()->getUIOpacity(); + sp_window_opacity = app->settings()->getWindowOpacity(); + sp_theme_effects_enabled = app->settings()->getThemeEffectsEnabled(); + sp_scanline_enabled = app->settings()->getScanlineEnabled(); + } + sp_low_spec_mode = runtimeLowSpec; + } + bool runtimeThemeEffects = effects::ThemeEffects::instance().isEnabled(); + if (sp_theme_effects_enabled != runtimeThemeEffects) { + sp_theme_effects_enabled = runtimeThemeEffects; + } + } + + auto& S = schema::UI(); + + // Responsive layout — matches other tabs + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float scrollbarMargin = ImGui::GetStyle().ScrollbarSize + Layout::spacingSm(); + float availWidth = contentAvail.x - scrollbarMargin; + float hs = Layout::hScale(availWidth); + float vs = Layout::vScale(contentAvail.y); + float pad = Layout::cardInnerPadding(); + float bottomPad = std::max(0.0f, pad - ImGui::GetStyle().ItemSpacing.y); + float gap = Layout::cardGap(); + float glassRound = Layout::glassRounding(); + + char buf[256]; + + // Label column position — adaptive to width + float labelW = std::max(S.drawElement("components.settings-page", "label-min-width").size, S.drawElement("components.settings-page", "label-width").size * hs); + // Input field width — fill remaining space in card + float inputW = std::max(S.drawElement("components.settings-page", "input-min-width").size, availWidth - labelW - pad * 2); + + // Scrollable content area — NoBackground matches other tabs + + ImGui::BeginChild("##SettingsPageScroll", ImVec2(0, 0), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + + // Capture the ACTUAL clip boundaries from inside the child window + ImVec2 childClipMin = ImGui::GetWindowPos(); + ImVec2 childClipMax(childClipMin.x + ImGui::GetWindowSize().x, + childClipMin.y + ImGui::GetWindowSize().y); + const float dp = Layout::dpiScale(); + const float fadeH = schema::UI().drawElement("components.settings-page", "edge-fade-zone").size * dp; + const float fadeOffTop = schema::UI().drawElement("components.settings-page", "edge-fade-offset-top").size * dp; + const float fadeOffBot = schema::UI().drawElement("components.settings-page", "edge-fade-offset-bottom").size * dp; + + // Get draw list AFTER BeginChild so we draw on the child window's list + ImDrawList* dl = ImGui::GetWindowDrawList(); + (void)dl; // used by cards below + + // Capture ForegroundDrawList vertex start — DrawGlassPanel draws + // theme effects (rainbow border, shimmer, specular glare, edge trace) + // on the ForegroundDrawList; those bypass the shader fade so we'll + // apply a vertex-based alpha fade to them after rendering. + ImDrawList* fgDL = ImGui::GetForegroundDrawList(); + int fgVtxStart = fgDL->VtxBuffer.Size; + + // --- Shader-based scroll fade: bind custom fragment shader --- + // The shader multiplies output alpha by a smoothstep gradient based + // on screen Y, giving a true per-pixel alpha mask at scroll edges. + float settingsScrollY_pre = ImGui::GetScrollY(); + float settingsScrollMaxY_pre = ImGui::GetScrollMaxY(); + float settingsFadeTopY = childClipMin.y + fadeOffTop; + float settingsFadeBottomY = childClipMax.y - fadeOffBot; + float settingsFadeZoneTop = (settingsScrollY_pre > 1.0f) ? fadeH : 0.0f; + float settingsFadeZoneBot = (settingsScrollMaxY_pre > 0 && settingsScrollY_pre < settingsScrollMaxY_pre - 1.0f) ? fadeH : 0.0f; + if (fadeH > 0.0f && !sp_low_spec_mode && s_fadeShader.init()) { + s_fadeShader.fadeTopY = settingsFadeTopY; + s_fadeShader.fadeBottomY = settingsFadeBottomY; + s_fadeShader.fadeZoneTop = settingsFadeZoneTop; + s_fadeShader.fadeZoneBottom = settingsFadeZoneBot; + s_fadeShader.addBind(dl); + } + + // Top margin from schema + float topMargin = schema::UI().drawElement("components.settings-page", "top-margin").size; + if (topMargin > 0.0f) + ImGui::Dummy(ImVec2(0, topMargin)); + + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + ImFont* sub1 = Type().subtitle1(); + + // ==================================================================== + // APPEARANCE — card (draw-first approach; avoids ChannelsSplit which + // breaks BeginCombo popup rendering in some ImGui versions) + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "APPEARANCE"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + float contentW = availWidth - pad * 2; + float comboGap = S.drawElement("components.settings-page", "combo-row-gap").size; + float compactBP = S.drawElement("components.settings-page", "compact-breakpoint").size; + bool wideLayout = availWidth >= compactBP; + float refreshBtnW = S.drawElement("components.settings-page", "refresh-btn-width").size; + + // --- Skin data --- + auto& skinMgr = schema::SkinManager::instance(); + const auto& skins = skinMgr.available(); + std::string active_preview = "DragonX"; + bool active_is_custom = false; + for (const auto& skin : skins) { + if (skin.id == skinMgr.activeSkinId()) { + active_preview = skin.name; + active_is_custom = !skin.bundled; + break; + } + } + + // --- Language data --- + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::vector lang_names; + lang_names.reserve(languages.size()); + for (const auto& lang : languages) { + lang_names.push_back(lang.second.c_str()); + } + + // --- Balance layout data --- + const auto& layouts = GetBalanceLayouts(); + std::string balPreview = sp_balance_layout; + for (const auto& l : layouts) { + if (l.id == sp_balance_layout) { balPreview = l.name; break; } + } + + // --- Theme combo popup (shared between wide and narrow paths) --- + auto renderThemeComboPopup = [&]() { + ImGui::TextDisabled("Built-in"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (!skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + if (ImGui::Selectable(skin.name.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) ImGui::SetItemDefaultFocus(); + } + bool has_custom = false; + for (const auto& skin : skins) { + if (!skin.bundled) { has_custom = true; break; } + } + if (has_custom) { + ImGui::Spacing(); + ImGui::TextDisabled("Custom"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + if (!skin.valid) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.3f, 0.3f, 1.0f)); + ImGui::BeginDisabled(true); + std::string lbl = skin.name + " (invalid)"; + ImGui::Selectable(lbl.c_str(), false); + ImGui::EndDisabled(); + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", skin.validationError.c_str()); + } else { + std::string lbl = skin.name; + if (!skin.author.empty()) lbl += " (" + skin.author + ")"; + if (ImGui::Selectable(lbl.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) ImGui::SetItemDefaultFocus(); + } + } + } + }; + + if (wideLayout) { + // ============================================================ + // Wide: 3 combos on one row + compact 3-column effects grid + // ============================================================ + + // --- Combo row: Theme | Layout | Language [Refresh] --- + { + ImGui::PushFont(body2); + float lblGap = Layout::spacingXs(); + float lblThemeW = ImGui::CalcTextSize("Theme").x + lblGap; + float lblLayoutW = ImGui::CalcTextSize("Balance Layout").x + lblGap; + float lblLangW = ImGui::CalcTextSize("Language").x + lblGap; + float totalFixed = lblThemeW + lblLayoutW + lblLangW + + comboGap * 2 + Layout::spacingSm() + refreshBtnW; + float comboW = std::max(80.0f, (contentW - totalFixed) / 3.0f); + + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Theme"); + ImGui::SameLine(0, lblGap); + ImGui::SetNextItemWidth(comboW); + if (ImGui::BeginCombo("##Theme", active_preview.c_str())) { + renderThemeComboPopup(); + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Hotkey: Ctrl+Left/Right to cycle themes"); + + ImGui::SameLine(0, comboGap); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Balance Layout"); + ImGui::SameLine(0, lblGap); + ImGui::SetNextItemWidth(comboW); + if (ImGui::BeginCombo("##BalanceLayout", balPreview.c_str())) { + for (const auto& l : layouts) { + if (!l.enabled) continue; + bool selected = (l.id == sp_balance_layout); + if (ImGui::Selectable(l.name.c_str(), selected)) { + sp_balance_layout = l.id; + if (app->settings()) { + app->settings()->setBalanceLayout(sp_balance_layout); + app->settings()->save(); + } + } + if (selected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Hotkey: Left/Right arrow keys to cycle Balance layouts"); + + ImGui::SameLine(0, comboGap); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Language"); + ImGui::SameLine(0, lblGap); + ImGui::SetNextItemWidth(comboW); + if (ImGui::Combo("##Language", &sp_language_index, lang_names.data(), + static_cast(lang_names.size()))) { + auto it = languages.begin(); + std::advance(it, sp_language_index); + i18n.loadLanguage(it->first); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Interface language for the wallet UI"); + + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Refresh", ImVec2(refreshBtnW, 0), S.resolveFont("button"))) { + schema::SkinManager::instance().refresh(); + Notifications::instance().info("Theme list refreshed"); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Scan for new themes.\nPlace theme folders in:\n%s", + schema::SkinManager::getUserSkinsDirectory().c_str()); + } + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // --- Visual Effects (checkboxes on one row, Quality+Blur paired) --- + { + ImGui::PushFont(body2); + + // Checkbox row: Low-spec | Console scanline | Theme effects | Gradient background + if (ImGui::Checkbox("Low-spec mode", &sp_low_spec_mode)) { + effects::setLowSpecMode(sp_low_spec_mode); + if (sp_low_spec_mode) { + s_lowSpecSnap.valid = true; + s_lowSpecSnap.acrylic_enabled = sp_acrylic_enabled; + s_lowSpecSnap.blur_amount = sp_blur_amount; + s_lowSpecSnap.ui_opacity = sp_ui_opacity; + s_lowSpecSnap.window_opacity = sp_window_opacity; + s_lowSpecSnap.theme_effects_enabled = sp_theme_effects_enabled; + s_lowSpecSnap.scanline_enabled = sp_scanline_enabled; + sp_acrylic_enabled = false; + sp_blur_amount = 0.0f; + sp_ui_opacity = 1.0f; + sp_window_opacity = 1.0f; + sp_theme_effects_enabled = false; + sp_scanline_enabled = false; + effects::ImGuiAcrylic::ApplyBlurAmount(0.0f); + effects::ImGuiAcrylic::SetUIOpacity(1.0f); + effects::ThemeEffects::instance().setEnabled(false); + ConsoleTab::s_scanline_enabled = false; + } else if (s_lowSpecSnap.valid) { + sp_blur_amount = s_lowSpecSnap.blur_amount; + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + sp_ui_opacity = s_lowSpecSnap.ui_opacity; + sp_window_opacity = s_lowSpecSnap.window_opacity; + sp_theme_effects_enabled = s_lowSpecSnap.theme_effects_enabled; + sp_scanline_enabled = s_lowSpecSnap.scanline_enabled; + effects::ImGuiAcrylic::ApplyBlurAmount(sp_blur_amount); + effects::ImGuiAcrylic::SetUIOpacity(sp_ui_opacity); + effects::ThemeEffects::instance().setEnabled(sp_theme_effects_enabled); + ConsoleTab::s_scanline_enabled = sp_scanline_enabled; + s_lowSpecSnap.valid = false; + } + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Disable all heavy visual effects\nHotkey: Ctrl+Shift+Down"); + + // Simple background is lightweight — always interactive, even in low-spec mode + ImGui::SameLine(0, Layout::spacingLg()); + if (ImGui::Checkbox("Simple background", &sp_gradient_background)) { + schema::SkinManager::instance().setGradientMode(sp_gradient_background); + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Use a simple gradient for the background\nHotkey: Ctrl+Up"); + + ImGui::BeginDisabled(sp_low_spec_mode); + + ImGui::SameLine(0, Layout::spacingLg()); + if (ImGui::Checkbox("Console scanline", &sp_scanline_enabled)) { + ConsoleTab::s_scanline_enabled = sp_scanline_enabled; + app->settings()->setScanlineEnabled(sp_scanline_enabled); + app->settings()->save(); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("CRT scanline effect in console"); + + ImGui::SameLine(0, Layout::spacingLg()); + if (ImGui::Checkbox("Theme effects", &sp_theme_effects_enabled)) { + effects::ThemeEffects::instance().setEnabled(sp_theme_effects_enabled); + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Shimmer, glow, hue-cycling per theme"); + + // Row 1: Acrylic preset slider + Noise slider (side by side, labels above) + float effCtrlMinW = S.drawElement("components.settings-page", "effects-input-min-width").size; + float halfW = (contentW - Layout::spacingLg()) * 0.5f; + float ctrlW = std::max(effCtrlMinW, halfW); + float baseX = ImGui::GetCursorScreenPos().x; + float rightX = baseX + ctrlW + Layout::spacingLg(); + + // Acrylic label + slider (left column) + ImGui::TextUnformatted("Acrylic"); + float row1Y = ImGui::GetCursorScreenPos().y; + ImGui::SetNextItemWidth(ctrlW); + { + // Build display format: "Off" at zero, percentage otherwise + char blur_fmt[16]; + if (sp_blur_amount < 0.01f) + snprintf(blur_fmt, sizeof(blur_fmt), "Off"); + else + snprintf(blur_fmt, sizeof(blur_fmt), "%.0f%%%%", sp_blur_amount * 25.0f); + if (ImGui::SliderFloat("##AcrylicBlur", &sp_blur_amount, 0.0f, 4.0f, blur_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + // Snap to off when dragged near 0% + if (sp_blur_amount > 0.0f && sp_blur_amount < 0.15f) sp_blur_amount = 0.0f; + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + effects::ImGuiAcrylic::ApplyBlurAmount(sp_blur_amount); + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) saveSettingsPageState(app->settings()); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Blur amount (0%% = off, 100%% = maximum)"); + float afterRow1Y = ImGui::GetCursorScreenPos().y; + + // Noise label + slider (right column, same row) + float lblH = ImGui::GetTextLineHeight() + ImGui::GetStyle().ItemSpacing.y; + ImGui::SetCursorScreenPos(ImVec2(rightX, row1Y - lblH)); + ImGui::TextUnformatted("Noise"); + ImGui::SetCursorScreenPos(ImVec2(rightX, row1Y)); + ImGui::SetNextItemWidth(ctrlW); + { + char noise_fmt[16]; + if (sp_noise_opacity < 0.01f) + snprintf(noise_fmt, sizeof(noise_fmt), "Off"); + else + snprintf(noise_fmt, sizeof(noise_fmt), "%.0f%%%%", sp_noise_opacity * 100.0f); + if (ImGui::SliderFloat("##NoiseOpacity", &sp_noise_opacity, 0.0f, 1.0f, noise_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + effects::ImGuiAcrylic::SetNoiseOpacity(sp_noise_opacity); + saveSettingsPageState(app->settings()); + } + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Grain texture intensity (0%% = off, 100%% = maximum)"); + + // Reset cursor to left column, past row 1 + ImGui::SetCursorScreenPos(ImVec2(baseX, afterRow1Y)); + + // Row 2: UI Opacity + Window Opacity (labels above) + ImGui::TextUnformatted("UI Opacity"); + float row2Y = ImGui::GetCursorScreenPos().y; + ImGui::SetNextItemWidth(ctrlW); + { + char uiop_fmt[16]; + snprintf(uiop_fmt, sizeof(uiop_fmt), "%.0f%%%%", sp_ui_opacity * 100.0f); + if (ImGui::SliderFloat("##UIOpacity", &sp_ui_opacity, 0.3f, 1.0f, uiop_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + effects::ImGuiAcrylic::SetUIOpacity(sp_ui_opacity); + saveSettingsPageState(app->settings()); + } + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Card and sidebar opacity (100%% = fully opaque, lower = more see-through)"); + float afterRow2Y = ImGui::GetCursorScreenPos().y; + + // Window label + slider (right column, same row) + ImGui::SetCursorScreenPos(ImVec2(rightX, row2Y - lblH)); + ImGui::TextUnformatted("Window"); + ImGui::SetCursorScreenPos(ImVec2(rightX, row2Y)); + ImGui::SetNextItemWidth(ctrlW); + { + char winop_fmt[16]; + snprintf(winop_fmt, sizeof(winop_fmt), "%.0f%%%%", sp_window_opacity * 100.0f); + if (ImGui::SliderFloat("##WindowOpacity", &sp_window_opacity, 0.3f, 1.0f, winop_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + saveSettingsPageState(app->settings()); + } + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Background opacity (lower = desktop visible through window)"); + + // Reset cursor to left column, past row 2 + ImGui::SetCursorScreenPos(ImVec2(baseX, afterRow2Y)); + + ImGui::EndDisabled(); // low-spec + ImGui::PopFont(); + } + } else { + // ============================================================ + // Narrow: stacked combos + 2-column effects (original layout) + // ============================================================ + + // --- Theme row --- + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Theme"); + ImGui::SameLine(labelW); + + float themeComboW = std::max(S.drawElement("components.settings-page", "theme-combo-min-width").size, + availWidth - pad * 2 - labelW - refreshBtnW - Layout::spacingSm()); + ImGui::SetNextItemWidth(themeComboW); + if (ImGui::BeginCombo("##Theme", active_preview.c_str())) { + renderThemeComboPopup(); + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Hotkey: Ctrl+Left/Right to cycle themes"); + if (active_is_custom) { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(0.4f, 0.8f, 1.0f, 1.0f), "*"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Custom theme active"); + } + ImGui::SameLine(); + if (TactileButton("Refresh", ImVec2(refreshBtnW, 0), S.resolveFont("button"))) { + schema::SkinManager::instance().refresh(); + Notifications::instance().info("Theme list refreshed"); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Scan for new themes.\nPlace theme folders in:\n%s", + schema::SkinManager::getUserSkinsDirectory().c_str()); + } + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // --- Balance Layout row --- + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Balance Layout"); + ImGui::SameLine(labelW); + ImGui::SetNextItemWidth(std::max(180.0f, inputW)); + if (ImGui::BeginCombo("##BalanceLayout", balPreview.c_str())) { + for (const auto& l : layouts) { + if (!l.enabled) continue; + bool selected = (l.id == sp_balance_layout); + if (ImGui::Selectable(l.name.c_str(), selected)) { + sp_balance_layout = l.id; + if (app->settings()) { + app->settings()->setBalanceLayout(sp_balance_layout); + app->settings()->save(); + } + } + if (selected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Hotkey: Left/Right arrow keys to cycle Balance layouts"); + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // --- Language row --- + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Language"); + ImGui::SameLine(labelW); + ImGui::SetNextItemWidth(inputW); + if (ImGui::Combo("##Language", &sp_language_index, lang_names.data(), + static_cast(lang_names.size()))) { + auto it = languages.begin(); + std::advance(it, sp_language_index); + i18n.loadLanguage(it->first); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Interface language for the wallet UI"); + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // --- Visual Effects (checkboxes + controls) --- + { + ImGui::PushFont(body2); + + // Checkbox row 1: Low-spec + if (ImGui::Checkbox("Low-spec mode", &sp_low_spec_mode)) { + effects::setLowSpecMode(sp_low_spec_mode); + if (sp_low_spec_mode) { + s_lowSpecSnap.valid = true; + s_lowSpecSnap.acrylic_enabled = sp_acrylic_enabled; + s_lowSpecSnap.blur_amount = sp_blur_amount; + s_lowSpecSnap.ui_opacity = sp_ui_opacity; + s_lowSpecSnap.window_opacity = sp_window_opacity; + s_lowSpecSnap.theme_effects_enabled = sp_theme_effects_enabled; + s_lowSpecSnap.scanline_enabled = sp_scanline_enabled; + sp_acrylic_enabled = false; + sp_blur_amount = 0.0f; + sp_ui_opacity = 1.0f; + sp_window_opacity = 1.0f; + sp_theme_effects_enabled = false; + sp_scanline_enabled = false; + effects::ImGuiAcrylic::ApplyBlurAmount(0.0f); + effects::ImGuiAcrylic::SetUIOpacity(1.0f); + effects::ThemeEffects::instance().setEnabled(false); + ConsoleTab::s_scanline_enabled = false; + } else if (s_lowSpecSnap.valid) { + sp_blur_amount = s_lowSpecSnap.blur_amount; + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + sp_ui_opacity = s_lowSpecSnap.ui_opacity; + sp_window_opacity = s_lowSpecSnap.window_opacity; + sp_theme_effects_enabled = s_lowSpecSnap.theme_effects_enabled; + sp_scanline_enabled = s_lowSpecSnap.scanline_enabled; + effects::ImGuiAcrylic::ApplyBlurAmount(sp_blur_amount); + effects::ImGuiAcrylic::SetUIOpacity(sp_ui_opacity); + effects::ThemeEffects::instance().setEnabled(sp_theme_effects_enabled); + ConsoleTab::s_scanline_enabled = sp_scanline_enabled; + s_lowSpecSnap.valid = false; + } + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Disable all heavy visual effects\nHotkey: Ctrl+Shift+Down"); + + // Simple background is lightweight — always interactive, even in low-spec mode + if (ImGui::Checkbox("Gradient bg", &sp_gradient_background)) { + schema::SkinManager::instance().setGradientMode(sp_gradient_background); + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Use a gradient version of the theme background image\nHotkey: Ctrl+Up"); + + ImGui::BeginDisabled(sp_low_spec_mode); + + // Checkbox row 2: Console scanline | Theme effects + if (ImGui::Checkbox("Console scanline", &sp_scanline_enabled)) { + ConsoleTab::s_scanline_enabled = sp_scanline_enabled; + app->settings()->setScanlineEnabled(sp_scanline_enabled); + app->settings()->save(); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("CRT scanline effect in console"); + + ImGui::SameLine(0, Layout::spacingLg()); + if (ImGui::Checkbox("Theme effects", &sp_theme_effects_enabled)) { + effects::ThemeEffects::instance().setEnabled(sp_theme_effects_enabled); + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Shimmer, glow, hue-cycling per theme"); + + // Acrylic blur slider (label above) + float ctrlW = std::max(S.drawElement("components.settings-page", "effects-input-min-width").size, + contentW); + ImGui::TextUnformatted("Acrylic"); + ImGui::SetNextItemWidth(ctrlW); + { + char blur_fmt[16]; + if (sp_blur_amount < 0.01f) + snprintf(blur_fmt, sizeof(blur_fmt), "Off"); + else + snprintf(blur_fmt, sizeof(blur_fmt), "%.0f%%%%", sp_blur_amount * 25.0f); + if (ImGui::SliderFloat("##AcrylicBlur", &sp_blur_amount, 0.0f, 4.0f, blur_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + if (sp_blur_amount > 0.0f && sp_blur_amount < 0.15f) sp_blur_amount = 0.0f; + sp_acrylic_enabled = (sp_blur_amount > 0.001f); + effects::ImGuiAcrylic::ApplyBlurAmount(sp_blur_amount); + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) saveSettingsPageState(app->settings()); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Blur amount (0%% = off, 100%% = maximum)"); + + // Noise opacity slider (label above) + ImGui::TextUnformatted("Noise"); + ImGui::SetNextItemWidth(ctrlW); + { + char noise_fmt[16]; + if (sp_noise_opacity < 0.01f) + snprintf(noise_fmt, sizeof(noise_fmt), "Off"); + else + snprintf(noise_fmt, sizeof(noise_fmt), "%.0f%%%%", sp_noise_opacity * 100.0f); + if (ImGui::SliderFloat("##NoiseOpacity", &sp_noise_opacity, 0.0f, 1.0f, noise_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + effects::ImGuiAcrylic::SetNoiseOpacity(sp_noise_opacity); + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) saveSettingsPageState(app->settings()); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Grain texture intensity (0%% = off, 100%% = maximum)"); + + // UI Opacity slider (label above) + ImGui::TextUnformatted("UI Opacity"); + ImGui::SetNextItemWidth(ctrlW); + { + char uiop_fmt[16]; + snprintf(uiop_fmt, sizeof(uiop_fmt), "%.0f%%%%", sp_ui_opacity * 100.0f); + if (ImGui::SliderFloat("##UIOpacity", &sp_ui_opacity, 0.3f, 1.0f, uiop_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + effects::ImGuiAcrylic::SetUIOpacity(sp_ui_opacity); + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) saveSettingsPageState(app->settings()); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Card and sidebar opacity (100%% = fully opaque, lower = more see-through)"); + + // Window Opacity slider (label above) + ImGui::TextUnformatted("Window"); + ImGui::SetNextItemWidth(ctrlW); + { + char winop_fmt[16]; + snprintf(winop_fmt, sizeof(winop_fmt), "%.0f%%%%", sp_window_opacity * 100.0f); + if (ImGui::SliderFloat("##WindowOpacity", &sp_window_opacity, 0.3f, 1.0f, winop_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + } + } + if (ImGui::IsItemDeactivatedAfterEdit()) saveSettingsPageState(app->settings()); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Background opacity (lower = desktop visible through window)"); + + ImGui::EndDisabled(); // low-spec + ImGui::PopFont(); + } + } + + // Bottom padding + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + // Draw glass panel behind content (auto-sized) + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // WALLET — card (Keys, Backup, Tools, Maintenance, Node/RPC) + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "WALLET"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + float contentW = availWidth - pad * 2; + bool wideBtns = availWidth >= S.drawElement("components.settings-page", "compact-breakpoint").size; + + // Content-aware button sizing: uniform per-row width based on widest label + float minBtnW = S.drawElement("components.settings-page", "wallet-btn-min-width").sizeOr(130.0f); + float btnPad = S.drawElement("components.settings-page", "wallet-btn-padding").sizeOr(24.0f); + auto rowBtnW = [&](std::initializer_list labels) -> float { + float maxTextW = 0; + for (auto* l : labels) maxTextW = std::max(maxTextW, ImGui::CalcTextSize(l).x); + return std::max(minBtnW, maxTextW + btnPad * 2); + }; + + // Row 1 — Tools & Actions + { + float bw = rowBtnW({"Address Book...", "Validate Address...", "Request Payment...", "Shield Mining...", "Merge to Address...", "Clear Z-Tx History"}); + if (TactileButton("Address Book...", ImVec2(bw, 0), S.resolveFont("button"))) + AddressBookDialog::show(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Manage saved addresses for quick sending"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Validate Address...", ImVec2(bw, 0), S.resolveFont("button"))) + ValidateAddressDialog::show(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Check if a DragonX address is valid"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Request Payment...", ImVec2(bw, 0), S.resolveFont("button"))) + RequestPaymentDialog::show(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Generate a payment request with QR code"); + if (wideBtns) ImGui::SameLine(0, Layout::spacingMd()); else ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + if (TactileButton("Shield Mining...", ImVec2(bw, 0), S.resolveFont("button"))) + ShieldDialog::show(ShieldDialog::Mode::ShieldCoinbase); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Move transparent mining rewards to a shielded address"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Merge to Address...", ImVec2(bw, 0), S.resolveFont("button"))) + ShieldDialog::show(ShieldDialog::Mode::MergeToAddress); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Consolidate multiple UTXOs into one address"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Clear Z-Tx History", ImVec2(bw, 0), S.resolveFont("button"))) { + std::string ztx_file = util::Platform::getDragonXDataDir() + "ztx_history.json"; + if (util::Platform::deleteFile(ztx_file)) + Notifications::instance().success("Z-transaction history cleared"); + else + Notifications::instance().info("No history file found"); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Delete locally cached z-transaction history"); + } + + // Thin divider + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + { + float divAlpha = S.drawElement("components.settings-page", "section-divider-alpha").opacity; + if (divAlpha <= 0.0f) divAlpha = 0.08f; + ImU32 baseDivCol = S.resolveColor("var(--status-divider)", IM_COL32(255, 255, 255, 20)); + ImU32 divCol = material::ScaleAlpha(baseDivCol, divAlpha / 0.08f); + ImVec2 p = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(p.x, p.y), ImVec2(p.x + contentW, p.y), divCol); + } + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Privacy, Network & Daemon checkboxes — all on one line, shrink text to fit + { + float cbSpacing = Layout::spacingMd(); + float fh = ImGui::GetFrameHeight(); + float inner = ImGui::GetStyle().ItemInnerSpacing.x; + auto cbW = [&](const char* label) { return fh + inner + ImGui::CalcTextSize(label).x; }; + + float totalW = cbW("Save shielded tx history") + cbSpacing + + cbW("Auto-shield") + cbSpacing + + cbW("Use Tor") + cbSpacing + + cbW("Keep daemon running") + cbSpacing + + cbW("Stop external daemon"); + float scale = (totalW > contentW) ? contentW / totalW : 1.0f; + if (scale < 1.0f) ImGui::SetWindowFontScale(scale); + float sp = cbSpacing * scale; + + ImGui::Checkbox("Save shielded tx history", &sp_save_ztxs); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Store z-address transaction history locally for faster loading"); + ImGui::SameLine(0, sp); + ImGui::Checkbox("Auto-shield", &sp_auto_shield); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Automatically move transparent balance to shielded addresses for privacy"); + ImGui::SameLine(0, sp); + ImGui::Checkbox("Use Tor", &sp_use_tor); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Route daemon connections through the Tor network for anonymity"); + ImGui::SameLine(0, sp); + if (ImGui::Checkbox("Keep daemon running", &sp_keep_daemon_running)) { + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Daemon will still stop when running the setup wizard"); + ImGui::SameLine(0, sp); + if (ImGui::Checkbox("Stop external daemon", &sp_stop_external_daemon)) { + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Applies when connecting to a daemon\nyou started outside this wallet"); + + if (scale < 1.0f) ImGui::SetWindowFontScale(1.0f); + } + + // Bottom row — Keys & Data left-aligned, Setup Wizard right-aligned + { + const char* r1[] = {"Import Key...", "Export Key...", "Export All...", "Backup...", "Export CSV..."}; + const char* t1[] = { + "Import a private key (zkey or tkey) into this wallet", + "Export the private key for the selected address", + "Export all private keys to a file", + "Create a backup of your wallet.dat file", + "Export transaction history as a CSV spreadsheet" + }; + const char* wizLabel = "Run Setup Wizard..."; + float sp = Layout::spacingSm(); + ImFont* btnFont = S.resolveFont("button"); + + // Measure natural widths + float btnPadX = btnPad * 2; + float naturalW = 0; + for (int i = 0; i < 5; i++) + naturalW += ImGui::CalcTextSize(r1[i]).x + btnPadX; + float wizW = ImGui::CalcTextSize(wizLabel).x + btnPadX; + float totalW = naturalW + wizW + sp * 6; // 5 gaps between data btns + 1 gap before wizard + + float scale = (totalW > contentW) ? contentW / totalW : 1.0f; + if (scale < 1.0f) ImGui::SetWindowFontScale(scale); + + float scaledSp = sp * scale; + + if (TactileButton(r1[0], ImVec2(0, 0), btnFont)) + app->showImportKeyDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", t1[0]); + ImGui::SameLine(0, scaledSp); + if (TactileButton(r1[1], ImVec2(0, 0), btnFont)) + app->showExportKeyDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", t1[1]); + ImGui::SameLine(0, scaledSp); + if (TactileButton(r1[2], ImVec2(0, 0), btnFont)) + ExportAllKeysDialog::show(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", t1[2]); + ImGui::SameLine(0, scaledSp); + if (TactileButton(r1[3], ImVec2(0, 0), btnFont)) + app->showBackupDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", t1[3]); + ImGui::SameLine(0, scaledSp); + if (TactileButton(r1[4], ImVec2(0, 0), btnFont)) + ExportTransactionsDialog::show(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", t1[4]); + + // Right-align Setup Wizard + float curX = ImGui::GetCursorScreenPos().x; + float wizBtnW = ImGui::CalcTextSize(wizLabel).x + btnPadX; + if (scale < 1.0f) wizBtnW *= scale; + float rightEdge = cardMin.x + availWidth - pad; + float wizX = rightEdge - wizBtnW; + if (wizX > curX) { + ImGui::SameLine(0, 0); + ImGui::SetCursorScreenPos(ImVec2(wizX, ImGui::GetCursorScreenPos().y)); + } else { + ImGui::SameLine(0, scaledSp); + } + if (TactileButton(wizLabel, ImVec2(0, 0), btnFont)) + app->restartWizard(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Re-run the initial setup wizard\nDaemon will be restarted"); + + if (scale < 1.0f) ImGui::SetWindowFontScale(1.0f); + } + + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // NODE & SECURITY — card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NODE & SECURITY"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + float contentW = availWidth - pad * 2; + float minBtnW = S.drawElement("components.settings-page", "wallet-btn-min-width").sizeOr(130.0f); + float btnPad = S.drawElement("components.settings-page", "wallet-btn-padding").sizeOr(24.0f); + auto rowBtnW = [&](std::initializer_list labels) -> float { + float maxTextW = 0; + for (auto* l : labels) maxTextW = std::max(maxTextW, ImGui::CalcTextSize(l).x); + return std::max(minBtnW, maxTextW + btnPad * 2); + }; + + // --- NODE (left) + SECURITY (right) side by side --- + { + float colGap = Layout::spacingLg(); + float leftColW = (contentW - colGap) * 0.6f; + float rightColW = (contentW - colGap) * 0.4f; + ImVec2 sectionOrigin = ImGui::GetCursorScreenPos(); + float leftX = sectionOrigin.x; + float rightX = sectionOrigin.x + leftColW + colGap; + + // ---- LEFT COLUMN: NODE ---- + ImGui::SetCursorScreenPos(ImVec2(leftX, sectionOrigin.y)); + ImGui::PushClipRect(ImVec2(leftX, sectionOrigin.y), + ImVec2(leftX + leftColW, sectionOrigin.y + 9999), true); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NODE"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + { + ImFont* body2Info = S.resolveFont("body2"); + if (!body2Info) body2Info = Type().body2(); + ImGui::PushFont(body2Info); + + float rpcLblW = std::max( + S.drawElement("components.settings-page", "rpc-label-min-width").size, + std::min(leftColW * 0.35f, S.drawElement("components.settings-page", "rpc-label-width").size * hs)); + + std::string wallet_path = util::Platform::getDragonXDataDir() + "wallet.dat"; + uint64_t wallet_size = util::Platform::getFileSize(wallet_path); + + // Data Dir + Wallet Size — same line with "Label: value" format + ImGui::SetCursorScreenPos(ImVec2(leftX, ImGui::GetCursorScreenPos().y)); + ImGui::AlignTextToFramePadding(); + { + // Measure the wallet size string first + std::string size_str = (wallet_size > 0) ? util::Platform::formatFileSize(wallet_size) : "Not found"; + std::string dirPath = util::Platform::getDragonXDataDir(); + + // Calculate space taken by "Wallet Size: " on the right + float walletSizeLabelW = ImGui::CalcTextSize("Wallet Size: ").x; + float walletSizeValW = ImGui::CalcTextSize(size_str.c_str()).x; + float walletSizeTotalW = walletSizeLabelW + walletSizeValW + Layout::spacingLg(); + + // Available space for "Data Dir: " + float dataDirLabelW = ImGui::CalcTextSize("Data Dir: ").x; + float availForPath = leftColW - walletSizeTotalW - dataDirLabelW; + + ImGui::TextUnformatted("Data Dir: "); + ImGui::SameLine(0, Layout::spacingXs()); + ImVec2 pathSize = ImGui::CalcTextSize(dirPath.c_str()); + ImVec4 linkCol = ImGui::ColorConvertU32ToFloat4(Primary()); + ImVec4 linkHoverCol = linkCol; + linkHoverCol.w = std::min(1.0f, linkCol.w + 0.2f); + bool hovered = false; + if (pathSize.x > availForPath && availForPath > 0) { + float scale = availForPath / pathSize.x; + float condensedSize = body2Info->LegacySize * std::max(scale, 0.65f); + ImGui::SetWindowFontScale(condensedSize / body2Info->LegacySize); + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(linkCol, "%s", dirPath.c_str()); + hovered = ImGui::IsItemHovered(); + if (hovered) { + ImVec2 tMin = ImGui::GetItemRectMin(); + ImVec2 tMax = ImGui::GetItemRectMax(); + dl->AddLine(ImVec2(tMin.x, tMax.y), ImVec2(tMax.x, tMax.y), ImGui::GetColorU32(linkHoverCol)); + } + ImGui::SetWindowFontScale(1.0f); + } else { + ImGui::TextColored(linkCol, "%s", dirPath.c_str()); + hovered = ImGui::IsItemHovered(); + if (hovered) { + ImVec2 tMin = ImGui::GetItemRectMin(); + ImVec2 tMax = ImGui::GetItemRectMax(); + dl->AddLine(ImVec2(tMin.x, tMax.y), ImVec2(tMax.x, tMax.y), ImGui::GetColorU32(linkHoverCol)); + } + } + if (hovered) { + ImGui::SetTooltip("Click to open in file explorer"); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + if (ImGui::IsItemClicked()) + util::Platform::openFolder(dirPath); + + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::TextUnformatted("Wallet Size: "); + ImGui::SameLine(0, Layout::spacingXs()); + if (wallet_size > 0) { + ImGui::TextUnformatted(size_str.c_str()); + } else { + ImGui::TextDisabled("Not found"); + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // RPC connection — two columns: (Host | Username) and (Port | Password) + float rpcHalfW = (leftColW - Layout::spacingMd()) * 0.5f; + float rpcHalfLblW = std::min(rpcLblW, rpcHalfW * 0.4f); + float rpcHalfInputW = std::max(40.0f, rpcHalfW - rpcHalfLblW); + float rpcRightColX = leftX + rpcHalfW + Layout::spacingMd(); + + // Row 1: RPC Host + Username + float row1Y = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(leftX, row1Y)); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("RPC Host"); + ImGui::SameLine(leftX - sectionOrigin.x + rpcHalfLblW); + ImGui::SetNextItemWidth(rpcHalfInputW); + ImGui::InputText("##RPCHost", sp_rpc_host, sizeof(sp_rpc_host)); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Hostname of the DragonX daemon"); + + float afterRow1Y = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(rpcRightColX, row1Y)); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Username"); + ImGui::SameLine(rpcRightColX - sectionOrigin.x + rpcHalfLblW); + ImGui::SetNextItemWidth(rpcHalfInputW); + ImGui::InputText("##RPCUser", sp_rpc_user, sizeof(sp_rpc_user)); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("RPC authentication username"); + + ImGui::SetCursorScreenPos(ImVec2(leftX, std::max(afterRow1Y, ImGui::GetCursorScreenPos().y))); + + // Row 2: Port + Password + float row2Y = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(leftX, row2Y)); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Port"); + ImGui::SameLine(leftX - sectionOrigin.x + rpcHalfLblW); + ImGui::SetNextItemWidth(rpcHalfInputW); + ImGui::InputText("##RPCPort", sp_rpc_port, sizeof(sp_rpc_port)); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Port for daemon RPC connections"); + + float afterRow2Y = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(rpcRightColX, row2Y)); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Password"); + ImGui::SameLine(rpcRightColX - sectionOrigin.x + rpcHalfLblW); + ImGui::SetNextItemWidth(rpcHalfInputW); + ImGui::InputText("##RPCPassword", sp_rpc_password, sizeof(sp_rpc_password), + ImGuiInputTextFlags_Password); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("RPC authentication password"); + + ImGui::SetCursorScreenPos(ImVec2(leftX, std::max(afterRow2Y, ImGui::GetCursorScreenPos().y))); + + ImGui::SetCursorScreenPos(ImVec2(leftX, ImGui::GetCursorScreenPos().y)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), + "Auto-detected from DRAGONX.conf"); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + // Node maintenance buttons + { + ImFont* btnFont = S.resolveFont("button"); + float nodeBtnW; + { + if (btnFont) ImGui::PushFont(btnFont); + nodeBtnW = rowBtnW({"Test Connection", "Rescan Blockchain"}); + if (btnFont) ImGui::PopFont(/* btnFont */); + } + ImGui::SetCursorScreenPos(ImVec2(leftX, ImGui::GetCursorScreenPos().y)); + ImGui::BeginDisabled(!app->isConnected()); + if (TactileButton("Test Connection", ImVec2(nodeBtnW, 0), btnFont)) { + if (app->rpc() && app->rpc()->isConnected() && app->worker()) { + app->worker()->post([rpc = app->rpc()]() -> rpc::RPCWorker::MainCb { + try { + rpc->call("getinfo"); + return []() { + Notifications::instance().success("RPC connection OK"); + }; + } catch (const std::exception& e) { + std::string err = e.what(); + return [err]() { + Notifications::instance().error("RPC error: " + err); + }; + } + }); + } else { + Notifications::instance().warning("Not connected to daemon"); + } + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) ImGui::SetTooltip("Verify the RPC connection to the daemon"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Rescan Blockchain", ImVec2(nodeBtnW, 0), btnFont)) { + if (app->rpc() && app->rpc()->isConnected() && app->worker()) { + Notifications::instance().info("Starting blockchain rescan..."); + app->worker()->post([rpc = app->rpc()]() -> rpc::RPCWorker::MainCb { + try { + rpc->call("rescanblockchain", {0}); + return []() { + Notifications::instance().success("Blockchain rescan started"); + }; + } catch (const std::exception& e) { + std::string err = e.what(); + return [err]() { + Notifications::instance().error("Failed to start rescan: " + err); + }; + } + }); + } else { + Notifications::instance().warning("Not connected to daemon"); + } + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) ImGui::SetTooltip("Rescan the blockchain for missing transactions"); + ImGui::EndDisabled(); + } + + ImGui::PopFont(); + } + + float leftBottom = ImGui::GetCursorScreenPos().y; + ImGui::PopClipRect(); + + // ---- RIGHT COLUMN: SECURITY ---- + ImGui::SetCursorScreenPos(ImVec2(rightX, sectionOrigin.y)); + ImGui::PushClipRect(ImVec2(rightX, sectionOrigin.y), + ImVec2(rightX + rightColW, sectionOrigin.y + 9999), true); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SECURITY"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + { + // Encrypt / Change passphrase / Lock buttons + bool isEncrypted = app->state().isEncrypted(); + bool isLocked = app->state().isLocked(); + + float secBtnW = std::min(rowBtnW({"Encrypt Wallet", "Change Passphrase", "Lock Now"}), (rightColW - Layout::spacingMd()) * 0.5f); + + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y)); + if (!isEncrypted) { + if (TactileButton("Encrypt Wallet", ImVec2(secBtnW, 0), S.resolveFont("button"))) + app->showEncryptDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Encrypt wallet.dat with a passphrase"); + ImGui::SameLine(0, Layout::spacingMd()); + ImGui::TextColored(ImVec4(1,1,1,0.5f), "Not encrypted"); + } else { + if (TactileButton("Change Passphrase", ImVec2(secBtnW, 0), S.resolveFont("button"))) + app->showChangePassphraseDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Change the wallet encryption passphrase"); + ImGui::SameLine(0, Layout::spacingMd()); + if (isLocked) { + ImGui::PushFont(Type().iconSmall()); + ImGui::TextColored(ImVec4(1,0.7f,0.3f,1.0f), ICON_MD_LOCK); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingXs()); + ImGui::TextColored(ImVec4(1,0.7f,0.3f,1.0f), "Locked"); + } else { + if (TactileButton("Lock Now", ImVec2(secBtnW, 0), S.resolveFont("button"))) + app->lockWallet(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Lock the wallet immediately"); + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::PushFont(Type().iconSmall()); + ImGui::TextColored(ImVec4(0.3f,1.0f,0.5f,1.0f), ICON_MD_LOCK_OPEN); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingXs()); + ImGui::TextColored(ImVec4(0.3f,1.0f,0.5f,1.0f), "Unlocked"); + } + // Remove Encryption button + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y + Layout::spacingXs())); + if (TactileButton("Remove Encryption", ImVec2(secBtnW, 0), S.resolveFont("button"))) + app->showDecryptDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Remove encryption and store wallet unprotected"); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Auto-Lock timeout + { + float comboW = S.drawElement("components.settings-page", "security-combo-width").sizeOr(120.0f); + + int timeout = app->settings()->getAutoLockTimeout(); + const char* timeoutLabels[] = { "Off", "1 min", "5 min", "15 min", "30 min", "1 hour" }; + int timeoutValues[] = { 0, 60, 300, 900, 1800, 3600 }; + int selTimeout = 0; + for (int i = 0; i < 6; i++) { + if (timeoutValues[i] == timeout) { selTimeout = i; break; } + } + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y)); + Type().textColored(TypeStyle::Caption, OnSurfaceMedium(), "AUTO-LOCK"); + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y)); + ImGui::PushItemWidth(comboW); + if (ImGui::Combo("##autolock", &selTimeout, timeoutLabels, 6)) { + app->settings()->setAutoLockTimeout(timeoutValues[selTimeout]); + app->settings()->save(); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Lock wallet after this much inactivity"); + ImGui::PopItemWidth(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // PIN unlock section + bool isEncryptedPIN = app->state().isEncrypted(); + if (isEncryptedPIN) { + bool hasPIN = app->hasPinVault(); + float pinBtnW = std::min(rowBtnW({"Set PIN", "Change PIN", "Remove PIN"}), (rightColW - Layout::spacingSm()) * 0.5f); + + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y)); + if (!hasPIN) { + if (TactileButton("Set PIN", ImVec2(pinBtnW, 0), S.resolveFont("button"))) + app->showPinSetupDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Set a 4-8 digit PIN for quick unlock"); + ImGui::SameLine(0, Layout::spacingMd()); + ImGui::TextColored(ImVec4(1,1,1,0.5f), "Quick-unlock PIN"); + } else { + if (TactileButton("Change PIN", ImVec2(pinBtnW, 0), S.resolveFont("button"))) + app->showPinChangeDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Change your unlock PIN"); + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Remove PIN", ImVec2(pinBtnW, 0), S.resolveFont("button"))) + app->showPinRemoveDialog(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Remove PIN and require passphrase to unlock"); + ImGui::SameLine(0, Layout::spacingMd()); + ImGui::PushFont(Type().iconSmall()); + ImGui::TextColored(ImVec4(0.3f,1.0f,0.5f,1.0f), ICON_MD_DIALPAD); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingXs()); + ImGui::TextColored(ImVec4(0.3f,1.0f,0.5f,1.0f), "PIN"); + } + } else { + ImGui::SetCursorScreenPos(ImVec2(rightX, ImGui::GetCursorScreenPos().y)); + ImGui::TextColored(ImVec4(1,1,1,0.3f), "Encrypt wallet first to enable PIN"); + } + } + + float rightBottom = ImGui::GetCursorScreenPos().y; + ImGui::PopClipRect(); + + // Advance cursor past both columns + float maxBottom = std::max(leftBottom, rightBottom); + ImGui::SetCursorScreenPos(ImVec2(sectionOrigin.x, maxBottom)); + } + + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // EXPLORER & OPTIONS — full-width card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "EXPLORER"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + float contentW = availWidth - pad * 2; + ImGui::PushFont(body2); + + // Row 1: Transaction URL | Address URL (side-by-side) + float halfW = (contentW - Layout::spacingLg()) * 0.5f; + float lblTxW = ImGui::CalcTextSize("Transaction URL").x + Layout::spacingXs(); + float lblAddrW = ImGui::CalcTextSize("Address URL").x + Layout::spacingXs(); + float inputTxW = std::max(80.0f, halfW - lblTxW); + float inputAddrW = std::max(80.0f, halfW - lblAddrW); + + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Transaction URL"); + ImGui::SameLine(0, Layout::spacingXs()); + ImGui::SetNextItemWidth(inputTxW); + ImGui::InputText("##TxExplorer", sp_tx_explorer, sizeof(sp_tx_explorer)); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Base URL for viewing transactions in a block explorer"); + ImGui::SameLine(pad + halfW + Layout::spacingLg()); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Address URL"); + ImGui::SameLine(0, Layout::spacingXs()); + ImGui::SetNextItemWidth(inputAddrW); + ImGui::InputText("##AddrExplorer", sp_addr_explorer, sizeof(sp_addr_explorer)); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Base URL for viewing addresses in a block explorer"); + + ImGui::PopFont(); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Row 2: Checkboxes + Block Explorer button (on one line) + ImGui::Checkbox("Allow custom transaction fees", &sp_allow_custom_fees); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Enable manual fee entry when sending transactions"); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::Checkbox("Fetch price data from CoinGecko", &sp_fetch_prices); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Retrieve DRGX market prices from CoinGecko API"); + ImGui::SameLine(0, Layout::spacingLg()); + if (TactileButton("Block Explorer", ImVec2(0, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://explorer.dragonx.is"); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Open the DragonX block explorer in your browser"); + + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // ABOUT — card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "ABOUT"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + float contentW = availWidth - pad * 2; + + // App name + version on same line + ImGui::PushFont(sub1); + ImGui::TextUnformatted(DRAGONX_APP_NAME); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::PushFont(body2); + snprintf(buf, sizeof(buf), "v%s", DRAGONX_VERSION); + ImGui::TextUnformatted(buf); + ImGui::SameLine(0, Layout::spacingLg()); + snprintf(buf, sizeof(buf), "ImGui %s", IMGUI_VERSION); + ImGui::TextColored(ImVec4(1,1,1,0.4f), "%s", buf); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::PushFont(body2); + ImGui::PushTextWrapPos(cardMin.x + availWidth - pad); + ImGui::TextUnformatted( + "A shielded cryptocurrency wallet for DragonX (DRGX), " + "built with Dear ImGui for a lightweight, portable experience."); + ImGui::PopTextWrapPos(); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::PushFont(capFont); + ImGui::TextColored(ImVec4(1,1,1,0.5f), "Copyright 2024-2026 The Hush Developers | GPLv3 License"); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + + // Buttons — consistent equal-width row + { + float aboutBtnW = (contentW - Layout::spacingMd() * 3) / 4.0f; + + if (TactileButton("Website", ImVec2(aboutBtnW, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://dragonx.is"); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Open the DragonX website"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Report Bug", ImVec2(aboutBtnW, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://git.hush.is/dragonx/ObsidianDragon/issues"); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Report an issue on the project tracker"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Save Settings", ImVec2(aboutBtnW, 0), S.resolveFont("button"))) { + saveSettingsPageState(app->settings()); + Notifications::instance().success("Settings saved"); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Save all settings to disk"); + ImGui::SameLine(0, Layout::spacingMd()); + if (TactileButton("Reset to Defaults", ImVec2(aboutBtnW, 0), S.resolveFont("button"))) { + if (app->settings()) { + loadSettingsPageState(app->settings()); + Notifications::instance().info("Settings reloaded from disk"); + } + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Reload settings from disk (undo unsaved changes)"); + } + + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // DEBUG LOGGING — collapsible card with glass styling + // ==================================================================== + { + // Clickable header row + ImVec2 headerPos = ImGui::GetCursorScreenPos(); + const char* arrow = sp_debug_expanded ? ICON_MD_EXPAND_LESS : ICON_MD_EXPAND_MORE; + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1,1,1,0.05f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1,1,1,0.08f)); + if (ImGui::Button("##DebugToggle", ImVec2(availWidth, ImGui::GetFrameHeight()))) { + sp_debug_expanded = !sp_debug_expanded; + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip(sp_debug_expanded ? "Collapse debug logging options" : "Expand debug logging options"); + ImGui::PopStyleColor(3); + + // Draw overline label + arrow on top of the invisible button + { + ImFont* ovFont = Type().overline(); + float textY = headerPos.y + (ImGui::GetFrameHeight() - ovFont->LegacySize) * 0.5f; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(headerPos.x, textY), OnSurfaceMedium(), "DEBUG LOGGING"); + // Use the icon font for the expand/collapse arrow + ImFont* iconFont = Type().iconSmall(); + if (!iconFont) iconFont = ovFont; + float arrowW = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, arrow).x; + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(headerPos.x + availWidth - arrowW - pad, textY), OnSurfaceMedium(), arrow); + } + + if (sp_debug_expanded) { + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + pad)); + ImGui::Indent(pad); + + ImGui::TextColored(ImVec4(1,1,1,0.5f), + "Select categories to enable daemon debug logging (-debug= flags)."); + ImGui::TextColored(ImVec4(1,1,1,0.35f), + "Changes take effect after restarting the daemon."); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // The 22 hushd debug categories + static const char* debugCats[] = { + "addrman", "alert", "bench", "coindb", "db", "estimatefee", + "http", "libevent", "lock", "mempool", "net", + "paymentdisclosure", "pow", "proxy", "prune", "rand", + "reindex", "rpc", "selectcoins", "tor", "zmq", "zrpc" + }; + static const char* debugTips[] = { + "Peer address tracking and management", + "Alert system messages", + "Benchmark timings for operations", + "Coin database read/write operations", + "Berkeley DB operations", + "Fee estimation algorithm", + "HTTP RPC server activity", + "Libevent networking library", + "Lock contention debugging", + "Transaction memory pool activity", + "Network connections and messages", + "Payment disclosure protocol", + "Proof-of-work mining activity", + "SOCKS5 proxy connections", + "Block pruning operations", + "Random number generation", + "Blockchain reindexing progress", + "RPC command processing", + "Coin selection for transactions", + "Tor integration and circuit info", + "ZeroMQ notification system", + "Shielded (z-addr) RPC operations" + }; + constexpr int numCats = sizeof(debugCats) / sizeof(debugCats[0]); + + // Render as a 4-column grid of checkboxes + int columns = 4; + float dbgContentW = availWidth - pad * 2.0f; + float colW = dbgContentW / columns; + + for (int i = 0; i < numCats; i++) { + if (i > 0 && (i % columns) != 0) { + ImGui::SameLine(pad + colW * (i % columns)); + } + bool enabled = sp_debug_categories.count(debugCats[i]) > 0; + if (ImGui::Checkbox(debugCats[i], &enabled)) { + if (enabled) { + sp_debug_categories.insert(debugCats[i]); + } else { + sp_debug_categories.erase(debugCats[i]); + } + sp_debug_cats_dirty = true; + saveSettingsPageState(app->settings()); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", debugTips[i]); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // "Restart daemon" button — only active when categories changed + if (sp_debug_cats_dirty) { + ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 218, 0, 255)); + ImFont* iconFont = Type().iconSmall(); + if (iconFont) { + ImGui::PushFont(iconFont); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(ICON_MD_INFO); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingXs()); + } + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Debug categories changed — restart daemon to apply"); + ImGui::PopStyleColor(); + ImGui::SameLine(); + if (TactileButton("Restart daemon", ImVec2(0, 0), S.resolveFont("button"))) { + sp_debug_cats_dirty = false; + app->restartDaemon(); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Restart the daemon to apply debug logging changes"); + } + + ImGui::Dummy(ImVec2(0, bottomPad)); + ImGui::Unindent(pad); + + ImVec2 cardMax(cardMin.x + availWidth, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + } + + // --- Shader-based scroll fade: unbind (restore ImGui's default shader) --- + if (fadeH > 0.0f && !sp_low_spec_mode && s_fadeShader.ready) { + effects::ScrollFadeShader::addUnbind(dl); + } + + // --- Vertex-based alpha fade for ForegroundDrawList theme effects --- + // DrawGlassPanel draws rainbow borders, shimmer, specular glare, and + // edge traces on the ForegroundDrawList which bypasses the shader. + // Apply the same fade boundaries via vertex alpha manipulation. + if (fadeH > 0.0f) { + int fgVtxEnd = fgDL->VtxBuffer.Size; + float safeTop = settingsFadeTopY + settingsFadeZoneTop; + float safeBot = settingsFadeBottomY - settingsFadeZoneBot; + for (int vi = fgVtxStart; vi < fgVtxEnd; vi++) { + ImDrawVert& v = fgDL->VtxBuffer[vi]; + if (v.pos.y >= safeTop && v.pos.y <= safeBot) + continue; + float alpha = 1.0f; + if (settingsFadeZoneTop > 0.0f) { + float dTop = v.pos.y - settingsFadeTopY; + if (dTop < settingsFadeZoneTop) + alpha = std::min(alpha, std::max(0.0f, dTop / settingsFadeZoneTop)); + } + if (settingsFadeZoneBot > 0.0f) { + float dBot = settingsFadeBottomY - v.pos.y; + if (dBot < settingsFadeZoneBot) + alpha = std::min(alpha, std::max(0.0f, dBot / settingsFadeZoneBot)); + } + if (alpha < 1.0f) { + int a = (v.col >> IM_COL32_A_SHIFT) & 0xFF; + a = static_cast(a * alpha); + v.col = (v.col & ~IM_COL32_A_MASK) | (static_cast(a) << IM_COL32_A_SHIFT); + } + } + } + + ImGui::EndChild(); // ##SettingsPageScroll + +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/pages/settings_page.cpp.bak b/src/ui/pages/settings_page.cpp.bak new file mode 100644 index 0000000..21c9f8e --- /dev/null +++ b/src/ui/pages/settings_page.cpp.bak @@ -0,0 +1,848 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "settings_page.h" +#include "../../app.h" +#include "../../version.h" +#include "../../config/settings.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../../rpc/rpc_client.h" +#include "../theme.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../schema/skin_manager.h" +#include "../notifications.h" +#include "../effects/imgui_acrylic.h" +#include "../material/draw_helpers.h" +#include "../material/type.h" +#include "../material/colors.h" +#include "../windows/validate_address_dialog.h" +#include "../windows/address_book_dialog.h" +#include "../windows/shield_dialog.h" +#include "../windows/request_payment_dialog.h" +#include "../windows/block_info_dialog.h" +#include "../windows/export_all_keys_dialog.h" +#include "../windows/export_transactions_dialog.h" +#include "imgui.h" +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ============================================================================ +// Settings state — loaded from config::Settings on first render +// ============================================================================ +static bool sp_initialized = false; +static int sp_language_index = 0; +static bool sp_save_ztxs = true; +static bool sp_allow_custom_fees = false; +static bool sp_auto_shield = false; +static bool sp_fetch_prices = true; +static bool sp_use_tor = false; +static char sp_rpc_host[128] = DRAGONX_DEFAULT_RPC_HOST; +static char sp_rpc_port[16] = DRAGONX_DEFAULT_RPC_PORT; +static char sp_rpc_user[64] = ""; +static char sp_rpc_password[64] = ""; +static char sp_tx_explorer[256] = "https://explorer.dragonx.is/tx/"; +static char sp_addr_explorer[256] = "https://explorer.dragonx.is/address/"; + +// Acrylic settings +static bool sp_acrylic_enabled = true; +static int sp_acrylic_quality = 2; +static float sp_blur_multiplier = 1.0f; +static bool sp_reduced_transparency = false; + +static void loadSettingsPageState(config::Settings* settings) { + if (!settings) return; + + sp_save_ztxs = settings->getSaveZtxs(); + sp_allow_custom_fees = settings->getAllowCustomFees(); + sp_auto_shield = settings->getAutoShield(); + sp_fetch_prices = settings->getFetchPrices(); + sp_use_tor = settings->getUseTor(); + + strncpy(sp_tx_explorer, settings->getTxExplorerUrl().c_str(), sizeof(sp_tx_explorer) - 1); + strncpy(sp_addr_explorer, settings->getAddressExplorerUrl().c_str(), sizeof(sp_addr_explorer) - 1); + + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::string current_lang = settings->getLanguage(); + if (current_lang.empty()) current_lang = "en"; + + sp_language_index = 0; + int idx = 0; + for (const auto& lang : languages) { + if (lang.first == current_lang) { + sp_language_index = idx; + break; + } + idx++; + } + + sp_acrylic_enabled = effects::ImGuiAcrylic::IsEnabled(); + sp_acrylic_quality = static_cast(effects::ImGuiAcrylic::GetQuality()); + sp_blur_multiplier = effects::ImGuiAcrylic::GetBlurMultiplier(); + sp_reduced_transparency = effects::ImGuiAcrylic::GetReducedTransparency(); + + sp_initialized = true; +} + +static void saveSettingsPageState(config::Settings* settings) { + if (!settings) return; + + settings->setTheme(settings->getSkinId()); + settings->setSaveZtxs(sp_save_ztxs); + settings->setAllowCustomFees(sp_allow_custom_fees); + settings->setAutoShield(sp_auto_shield); + settings->setFetchPrices(sp_fetch_prices); + settings->setUseTor(sp_use_tor); + settings->setTxExplorerUrl(sp_tx_explorer); + settings->setAddressExplorerUrl(sp_addr_explorer); + + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + auto it = languages.begin(); + std::advance(it, sp_language_index); + if (it != languages.end()) { + settings->setLanguage(it->first); + } + + settings->save(); +} + +// ============================================================================ +// Settings Page Renderer +// ============================================================================ + +void RenderSettingsPage(App* app) { + // Load settings state on first render + if (!sp_initialized && app->settings()) { + loadSettingsPageState(app->settings()); + } + + auto& S = schema::UI(); + + // Responsive layout — matches other tabs + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availWidth = contentAvail.x; + float hs = Layout::hScale(availWidth); + float vs = Layout::vScale(contentAvail.y); + float pad = Layout::cardInnerPadding(); + float gap = Layout::cardGap(); + float glassRound = Layout::glassRounding(); + (void)vs; + + char buf[256]; + + // Label column position — adaptive to width + float labelW = std::max(100.0f, 120.0f * hs); + // Input field width — fill remaining space in card + float inputW = std::max(180.0f, availWidth - labelW - pad * 3); + + // Scrollable content area — NoBackground matches other tabs + ImGui::BeginChild("##SettingsPageScroll", ImVec2(0, 0), false, + ImGuiWindowFlags_NoBackground); + + // Get draw list AFTER BeginChild so we draw on the child window's list + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + ImFont* sub1 = Type().subtitle1(); + + // ==================================================================== + // GENERAL — Appearance & Preferences card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "APPEARANCE"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Measure content height for card + // We'll use ImGui cursor-based layout inside the card + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + + // Use a child window inside the glass panel for layout + // First draw the glass panel, then place content + // We need to estimate height — use a generous estimate and clip + float rowH = body2->LegacySize + Layout::spacingSm(); + float sectionGap = Layout::spacingMd(); + float cardH = pad // top pad + + rowH // Theme + + rowH // Language + + sectionGap + + rowH * 5 // Visual effects (acrylic + quality + blur + reduce + gap) + + pad; // bottom pad + if (!sp_acrylic_enabled) cardH -= rowH * 2; + + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + // --- Theme row --- + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Theme"); + ImGui::SameLine(labelW); + + auto& skinMgr = schema::SkinManager::instance(); + const auto& skins = skinMgr.available(); + + std::string active_preview = "DragonX"; + bool active_is_custom = false; + for (const auto& skin : skins) { + if (skin.id == skinMgr.activeSkinId()) { + active_preview = skin.name; + active_is_custom = !skin.bundled; + break; + } + } + + float refreshBtnW = 80.0f; + ImGui::SetNextItemWidth(inputW - refreshBtnW - Layout::spacingSm()); + if (ImGui::BeginCombo("##Theme", active_preview.c_str())) { + ImGui::TextDisabled("Built-in"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (!skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + if (ImGui::Selectable(skin.name.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) ImGui::SetItemDefaultFocus(); + } + bool has_custom = false; + for (const auto& skin : skins) { + if (!skin.bundled) { has_custom = true; break; } + } + if (has_custom) { + ImGui::Spacing(); + ImGui::TextDisabled("Custom"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + if (!skin.valid) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.3f, 0.3f, 1.0f)); + ImGui::BeginDisabled(true); + std::string lbl = skin.name + " (invalid)"; + ImGui::Selectable(lbl.c_str(), false); + ImGui::EndDisabled(); + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", skin.validationError.c_str()); + } else { + std::string lbl = skin.name; + if (!skin.author.empty()) lbl += " (" + skin.author + ")"; + if (ImGui::Selectable(lbl.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) ImGui::SetItemDefaultFocus(); + } + } + } + ImGui::EndCombo(); + } + if (active_is_custom) { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(0.4f, 0.8f, 1.0f, 1.0f), "*"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Custom theme active"); + } + ImGui::SameLine(); + if (TactileButton("Refresh", ImVec2(refreshBtnW, 0), S.resolveFont("button"))) { + schema::SkinManager::instance().refresh(); + Notifications::instance().info("Theme list refreshed"); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Scan for new themes.\nPlace theme folders in:\n%s", + schema::SkinManager::getUserSkinsDirectory().c_str()); + } + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // --- Language row --- + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Language"); + ImGui::SameLine(labelW); + + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::vector lang_names; + lang_names.reserve(languages.size()); + for (const auto& lang : languages) { + lang_names.push_back(lang.second.c_str()); + } + + ImGui::SetNextItemWidth(inputW); + if (ImGui::Combo("##Language", &sp_language_index, lang_names.data(), + static_cast(lang_names.size()))) { + auto it = languages.begin(); + std::advance(it, sp_language_index); + i18n.loadLanguage(it->first); + } + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // --- Visual Effects subsection --- + dl->AddText(ovFont, ovFont->LegacySize, ImGui::GetCursorScreenPos(), OnSurfaceMedium(), "VISUAL EFFECTS"); + ImGui::Dummy(ImVec2(0, ovFont->LegacySize + Layout::spacingXs())); + + { + // Two-column: left = acrylic toggle + reduce toggle, right = quality + blur + float colW = (availWidth - pad * 2 - Layout::spacingLg()) * 0.5f; + + if (ImGui::Checkbox("Acrylic effects", &sp_acrylic_enabled)) { + effects::ImGuiAcrylic::SetEnabled(sp_acrylic_enabled); + } + + if (sp_acrylic_enabled) { + ImGui::SameLine(labelW + colW + Layout::spacingLg()); + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Quality"); + ImGui::PopFont(); + ImGui::SameLine(); + const char* quality_levels[] = { "Off", "Low", "Medium", "High" }; + ImGui::SetNextItemWidth(std::max(100.0f, colW - 80.0f)); + if (ImGui::Combo("##AcrylicQuality", &sp_acrylic_quality, quality_levels, + IM_ARRAYSIZE(quality_levels))) { + effects::ImGuiAcrylic::SetQuality( + static_cast(sp_acrylic_quality)); + } + } + + if (ImGui::Checkbox("Reduce transparency", &sp_reduced_transparency)) { + effects::ImGuiAcrylic::SetReducedTransparency(sp_reduced_transparency); + } + + if (sp_acrylic_enabled) { + ImGui::SameLine(labelW + colW + Layout::spacingLg()); + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Blur"); + ImGui::PopFont(); + ImGui::SameLine(); + ImGui::SetNextItemWidth(std::max(100.0f, colW - 80.0f)); + if (ImGui::SliderFloat("##BlurAmount", &sp_blur_multiplier, 0.5f, 2.0f, "%.1fx")) { + effects::ImGuiAcrylic::SetBlurMultiplier(sp_blur_multiplier); + } + } + } + + // Recalculate actual card bottom from cursor + ImVec2 cardEnd = ImGui::GetCursorScreenPos(); + float actualH = (cardEnd.y - cardMin.y) + pad; + if (actualH != cardH) { + // Redraw glass panel with correct height + cardMax.y = cardMin.y + actualH; + } + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // PRIVACY & OPTIONS — Two cards side by side + // ==================================================================== + { + float colW = (availWidth - gap) * 0.5f; + ImVec2 rowOrigin = ImGui::GetCursorScreenPos(); + + // --- Privacy card (left) --- + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "PRIVACY"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = pad + (body2->LegacySize + Layout::spacingSm()) * 3 + pad; + ImVec2 cardMax(cardMin.x + colW, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + ImGui::Checkbox("Save shielded tx history", &sp_save_ztxs); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + ImGui::Checkbox("Auto-shield transparent funds", &sp_auto_shield); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + ImGui::Checkbox("Use Tor for connections", &sp_use_tor); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(colW, 0)); + } + + // --- Options card (right) --- + { + float rightX = rowOrigin.x + colW + gap; + // Position cursor at the same Y as privacy label + ImGui::SetCursorScreenPos(ImVec2(rightX, rowOrigin.y)); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "OPTIONS"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = pad + (body2->LegacySize + Layout::spacingSm()) * 3 + pad; + ImVec2 cardMax(cardMin.x + colW, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + ImGui::Checkbox("Allow custom transaction fees", &sp_allow_custom_fees); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + ImGui::Checkbox("Fetch price data from CoinGecko", &sp_fetch_prices); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(colW, 0)); + } + + // Advance past the side-by-side row + // Find the maximum bottom + float rowBottom = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(rowOrigin.x, rowBottom)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // EXPLORER URLS + SAVE — card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "BLOCK EXPLORER & SETTINGS"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float rowH = body2->LegacySize + Layout::spacingSm(); + float cardH = pad + rowH * 2 + Layout::spacingSm() + + body2->LegacySize + Layout::spacingMd() // save/reset row + + pad; + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + // Transaction URL + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Transaction URL"); + ImGui::SameLine(labelW); + ImGui::SetNextItemWidth(inputW); + ImGui::InputText("##TxExplorer", sp_tx_explorer, sizeof(sp_tx_explorer)); + ImGui::PopFont(); + } + + // Address URL + { + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Address URL"); + ImGui::SameLine(labelW); + ImGui::SetNextItemWidth(inputW); + ImGui::InputText("##AddrExplorer", sp_addr_explorer, sizeof(sp_addr_explorer)); + ImGui::PopFont(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Save / Reset — right-aligned + { + float saveBtnW = 120.0f; + float resetBtnW = 140.0f; + float btnGap = Layout::spacingSm(); + + if (TactileButton("Save Settings", ImVec2(saveBtnW, 0), S.resolveFont("button"))) { + saveSettingsPageState(app->settings()); + Notifications::instance().success("Settings saved"); + } + ImGui::SameLine(0, btnGap); + if (TactileButton("Reset to Defaults", ImVec2(resetBtnW, 0), S.resolveFont("button"))) { + if (app->settings()) { + loadSettingsPageState(app->settings()); + Notifications::instance().info("Settings reloaded from disk"); + } + } + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // KEYS & BACKUP — card with two rows + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "KEYS & BACKUP"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float btnRowH = std::max(28.0f, 34.0f * vs) + Layout::spacingSm(); + float cardH = pad + btnRowH * 2 + Layout::spacingSm() + pad; + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + // Keys row — spread buttons across width + { + float btnW = (availWidth - pad * 2 - Layout::spacingSm() * 2) / 3.0f; + if (TactileButton("Import Private Key...", ImVec2(btnW, 0), S.resolveFont("button"))) { + app->showImportKeyDialog(); + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Export Private Key...", ImVec2(btnW, 0), S.resolveFont("button"))) { + app->showExportKeyDialog(); + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Export All Keys...", ImVec2(btnW, 0), S.resolveFont("button"))) { + ExportAllKeysDialog::show(); + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Backup row + { + float btnW = (availWidth - pad * 2 - Layout::spacingSm()) / 2.0f; + if (TactileButton("Backup wallet.dat...", ImVec2(btnW, 0), S.resolveFont("button"))) { + app->showBackupDialog(); + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Export Transactions CSV...", ImVec2(btnW, 0), S.resolveFont("button"))) { + ExportTransactionsDialog::show(); + } + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // WALLET — Two cards side by side: Tools | Maintenance + // ==================================================================== + { + float colW = (availWidth - gap) * 0.5f; + ImVec2 rowOrigin = ImGui::GetCursorScreenPos(); + float btnH = std::max(28.0f, 34.0f * vs); + + // --- Wallet Tools card (left) --- + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "WALLET TOOLS"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = pad + (btnH + Layout::spacingSm()) * 3 + pad; + ImVec2 cardMax(cardMin.x + colW, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + float innerBtnW = colW - pad * 2; + if (TactileButton("Address Book...", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + AddressBookDialog::show(); + } + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + if (TactileButton("Validate Address...", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + ValidateAddressDialog::show(); + } + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + if (TactileButton("Request Payment...", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + RequestPaymentDialog::show(); + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(colW, 0)); + } + + // --- Shielding & Maintenance card (right) --- + { + float rightX = rowOrigin.x + colW + gap; + ImGui::SetCursorScreenPos(ImVec2(rightX, rowOrigin.y)); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SHIELDING & MAINTENANCE"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = pad + (btnH + Layout::spacingSm()) * 3 + pad; + ImVec2 cardMax(cardMin.x + colW, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + float innerBtnW = colW - pad * 2; + if (TactileButton("Shield Mining Rewards...", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + ShieldDialog::show(ShieldDialog::Mode::ShieldCoinbase); + } + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + if (TactileButton("Merge to Address...", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + ShieldDialog::show(ShieldDialog::Mode::MergeToAddress); + } + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + ImGui::BeginDisabled(!app->isConnected()); + if (TactileButton("Rescan Blockchain", ImVec2(innerBtnW, btnH), S.resolveFont("button"))) { + if (app->rpc() && app->rpc()->isConnected()) { + app->rpc()->rescanBlockchain(0, [](bool success, const nlohmann::json&) { + if (success) + Notifications::instance().success("Blockchain rescan started"); + else + Notifications::instance().error("Failed to start rescan"); + }); + } else { + Notifications::instance().warning("Not connected to daemon"); + } + } + ImGui::EndDisabled(); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(colW, 0)); + } + + // Advance past sidebar row + float rowBottom = ImGui::GetCursorScreenPos().y; + ImGui::SetCursorScreenPos(ImVec2(rowOrigin.x, rowBottom)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // WALLET INFO — Small card with file path + clear history + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "WALLET INFO"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float rowH = body2->LegacySize + Layout::spacingSm(); + float btnRowH = std::max(28.0f, 34.0f * vs) + Layout::spacingSm(); + float cardH = pad + rowH * 2 + btnRowH + pad; + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + std::string wallet_path = util::Platform::getDragonXDataDir() + "wallet.dat"; + uint64_t wallet_size = util::Platform::getFileSize(wallet_path); + + ImGui::PushFont(body2); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Location"); + ImGui::SameLine(labelW); + ImGui::TextUnformatted(wallet_path.c_str()); + + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("File size"); + ImGui::SameLine(labelW); + if (wallet_size > 0) { + std::string size_str = util::Platform::formatFileSize(wallet_size); + ImGui::TextUnformatted(size_str.c_str()); + } else { + ImGui::TextDisabled("Not found"); + } + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + if (TactileButton("Clear Z-Transaction History", ImVec2(0, 0), S.resolveFont("button"))) { + std::string ztx_file = util::Platform::getDragonXDataDir() + "ztx_history.json"; + if (util::Platform::deleteFile(ztx_file)) + Notifications::instance().success("Z-transaction history cleared"); + else + Notifications::instance().info("No history file found"); + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // NODE / RPC — card with two-column inputs + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NODE / RPC CONNECTION"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float rowH = body2->LegacySize + Layout::spacingSm(); + float btnRowH = std::max(28.0f, 34.0f * vs) + Layout::spacingSm(); + float cardH = pad + rowH * 2 + Layout::spacingSm() + rowH * 2 + Layout::spacingSm() + + capFont->LegacySize + Layout::spacingSm() + + btnRowH + pad; + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + // Two-column: Host+Port on one line, User+Pass on next + float halfInput = (availWidth - pad * 2 - labelW * 2 - Layout::spacingLg()) * 0.5f; + float rpcLabelW = std::max(70.0f, 85.0f * hs); + + ImGui::PushFont(body2); + + // Row 1: Host + Port + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Host"); + ImGui::SameLine(rpcLabelW); + ImGui::SetNextItemWidth(halfInput + labelW - rpcLabelW); + ImGui::InputText("##RPCHost", sp_rpc_host, sizeof(sp_rpc_host)); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Port"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(std::max(60.0f, halfInput * 0.4f)); + ImGui::InputText("##RPCPort", sp_rpc_port, sizeof(sp_rpc_port)); + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Row 2: Username + Password + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Username"); + ImGui::SameLine(rpcLabelW); + ImGui::SetNextItemWidth(halfInput + labelW - rpcLabelW); + ImGui::InputText("##RPCUser", sp_rpc_user, sizeof(sp_rpc_user)); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted("Password"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(halfInput); + ImGui::InputText("##RPCPassword", sp_rpc_password, sizeof(sp_rpc_password), + ImGuiInputTextFlags_Password); + + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), + "Connection settings are usually auto-detected from DRAGONX.conf"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (TactileButton("Test Connection", ImVec2(0, 0), S.resolveFont("button"))) { + if (app->rpc() && app->rpc()->isConnected()) { + app->rpc()->getInfo([](const nlohmann::json& result, const std::string& error) { + (void)result; + if (error.empty()) + Notifications::instance().success("RPC connection OK"); + else + Notifications::instance().error("RPC error: " + error); + }); + } else { + Notifications::instance().warning("Not connected to daemon"); + } + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Block Info...", ImVec2(0, 0), S.resolveFont("button"))) { + BlockInfoDialog::show(app->getBlockHeight()); + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + // ==================================================================== + // ABOUT — card + // ==================================================================== + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "ABOUT"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float rowH = body2->LegacySize + Layout::spacingXs(); + float btnRowH = std::max(28.0f, 34.0f * vs) + Layout::spacingSm(); + float cardH = pad + sub1->LegacySize + rowH * 2 + Layout::spacingSm() + + body2->LegacySize * 2 + Layout::spacingSm() + + capFont->LegacySize * 2 + Layout::spacingMd() + + btnRowH + pad; + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + pad, cardMin.y + pad)); + + // App name + version on same line + ImGui::PushFont(sub1); + ImGui::TextUnformatted(DRAGONX_APP_NAME); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::PushFont(body2); + snprintf(buf, sizeof(buf), "v%s", DRAGONX_VERSION); + ImGui::TextUnformatted(buf); + ImGui::SameLine(0, Layout::spacingLg()); + snprintf(buf, sizeof(buf), "ImGui %s", IMGUI_VERSION); + ImGui::TextColored(ImVec4(1,1,1,0.4f), "%s", buf); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::PushFont(body2); + ImGui::PushTextWrapPos(cardMax.x - pad); + ImGui::TextUnformatted( + "A shielded cryptocurrency wallet for DragonX (DRGX), " + "built with Dear ImGui for a lightweight, portable experience."); + ImGui::PopTextWrapPos(); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::PushFont(capFont); + ImGui::TextColored(ImVec4(1,1,1,0.5f), "Copyright 2024-2026 The Hush Developers | GPLv3 License"); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + + // Buttons — spread across width + { + float btnW = (availWidth - pad * 2 - Layout::spacingSm() * 2) / 3.0f; + if (TactileButton("Website", ImVec2(btnW, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://dragonx.is"); + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Report Bug", ImVec2(btnW, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://git.hush.is/hush/SilentDragonX/issues"); + } + ImGui::SameLine(0, Layout::spacingSm()); + if (TactileButton("Block Explorer", ImVec2(btnW, 0), S.resolveFont("button"))) { + util::Platform::openUrl("https://explorer.dragonx.is"); + } + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + ImGui::Dummy(ImVec2(0, gap)); + + ImGui::EndChild(); // ##SettingsPageScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/pages/settings_page.h b/src/ui/pages/settings_page.h new file mode 100644 index 0000000..dd1c41d --- /dev/null +++ b/src/ui/pages/settings_page.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; +namespace ui { + +/** + * @brief Render the Settings page (inline sidebar content, not a modal) + * Consolidates items previously in File/Edit/Wallet/View/Help menus + * into a single scrollable settings page with collapsible sections. + */ +void RenderSettingsPage(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/color_var_resolver.cpp b/src/ui/schema/color_var_resolver.cpp new file mode 100644 index 0000000..c772154 --- /dev/null +++ b/src/ui/schema/color_var_resolver.cpp @@ -0,0 +1,186 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "color_var_resolver.h" +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace schema { + +// ============================================================================ +// Palette management +// ============================================================================ + +void ColorVarResolver::setPalette(const std::unordered_map& palette) { + palette_ = palette; +} + +// ============================================================================ +// Public API +// ============================================================================ + +ImU32 ColorVarResolver::resolve(const std::string& value, ImU32 fallback) const { + if (value.empty()) { + return fallback; + } + + // "transparent" + if (value == "transparent") { + return IM_COL32(0, 0, 0, 0); + } + + // var(--name) → palette lookup + if (value.size() > 6 && value.substr(0, 4) == "var(") { + // Extract variable name: var(--primary) → --primary + size_t close = value.find(')'); + if (close == std::string::npos) { + return fallback; + } + std::string varName = value.substr(4, close - 4); + + // Trim whitespace + while (!varName.empty() && varName.front() == ' ') varName.erase(varName.begin()); + while (!varName.empty() && varName.back() == ' ') varName.pop_back(); + + auto it = palette_.find(varName); + if (it != palette_.end()) { + return it->second; + } + return fallback; + } + + // #hex + if (value[0] == '#') { + ImU32 out = 0; + if (parseHex(value, out)) { + return out; + } + return fallback; + } + + // rgba(r,g,b,a) + if (value.size() > 5 && value.substr(0, 5) == "rgba(") { + ImU32 out = 0; + if (parseRgba(value, out)) { + return out; + } + return fallback; + } + + // 0xRRGGBB / 0xRRGGBBAA (legacy format support) + if (value.size() > 2 && value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) { + ImU32 out = 0; + if (parseHex(value, out)) { + return out; + } + return fallback; + } + + return fallback; +} + +bool ColorVarResolver::hasValue(const std::string& value) { + return !value.empty(); +} + +// ============================================================================ +// Static parsers +// ============================================================================ + +bool ColorVarResolver::parseHex(const std::string& hexStr, ImU32& out) { + if (hexStr.empty()) return false; + + std::string hex = hexStr; + + // Remove leading # or 0x + if (hex[0] == '#') { + hex = hex.substr(1); + } else if (hex.size() > 2 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) { + hex = hex.substr(2); + } + + // Validate length + if (hex.size() != 6 && hex.size() != 8) { + return false; + } + + // Validate hex chars + for (char c : hex) { + if (!std::isxdigit(static_cast(c))) { + return false; + } + } + + unsigned long value = std::strtoul(hex.c_str(), nullptr, 16); + + if (hex.size() == 6) { + // #RRGGBB → IM_COL32(R, G, B, 255) + uint8_t r = (value >> 16) & 0xFF; + uint8_t g = (value >> 8) & 0xFF; + uint8_t b = value & 0xFF; + out = IM_COL32(r, g, b, 255); + } else { + // #RRGGBBAA → IM_COL32(R, G, B, A) + uint8_t r = (value >> 24) & 0xFF; + uint8_t g = (value >> 16) & 0xFF; + uint8_t b = (value >> 8) & 0xFF; + uint8_t a = value & 0xFF; + out = IM_COL32(r, g, b, a); + } + + return true; +} + +bool ColorVarResolver::parseRgba(const std::string& rgba, ImU32& out) { + // Expected: "rgba(183,28,28,0.5)" or "rgba(183, 28, 28, 0.5)" + if (rgba.size() < 11) return false; // minimum: "rgba(0,0,0,0)" + + // Find opening paren + size_t open = rgba.find('('); + size_t close = rgba.rfind(')'); + if (open == std::string::npos || close == std::string::npos || close <= open) { + return false; + } + + std::string inner = rgba.substr(open + 1, close - open - 1); + + // Parse 4 comma-separated values + float values[4] = {0, 0, 0, 0}; + int count = 0; + const char* p = inner.c_str(); + + for (int i = 0; i < 4 && *p; ++i) { + // Skip whitespace + while (*p == ' ' || *p == '\t') ++p; + + char* end = nullptr; + values[i] = std::strtof(p, &end); + if (end == p) break; // failed to parse + count++; + + p = end; + // Skip whitespace and comma + while (*p == ' ' || *p == '\t') ++p; + if (*p == ',') ++p; + } + + if (count != 4) return false; + + // r,g,b are 0-255 integers, a is 0.0-1.0 float + uint8_t r = static_cast(values[0] < 0 ? 0 : (values[0] > 255 ? 255 : values[0])); + uint8_t g = static_cast(values[1] < 0 ? 0 : (values[1] > 255 ? 255 : values[1])); + uint8_t b = static_cast(values[2] < 0 ? 0 : (values[2] > 255 ? 255 : values[2])); + uint8_t a = static_cast(values[3] < 0 ? 0 : (values[3] > 1.0f ? 255 : values[3] * 255.0f)); + + out = IM_COL32(r, g, b, a); + return true; +} + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/color_var_resolver.h b/src/ui/schema/color_var_resolver.h new file mode 100644 index 0000000..613b793 --- /dev/null +++ b/src/ui/schema/color_var_resolver.h @@ -0,0 +1,75 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace schema { + +/** + * @brief CSS custom property resolver for color values + * + * Resolves color strings in multiple formats: + * - var(--name) → lookup from theme palette + * - #RRGGBB → direct hex (6 digits, alpha=255) + * - #RRGGBBAA → direct hex with alpha (8 digits) + * - rgba(r,g,b,a) → CSS-style with float alpha 0.0-1.0 + * - transparent → fully transparent + * - empty string → returns fallback + */ +class ColorVarResolver { +public: + /** + * @brief Set the palette map (called when skin is loaded) + * @param palette Map of "--name" → ImU32 color values + */ + void setPalette(const std::unordered_map& palette); + + /** + * @brief Get the current palette + */ + const std::unordered_map& palette() const { return palette_; } + + /** + * @brief Resolve a color string to an ImU32 value + * + * @param value Color string (var ref, hex, rgba, or "transparent") + * @param fallback Value to return if resolution fails or value is empty + * @return Resolved ImU32 color + */ + ImU32 resolve(const std::string& value, ImU32 fallback = IM_COL32(0,0,0,0)) const; + + /** + * @brief Check if a color string is non-empty (has an override) + */ + static bool hasValue(const std::string& value); + + /** + * @brief Parse a hex color string (#RRGGBB or #RRGGBBAA) + * @param hex The hex string (with or without # prefix) + * @param[out] out Parsed color + * @return true if parsed successfully + */ + static bool parseHex(const std::string& hex, ImU32& out); + + /** + * @brief Parse an rgba() color string + * @param rgba String like "rgba(183,28,28,0.5)" + * @param[out] out Parsed color + * @return true if parsed successfully + */ + static bool parseRgba(const std::string& rgba, ImU32& out); + +private: + std::unordered_map palette_; +}; + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/element_styles.cpp b/src/ui/schema/element_styles.cpp new file mode 100644 index 0000000..bad5696 --- /dev/null +++ b/src/ui/schema/element_styles.cpp @@ -0,0 +1,294 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "element_styles.h" +#include + +namespace dragonx { +namespace ui { +namespace schema { + +// ============================================================================ +// TOML helper macros — read optional fields, leave sentinel if absent +// ============================================================================ + +#define READ_FLOAT(t, field, out) do { auto _v = (t)[field].value(); if (_v) (out) = static_cast(*_v); } while(0) +#define READ_INT(t, field, out) do { auto _v = (t)[field].value(); if (_v) (out) = static_cast(*_v); } while(0) +#define READ_STRING(t, field, out) do { auto _v = (t)[field].value(); if (_v) (out) = *_v; } while(0) +#define READ_PADDING(t, field, out) do { \ + if ((t).contains(field)) { \ + if (auto* _arr = (t)[field].as_array(); _arr && _arr->size() >= 2) { \ + auto _v0 = (*_arr)[0].value(); \ + auto _v1 = (*_arr)[1].value(); \ + if (_v0) (out)[0] = static_cast(*_v0); \ + if (_v1) (out)[1] = static_cast(*_v1); \ + } else { \ + auto _v = (t)[field].value(); \ + if (_v) (out)[0] = (out)[1] = static_cast(*_v); \ + } \ + } \ +} while(0) + +// ============================================================================ +// Parse functions — cast void* back to toml::table +// ============================================================================ + +namespace detail { + +void parseElementColors(const void* dataObj, ElementColors& out) { + const toml::table& t = *static_cast(dataObj); + READ_STRING(t, "color", out.color); + READ_STRING(t, "background", out.background); + READ_STRING(t, "background-hover", out.backgroundHover); + READ_STRING(t, "background-active", out.backgroundActive); + READ_STRING(t, "border-color", out.borderColor); +} + +void parseButtonStyle(const void* dataObj, ButtonStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_FLOAT(t, "height", out.height); + READ_STRING(t, "font", out.font); + READ_PADDING(t, "padding", out.padding); + READ_FLOAT(t, "opacity", out.opacity); + READ_FLOAT(t, "border-radius", out.borderRadius); + READ_FLOAT(t, "border-width", out.borderWidth); + READ_FLOAT(t, "min-width", out.minWidth); + READ_STRING(t, "align", out.align); + READ_FLOAT(t, "gap", out.gap); + parseElementColors(dataObj, out.colors); +} + +void parseInputStyle(const void* dataObj, InputStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_FLOAT(t, "height", out.height); + READ_INT(t, "lines", out.lines); + READ_STRING(t, "font", out.font); + READ_PADDING(t, "padding", out.padding); + READ_FLOAT(t, "border-radius", out.borderRadius); + READ_FLOAT(t, "border-width", out.borderWidth); + READ_STRING(t, "border-color-focus", out.borderColorFocus); + READ_STRING(t, "placeholder-color", out.placeholderColor); + READ_FLOAT(t, "width-ratio", out.widthRatio); + READ_FLOAT(t, "max-width", out.maxWidth); + parseElementColors(dataObj, out.colors); +} + +void parseLabelStyle(const void* dataObj, LabelStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_STRING(t, "font", out.font); + READ_STRING(t, "color", out.color); + READ_FLOAT(t, "opacity", out.opacity); + READ_STRING(t, "align", out.align); + READ_INT(t, "truncate", out.truncate); + READ_FLOAT(t, "position", out.position); +} + +void parseTableStyle(const void* dataObj, TableStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "min-height", out.minHeight); + READ_FLOAT(t, "height-ratio", out.heightRatio); + READ_FLOAT(t, "bottom-reserve", out.bottomReserve); + READ_FLOAT(t, "row-height", out.rowHeight); + READ_STRING(t, "header-font", out.headerFont); + READ_STRING(t, "cell-font", out.cellFont); + READ_STRING(t, "border-color", out.borderColor); + READ_STRING(t, "stripe-color", out.stripeColor); + + if (auto* cols = t["columns"].as_table()) { + for (auto&& [key, val] : *cols) { + auto* colTable = val.as_table(); + if (!colTable) continue; + ColumnStyle col; + READ_FLOAT(*colTable, "width", col.width); + READ_STRING(*colTable, "font", col.font); + READ_STRING(*colTable, "align", col.align); + READ_INT(*colTable, "truncate", col.truncate); + out.columns[std::string(key.str())] = col; + } + } +} + +void parseCheckboxStyle(const void* dataObj, CheckboxStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_STRING(t, "font", out.font); + READ_STRING(t, "color", out.color); + READ_STRING(t, "check-color", out.checkColor); + READ_STRING(t, "background", out.background); +} + +void parseComboStyle(const void* dataObj, ComboStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_STRING(t, "font", out.font); + READ_STRING(t, "color", out.color); + READ_STRING(t, "background", out.background); + READ_FLOAT(t, "border-radius", out.borderRadius); + READ_INT(t, "truncate", out.truncate); +} + +void parseSliderStyle(const void* dataObj, SliderStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_STRING(t, "track-color", out.trackColor); + READ_STRING(t, "fill-color", out.fillColor); + READ_STRING(t, "thumb-color", out.thumbColor); + READ_FLOAT(t, "thumb-radius", out.thumbRadius); +} + +void parseWindowStyle(const void* dataObj, WindowStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_FLOAT(t, "height", out.height); + READ_PADDING(t, "padding", out.padding); + READ_FLOAT(t, "border-radius", out.borderRadius); + READ_FLOAT(t, "border-width", out.borderWidth); + READ_STRING(t, "background", out.background); + READ_STRING(t, "border-color", out.borderColor); + READ_STRING(t, "title-font", out.titleFont); +} + +void parseSeparatorStyle(const void* dataObj, SeparatorStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_STRING(t, "color", out.color); + READ_FLOAT(t, "thickness", out.thickness); + READ_PADDING(t, "margin", out.margin); +} + +void parseDrawElementStyle(const void* dataObj, DrawElementStyle& out) { + const toml::table& t = *static_cast(dataObj); + READ_STRING(t, "color", out.color); + READ_STRING(t, "background", out.background); + READ_FLOAT(t, "thickness", out.thickness); + READ_FLOAT(t, "radius", out.radius); + READ_FLOAT(t, "opacity", out.opacity); + READ_FLOAT(t, "size", out.size); + READ_FLOAT(t, "height", out.height); + + // Collect any extra color/float properties not in the standard set + static const char* knownKeys[] = { + "color", "background", "thickness", "radius", "opacity", "size", "height", + nullptr + }; + for (auto&& [key, val] : t) { + // Skip known keys + bool known = false; + for (const char** k = knownKeys; *k; ++k) { + if (key.str() == *k) { known = true; break; } + } + if (known) continue; + + if (val.is_string()) { + out.extraColors[std::string(key.str())] = *val.value(); + } else if (val.is_integer() || val.is_floating_point()) { + out.extraFloats[std::string(key.str())] = static_cast(val.value().value_or(0.0)); + } + } +} + +void parseBreakpointConfig(const void* dataObj, BreakpointConfig& out) { + const toml::table& t = *static_cast(dataObj); + + if (auto* c = t["compact"].as_table()) { + READ_FLOAT(*c, "max-width", out.compact.maxWidth); + READ_FLOAT(*c, "max-height", out.compact.maxHeight); + READ_FLOAT(*c, "min-width", out.compact.minWidth); + READ_FLOAT(*c, "min-height", out.compact.minHeight); + } + if (auto* e = t["expanded"].as_table()) { + READ_FLOAT(*e, "max-width", out.expanded.maxWidth); + READ_FLOAT(*e, "max-height", out.expanded.maxHeight); + READ_FLOAT(*e, "min-width", out.expanded.minWidth); + READ_FLOAT(*e, "min-height", out.expanded.minHeight); + } +} + +void parseResponsiveButtonOverride(const void* dataObj, ResponsiveButtonOverride& out) { + const toml::table& t = *static_cast(dataObj); + READ_FLOAT(t, "width", out.width); + READ_FLOAT(t, "height", out.height); + READ_STRING(t, "font", out.font); + READ_PADDING(t, "padding", out.padding); +} + +} // namespace detail + +// ============================================================================ +// Merge helpers +// ============================================================================ + +void mergeButton(ButtonStyle& base, const ButtonStyle& overlay) { + if (overlay.width > 0) base.width = overlay.width; + if (overlay.height > 0) base.height = overlay.height; + if (!overlay.font.empty()) base.font = overlay.font; + if (overlay.padding[0] > 0) { base.padding[0] = overlay.padding[0]; base.padding[1] = overlay.padding[1]; } + if (overlay.opacity >= 0) base.opacity = overlay.opacity; + if (overlay.borderRadius >= 0) base.borderRadius = overlay.borderRadius; + if (overlay.borderWidth >= 0) base.borderWidth = overlay.borderWidth; + if (overlay.minWidth >= 0) base.minWidth = overlay.minWidth; + if (!overlay.align.empty()) base.align = overlay.align; + if (overlay.gap > 0) base.gap = overlay.gap; + + // Colors: non-empty string overrides + if (!overlay.colors.color.empty()) base.colors.color = overlay.colors.color; + if (!overlay.colors.background.empty()) base.colors.background = overlay.colors.background; + if (!overlay.colors.backgroundHover.empty()) base.colors.backgroundHover = overlay.colors.backgroundHover; + if (!overlay.colors.backgroundActive.empty()) base.colors.backgroundActive = overlay.colors.backgroundActive; + if (!overlay.colors.borderColor.empty()) base.colors.borderColor = overlay.colors.borderColor; +} + +void mergeInput(InputStyle& base, const InputStyle& overlay) { + if (overlay.width != 0) base.width = overlay.width; + if (overlay.height > 0) base.height = overlay.height; + if (overlay.lines > 0) base.lines = overlay.lines; + if (!overlay.font.empty()) base.font = overlay.font; + if (overlay.padding[0] > 0) { base.padding[0] = overlay.padding[0]; base.padding[1] = overlay.padding[1]; } + if (overlay.borderRadius >= 0) base.borderRadius = overlay.borderRadius; + if (overlay.borderWidth >= 0) base.borderWidth = overlay.borderWidth; + if (!overlay.borderColorFocus.empty()) base.borderColorFocus = overlay.borderColorFocus; + if (!overlay.placeholderColor.empty()) base.placeholderColor = overlay.placeholderColor; + if (overlay.widthRatio >= 0) base.widthRatio = overlay.widthRatio; + if (overlay.maxWidth >= 0) base.maxWidth = overlay.maxWidth; + + if (!overlay.colors.color.empty()) base.colors.color = overlay.colors.color; + if (!overlay.colors.background.empty()) base.colors.background = overlay.colors.background; + if (!overlay.colors.borderColor.empty()) base.colors.borderColor = overlay.colors.borderColor; +} + +void mergeLabel(LabelStyle& base, const LabelStyle& overlay) { + if (!overlay.font.empty()) base.font = overlay.font; + if (!overlay.color.empty()) base.color = overlay.color; + if (overlay.opacity >= 0) base.opacity = overlay.opacity; + if (!overlay.align.empty()) base.align = overlay.align; + if (overlay.truncate > 0) base.truncate = overlay.truncate; + if (overlay.position >= 0) base.position = overlay.position; +} + +void mergeWindow(WindowStyle& base, const WindowStyle& overlay) { + if (overlay.width > 0) base.width = overlay.width; + if (overlay.height > 0) base.height = overlay.height; + if (overlay.padding[0] > 0) { base.padding[0] = overlay.padding[0]; base.padding[1] = overlay.padding[1]; } + if (overlay.borderRadius >= 0) base.borderRadius = overlay.borderRadius; + if (overlay.borderWidth >= 0) base.borderWidth = overlay.borderWidth; + if (!overlay.background.empty()) base.background = overlay.background; + if (!overlay.borderColor.empty()) base.borderColor = overlay.borderColor; + if (!overlay.titleFont.empty()) base.titleFont = overlay.titleFont; +} + +void applyResponsiveButton(ButtonStyle& base, const ResponsiveButtonOverride& ovr) { + if (ovr.width > 0) base.width = ovr.width; + if (ovr.height > 0) base.height = ovr.height; + if (!ovr.font.empty()) base.font = ovr.font; + if (ovr.padding[0] > 0) { base.padding[0] = ovr.padding[0]; base.padding[1] = ovr.padding[1]; } +} + +#undef READ_FLOAT +#undef READ_INT +#undef READ_STRING +#undef READ_PADDING + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/element_styles.h b/src/ui/schema/element_styles.h new file mode 100644 index 0000000..0696c3c --- /dev/null +++ b/src/ui/schema/element_styles.h @@ -0,0 +1,273 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace schema { + +// ============================================================================ +// Color properties shared by all styleable elements +// ============================================================================ + +struct ElementColors { + std::string color; // "var(--on-primary)" | "rgba(...)" | "#hex" | "" + std::string background; + std::string backgroundHover; // null = auto-derive + std::string backgroundActive; // null = auto-derive + std::string borderColor; +}; + +// ============================================================================ +// Element Style Structs +// ============================================================================ + +/** + * @brief Style for button elements + * + * Sentinel values: 0 or -1 = inherit from globals, "" = inherit + */ +struct ButtonStyle { + float width = 0; // 0 = auto-size + float height = 0; // 0 = auto from font + padding + std::string font; // "" = inherit from globals + float padding[2] = {0, 0}; // [h, v] — 0 = inherit + float opacity = -1; // -1 = inherit, 0.0-1.0 + float borderRadius = -1; // -1 = inherit + float borderWidth = -1; // -1 = inherit + float minWidth = -1; // -1 = inherit + std::string align; // "" | "left" | "center" | "right" + ElementColors colors; + + // Gap between adjacent buttons (layout helper) + float gap = 0; +}; + +/** + * @brief Style for text input elements + */ +struct InputStyle { + float width = 0; // 0 = auto, -1 = fill remaining + float height = 0; // 0 = single-line auto + int lines = 0; // 0 = inherit, 1 = single, >1 = multiline + std::string font; + float padding[2] = {0, 0}; + float borderRadius = -1; + float borderWidth = -1; + ElementColors colors; + std::string borderColorFocus; // "var(--primary)" for focus ring + std::string placeholderColor; + + // Ratio-based width (alternative to fixed) + float widthRatio = -1; // -1 = not set, 0.0-1.0 = fraction of available + float maxWidth = -1; // -1 = no limit +}; + +/** + * @brief Style for text labels + */ +struct LabelStyle { + std::string font; + std::string color; + float opacity = -1; + std::string align; + int truncate = 0; // 0 = no truncation, >0 = max chars + float position = -1; // SameLine label position (-1 = not set) +}; + +/** + * @brief Style for table columns + */ +struct ColumnStyle { + float width = -1; + std::string font; + std::string align; + int truncate = 0; +}; + +/** + * @brief Style for table elements + */ +struct TableStyle { + float minHeight = -1; + float heightRatio = -1; // fraction of available space + float bottomReserve = -1; + float rowHeight = -1; + std::string headerFont; + std::string cellFont; + std::string borderColor; + std::string stripeColor; + std::map columns; +}; + +/** + * @brief Style for checkbox elements + */ +struct CheckboxStyle { + std::string font; + std::string color; + std::string checkColor; + std::string background; +}; + +/** + * @brief Style for combo/dropdown elements + */ +struct ComboStyle { + float width = 0; + std::string font; + std::string color; + std::string background; + float borderRadius = -1; + int truncate = 0; +}; + +/** + * @brief Style for slider elements + */ +struct SliderStyle { + float width = 0; + std::string trackColor; + std::string fillColor; + std::string thumbColor; + float thumbRadius = -1; +}; + +/** + * @brief Style for windows and dialogs + */ +struct WindowStyle { + float width = 0; + float height = 0; + float padding[2] = {0, 0}; + float borderRadius = -1; + float borderWidth = -1; + std::string background; + std::string borderColor; + std::string titleFont; +}; + +/** + * @brief Style for separator lines + */ +struct SeparatorStyle { + std::string color; + float thickness = -1; + float margin[2] = {0, 0}; // [top, bottom] +}; + +/** + * @brief Style for DrawList-driven custom elements (progress rings, sparklines, etc.) + */ +struct DrawElementStyle { + std::string color; + std::string background; + float thickness = -1; + float radius = -1; + float opacity = -1; + float size = -1; // generic size (e.g., QR code size) + float height = -1; + + // Additional named properties for flexible DrawList elements + std::map extraColors; + std::map extraFloats; + + /// Look up any extra float by key, returning fallback if absent. + float getFloat(const std::string& key, float fallback = 0.0f) const { + auto it = extraFloats.find(key); + return it != extraFloats.end() ? it->second : fallback; + } + + /// Return size if set (>= 0), else fallback. + float sizeOr(float fallback) const { return size >= 0.0f ? size : fallback; } +}; + +/** + * @brief Style for spacing (layout helper) + */ +struct SpacingStyle { + float size = 0; +}; + +// ============================================================================ +// Responsive overrides +// ============================================================================ + +/** + * @brief Per-breakpoint property overrides + * + * Only non-sentinel values override the base style. Applied on top of + * the element's base style when the current window size matches the + * breakpoint. + */ +struct ResponsiveButtonOverride { + float width = 0; + float height = 0; + std::string font; + float padding[2] = {0, 0}; +}; + +struct ResponsiveInputOverride { + float width = 0; + float height = 0; +}; + +// ============================================================================ +// Breakpoint definitions +// ============================================================================ + +struct BreakpointDef { + float maxWidth = -1; // -1 = no constraint + float maxHeight = -1; + float minWidth = -1; + float minHeight = -1; +}; + +struct BreakpointConfig { + BreakpointDef compact; + BreakpointDef expanded; +}; + +// ============================================================================ +// JSON parsing helpers (implemented in element_styles.cpp) +// ============================================================================ + +// Forward declare nlohmann::json to avoid header dependency +namespace detail { + // Parse individual style types from a JSON object + // These are called by UISchema during load — not for external use + void parseButtonStyle(const void* jsonObj, ButtonStyle& out); + void parseInputStyle(const void* jsonObj, InputStyle& out); + void parseLabelStyle(const void* jsonObj, LabelStyle& out); + void parseTableStyle(const void* jsonObj, TableStyle& out); + void parseCheckboxStyle(const void* jsonObj, CheckboxStyle& out); + void parseComboStyle(const void* jsonObj, ComboStyle& out); + void parseSliderStyle(const void* jsonObj, SliderStyle& out); + void parseWindowStyle(const void* jsonObj, WindowStyle& out); + void parseSeparatorStyle(const void* jsonObj, SeparatorStyle& out); + void parseDrawElementStyle(const void* jsonObj, DrawElementStyle& out); + void parseBreakpointConfig(const void* jsonObj, BreakpointConfig& out); + void parseElementColors(const void* jsonObj, ElementColors& out); + void parseResponsiveButtonOverride(const void* jsonObj, ResponsiveButtonOverride& out); +} + +// ============================================================================ +// Merge helpers — apply overlay on top of base (non-sentinel values win) +// ============================================================================ + +void mergeButton(ButtonStyle& base, const ButtonStyle& overlay); +void mergeInput(InputStyle& base, const InputStyle& overlay); +void mergeLabel(LabelStyle& base, const LabelStyle& overlay); +void mergeWindow(WindowStyle& base, const WindowStyle& overlay); +void applyResponsiveButton(ButtonStyle& base, const ResponsiveButtonOverride& ovr); + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/skin_manager.cpp b/src/ui/schema/skin_manager.cpp new file mode 100644 index 0000000..a4d46a0 --- /dev/null +++ b/src/ui/schema/skin_manager.cpp @@ -0,0 +1,800 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "skin_manager.h" +#include "ui_schema.h" +#include "../../util/platform.h" +#include "../../resources/embedded_resources.h" +#include "../theme.h" +#include "../material/color_theme.h" +#include "../effects/theme_effects.h" +#include "../effects/imgui_acrylic.h" + +#include +#include +#include +#include +#include +#include "../../util/logger.h" + +namespace fs = std::filesystem; + +namespace dragonx { +namespace ui { +namespace schema { + +// ============================================================================ +// Singleton +// ============================================================================ + +SkinManager& SkinManager::instance() { + static SkinManager s; + return s; +} + +// ============================================================================ +// Directory helpers +// ============================================================================ + +std::string SkinManager::getBundledSkinsDirectory() { + // Bundled skins live in res/themes/ next to the executable + fs::path exe_dir = util::getExecutableDirectory(); + fs::path themes_dir = exe_dir / "res" / "themes"; + + if (fs::exists(themes_dir)) { + return themes_dir.string(); + } + + // Fallback: current working directory + themes_dir = fs::current_path() / "res" / "themes"; + if (fs::exists(themes_dir)) { + return themes_dir.string(); + } + + // No on-disk themes dir found (single-file Windows distribution). + // Extract embedded overlay themes to the config directory. + fs::path configDir = util::Platform::getObsidianDragonDir(); + fs::path extractedDir = configDir / "bundled-themes"; + int extracted = resources::extractBundledThemes(extractedDir.string()); + if (extracted > 0) { + DEBUG_LOGF("[SkinManager] Extracted %d embedded bundled themes to %s\n", + extracted, extractedDir.string().c_str()); + } + if (fs::exists(extractedDir)) { + return extractedDir.string(); + } + + return (exe_dir / "res" / "themes").string(); +} + +std::string SkinManager::getUserSkinsDirectory() { + // User themes in ObsidianDragon config directory — folder-based + fs::path configDir = util::Platform::getObsidianDragonDir(); + return (configDir / "themes").string(); +} + +// ============================================================================ +// Scan for skins +// ============================================================================ + +void SkinManager::scanDirectory(const std::string& dir, bool bundled) { + if (!fs::exists(dir) || !fs::is_directory(dir)) { + DEBUG_LOGF("[SkinManager] Directory does not exist: %s\n", dir.c_str()); + return; + } + + DEBUG_LOGF("[SkinManager] Scanning %s directory: %s\n", bundled ? "bundled" : "user", dir.c_str()); + + if (bundled) { + // Bundled skins: all .toml files in res/themes/ except ui.toml + // (ui.toml is the base theme and is always loaded as "dragonx") + for (const auto& entry : fs::directory_iterator(dir)) { + if (!entry.is_regular_file()) continue; + + fs::path p = entry.path(); + if (p.extension() != ".toml") continue; + + std::string stem = p.stem().string(); + + // Skip ui.toml - it's the base theme handled separately as "dragonx" + if (stem == "ui") continue; + + // Try to parse and extract metadata + toml::table root; + try { + root = toml::parse_file(p.string()); + } catch (...) { + DEBUG_LOGF("[SkinManager] Skipping '%s': invalid TOML\n", p.filename().string().c_str()); + continue; + } + + auto* theme = root["theme"].as_table(); + if (!theme) { + DEBUG_LOGF("[SkinManager] Skipping '%s': no [theme] section\n", p.filename().string().c_str()); + continue; + } + + SkinInfo info; + info.path = p.string(); + info.bundled = true; + + // ID = filename stem (e.g. "dark" from dark.toml) + info.id = stem; + + if (auto name = (*theme)["name"].value()) { + info.name = *name; + } else { + info.name = info.id; + } + + if (auto author = (*theme)["author"].value()) { + info.author = *author; + } + + if (auto dark = (*theme)["dark"].value()) { + info.dark = *dark; + } + + // Resolve image paths from theme.images (bundled: res/img/) + fs::path imgDir = p.parent_path().parent_path() / "img"; + std::string bgFilename; + std::string logoFilename; + + if (auto* images = (*theme)["images"].as_table()) { + if (auto bg = (*images)["background_image"].value()) { + bgFilename = *bg; + } + if (auto logo = (*images)["logo"].value()) { + logoFilename = *logo; + } + } + + if (!bgFilename.empty()) { + fs::path bgPath = imgDir / bgFilename; + if (fs::exists(bgPath)) { + info.backgroundImagePath = bgPath.string(); + } + } + + if (!logoFilename.empty()) { + fs::path logoImgPath = imgDir / logoFilename; + if (fs::exists(logoImgPath)) { + info.logoPath = logoImgPath.string(); + } + } + + skins_.push_back(std::move(info)); + } + } else { + // User themes: each subfolder must contain a theme.toml + for (const auto& entry : fs::directory_iterator(dir)) { + if (!entry.is_directory()) continue; + + fs::path themeDir = entry.path(); + fs::path themeToml = themeDir / "theme.toml"; + + if (!fs::exists(themeToml)) { + DEBUG_LOGF("[SkinManager] Skipping folder '%s': no theme.toml found\n", + themeDir.filename().string().c_str()); + continue; + } + + DEBUG_LOGF("[SkinManager] Found theme folder: %s (theme.toml exists)\n", themeDir.filename().string().c_str()); + + // Validate the theme file + auto validation = validateSkinFile(themeToml.string()); + + // Parse metadata even from invalid themes (so they show in the list) + toml::table root; + try { + root = toml::parse_file(themeToml.string()); + } catch (...) { + // Still add as invalid + SkinInfo info; + info.id = themeDir.filename().string(); + info.name = info.id; + info.path = themeToml.string(); + info.directory = themeDir.string(); + info.bundled = false; + info.valid = false; + info.validationError = "Invalid TOML"; + skins_.push_back(std::move(info)); + continue; + } + + SkinInfo info; + info.id = themeDir.filename().string(); + info.path = themeToml.string(); + info.directory = themeDir.string(); + info.bundled = false; + info.valid = validation.valid; + info.validationError = validation.error; + + // Extract metadata from theme section + if (auto* theme = root["theme"].as_table()) { + + if (auto name = (*theme)["name"].value()) { + info.name = *name; + } else { + info.name = info.id; + } + + if (auto author = (*theme)["author"].value()) { + info.author = *author; + } + + if (auto dark = (*theme)["dark"].value()) { + info.dark = *dark; + } + + // Resolve image paths (from TOML) + fs::path imgDir = themeDir / "img"; + std::string bgFilename; + std::string logoFilename; + + if (auto* images = (*theme)["images"].as_table()) { + if (auto bg = (*images)["background_image"].value()) { + bgFilename = *bg; + } + if (auto logo = (*images)["logo"].value()) { + logoFilename = *logo; + } + } + + // Check if image files exist + if (!bgFilename.empty()) { + fs::path bgPath = imgDir / bgFilename; + if (fs::exists(bgPath)) { + info.backgroundImagePath = bgPath.string(); + } + } + + if (!logoFilename.empty()) { + fs::path logoImgPath = imgDir / logoFilename; + if (fs::exists(logoImgPath)) { + info.logoPath = logoImgPath.string(); + } + } + } else { + info.name = info.id; + } + + skins_.push_back(std::move(info)); + } + + // Also scan for loose .toml files (unified format with [theme.palette]) + for (const auto& entry : fs::directory_iterator(dir)) { + if (!entry.is_regular_file()) continue; + + fs::path p = entry.path(); + if (p.extension() != ".toml") continue; + + toml::table root; + try { + root = toml::parse_file(p.string()); + } catch (...) { + DEBUG_LOGF("[SkinManager] Skipping '%s': invalid TOML\n", p.filename().string().c_str()); + continue; + } + + SkinInfo info; + info.path = p.string(); + info.id = p.stem().string(); + info.bundled = false; + + // Check for unified format ([theme] with [theme.palette]) + auto* theme = root["theme"].as_table(); + if (theme) { + if (auto name = (*theme)["name"].value()) { + info.name = *name; + } else { + info.name = info.id; + } + if (auto author = (*theme)["author"].value()) { + info.author = *author; + } + if (auto dark = (*theme)["dark"].value()) { + info.dark = *dark; + } + + auto validation = validateSkinFile(p.string()); + info.valid = validation.valid; + info.validationError = validation.error; + + // Resolve image paths (look in same directory as the .toml file) + fs::path imgDir = p.parent_path(); + std::string bgFilename; + std::string logoFilename; + + if (auto* images = (*theme)["images"].as_table()) { + if (auto bg = (*images)["background_image"].value()) { + bgFilename = *bg; + } + if (auto logo = (*images)["logo"].value()) { + logoFilename = *logo; + } + } + + if (!bgFilename.empty()) { + fs::path bgPath = imgDir / bgFilename; + if (fs::exists(bgPath)) { + info.backgroundImagePath = bgPath.string(); + } + } + if (!logoFilename.empty()) { + fs::path logoImgPath = imgDir / logoFilename; + if (fs::exists(logoImgPath)) { + info.logoPath = logoImgPath.string(); + } + } + } + else { + DEBUG_LOGF("[SkinManager] Skipping '%s': unrecognized TOML format\n", + p.filename().string().c_str()); + continue; + } + + skins_.push_back(std::move(info)); + } + } +} + +void SkinManager::refresh() { + skins_.clear(); + + // Scan bundled skins (res/ directory) + scanDirectory(getBundledSkinsDirectory(), true); + + // Scan user skins + std::string userDir = getUserSkinsDirectory(); + if (fs::exists(userDir)) { + scanDirectory(userDir, false); + } + + // Ensure the base "dragonx" theme always appears (it's ui.toml, the main theme). + // Other bundled themes are discovered automatically from res/themes/*.toml. + { + bool found = false; + for (const auto& s : skins_) { + if (s.id == "dragonx") { found = true; break; } + } + if (!found) { + SkinInfo info; + info.id = "dragonx"; + info.name = "DragonX"; + info.author = "The Hush Developers"; + info.dark = true; + info.bundled = true; + info.valid = true; + // Try to set path to ui.toml if it exists + fs::path uiPath = fs::path(getBundledSkinsDirectory()) / "ui.toml"; + if (fs::exists(uiPath)) { + info.path = uiPath.string(); + } + skins_.push_back(std::move(info)); + DEBUG_LOGF("[SkinManager] Injected base theme: dragonx\n"); + } + } + + // Sort: "dragonx" first, then bundled grouped by mode (dark then light), then user + std::sort(skins_.begin(), skins_.end(), [](const SkinInfo& a, const SkinInfo& b) { + // DragonX always first + if (a.id == "dragonx") return true; + if (b.id == "dragonx") return false; + + // Bundled before user + if (a.bundled != b.bundled) return a.bundled; + + // Group: dark themes first, then light themes + if (a.dark != b.dark) return a.dark; + + // Alphabetical by name within each group + return a.name < b.name; + }); + + DEBUG_LOGF("[SkinManager] Found %zu skins\n", skins_.size()); +} + +// ============================================================================ +// Find +// ============================================================================ + +const SkinManager::SkinInfo* SkinManager::findById(const std::string& id) const { + for (const auto& skin : skins_) { + if (skin.id == id) return &skin; + } + return nullptr; +} + +// ============================================================================ +// Validation +// ============================================================================ + +SkinManager::ValidationResult SkinManager::validateSkinFile(const std::string& path) { + ValidationResult result; + + // 1. Must be valid TOML + toml::table root; + try { + root = toml::parse_file(path); + } catch (const toml::parse_error& e) { + result.error = std::string("Invalid TOML: ") + e.what(); + return result; + } + + // 3. Must contain "theme" table + auto* theme = root["theme"].as_table(); + if (!theme) { + result.error = "Missing or invalid 'theme' section"; + return result; + } + + // 4. theme.name must be a non-empty string + auto name = (*theme)["name"].value(); + if (!name || name->empty()) { + result.error = "theme.name must be a non-empty string"; + return result; + } + + // 5. theme.palette must exist with at least --primary and --background + auto* palette = (*theme)["palette"].as_table(); + if (!palette) { + result.error = "Missing theme.palette table"; + return result; + } + + if (!palette->contains("--primary")) { + result.error = "Palette missing required '--primary' color"; + return result; + } + if (!palette->contains("--background")) { + result.error = "Palette missing required '--background' color"; + return result; + } + + // 6. If globals exists, must be a table + if (root.contains("globals") && !root["globals"].is_table()) { + result.error = "'globals' must be a table"; + return result; + } + + result.valid = true; + return result; +} + +// ============================================================================ +// Import +// ============================================================================ + +bool SkinManager::importSkin(const std::string& sourcePath) { + fs::path srcPath(sourcePath); + std::string userDir = getUserSkinsDirectory(); + + try { + fs::create_directories(userDir); + } catch (const fs::filesystem_error& e) { + DEBUG_LOGF("[SkinManager] Failed to create themes directory: %s\n", e.what()); + return false; + } + + if (fs::is_directory(srcPath)) { + // Import a theme folder — copy entire folder into themes/ + fs::path themeToml = srcPath / "theme.toml"; + if (!fs::exists(themeToml)) { + DEBUG_LOGF("[SkinManager] Import folder has no theme.toml: %s\n", sourcePath.c_str()); + return false; + } + + auto validation = validateSkinFile(themeToml.string()); + if (!validation.valid) { + DEBUG_LOGF("[SkinManager] Import validation failed: %s\n", validation.error.c_str()); + return false; + } + + fs::path destDir = fs::path(userDir) / srcPath.filename(); + try { + fs::copy(srcPath, destDir, fs::copy_options::recursive | fs::copy_options::overwrite_existing); + } catch (const fs::filesystem_error& e) { + DEBUG_LOGF("[SkinManager] Failed to copy theme folder: %s\n", e.what()); + return false; + } + + DEBUG_LOGF("[SkinManager] Imported theme folder: %s → %s\n", sourcePath.c_str(), destDir.string().c_str()); + } else { + // Import a single .toml file — create a folder for it + auto validation = validateSkinFile(sourcePath); + if (!validation.valid) { + DEBUG_LOGF("[SkinManager] Import validation failed: %s\n", validation.error.c_str()); + return false; + } + + std::string folderName = srcPath.stem().string(); + fs::path destDir = fs::path(userDir) / folderName; + try { + fs::create_directories(destDir); + fs::copy_file(srcPath, destDir / "theme.toml", fs::copy_options::overwrite_existing); + } catch (const fs::filesystem_error& e) { + DEBUG_LOGF("[SkinManager] Failed to import skin file: %s\n", e.what()); + return false; + } + + DEBUG_LOGF("[SkinManager] Imported skin file as folder: %s → %s\n", sourcePath.c_str(), destDir.string().c_str()); + } + + refresh(); + return true; +} + +// ============================================================================ +// Remove +// ============================================================================ + +bool SkinManager::removeSkin(const std::string& id) { + const SkinInfo* skin = findById(id); + if (!skin) { + DEBUG_LOGF("[SkinManager] Skin not found: %s\n", id.c_str()); + return false; + } + + if (skin->bundled) { + DEBUG_LOGF("[SkinManager] Cannot remove bundled skin: %s\n", id.c_str()); + return false; + } + + try { + if (!skin->directory.empty() && fs::is_directory(skin->directory)) { + // Folder-based theme — remove the entire directory + fs::remove_all(skin->directory); + } else { + // Legacy flat file + fs::remove(skin->path); + } + } catch (const fs::filesystem_error& e) { + DEBUG_LOGF("[SkinManager] Failed to remove skin: %s\n", e.what()); + return false; + } + + DEBUG_LOGF("[SkinManager] Removed skin: %s\n", id.c_str()); + + // If we removed the active skin, fall back to default + if (activeSkinId_ == id) { + setActiveSkin("dragonx"); + } + + refresh(); + return true; +} + +// ============================================================================ +// Activate skin +// ============================================================================ + +bool SkinManager::setActiveSkin(const std::string& id) { + const SkinInfo* skin = findById(id); + if (!skin) { + DEBUG_LOGF("[SkinManager] Skin not found: %s\n", id.c_str()); + return false; + } + + if (!skin->valid) { + DEBUG_LOGF("[SkinManager] Skin is invalid: %s (%s)\n", id.c_str(), skin->validationError.c_str()); + return false; + } + + bool loaded = false; + + // For skin files: always reload base layout first, then merge visual + // overlay on top. This ensures overlays only change palette + backdrop + // while inheriting all layout values from ui.toml. + if (!skin->path.empty()) { + auto& schema = UISchema::instance(); + std::string basePath = schema.basePath(); + + if (!basePath.empty() || schema.hasEmbeddedBase()) { + if (!basePath.empty() && basePath == skin->path) { + // Switching back to the base theme: full reload, clear overlay + schema.reloadBase(); + schema.reapplyColorsToImGui(); + loaded = true; + } else { + // Switching to a non-base skin: reload base then merge overlay + if (schema.reloadBase()) { + if (schema.mergeOverlayFromFile(skin->path)) { + schema.reapplyColorsToImGui(); + loaded = true; + } + } + } + } + + // Fallback: no base path or embedded data, full load of skin file + if (!loaded && schema.loadFromFile(skin->path)) { + schema.reapplyColorsToImGui(); + loaded = true; + } + } else if (!id.empty()) { + // Skin with no path (e.g., "dragonx" on Windows with embedded ui.toml): + // just reload the base to restore the default theme + auto& schema = UISchema::instance(); + if (schema.hasEmbeddedBase() || !schema.basePath().empty()) { + schema.reloadBase(); + schema.reapplyColorsToImGui(); + loaded = true; + } + } + + // Fall back to built-in C++ themes (works even without theme files) + if (!loaded) { + if (!SetThemeById(id)) { + DEBUG_LOGF("[SkinManager] Failed to load skin: %s\n", id.c_str()); + return false; + } + DEBUG_LOGF("[SkinManager] Loaded via built-in theme fallback: %s\n", id.c_str()); + loaded = true; + } + + activeSkinId_ = id; + DEBUG_LOGF("[SkinManager] Activated skin: %s (%s)\n", id.c_str(), skin->name.c_str()); + + // Reload theme visual effects config from the new skin's [effects] section + effects::ThemeEffects::instance().loadFromTheme(); + + // Resolve image paths from UISchema (which parsed [theme] images from the TOML). + // The UISchema stores relative filenames (e.g. "backgrounds/texture/drgx_bg.png"); + // resolve them to absolute paths using the theme's directory structure. + { + // Use a mutable reference to update the SkinInfo + SkinInfo* mutableSkin = nullptr; + for (auto& s : skins_) { + if (s.id == id) { mutableSkin = &s; break; } + } + + fs::path imgDir = resolveImgDir(skin); + resolveAndFireCallback(mutableSkin, imgDir); + } + + // Force acrylic to re-capture the background with new theme colors/images. + // This must happen AFTER images are reloaded so the next frame renders the + // updated background before capture. + effects::ImGuiAcrylic::InvalidateCapture(); + + return true; +} + +void SkinManager::resolveAndReloadImages(const std::string& skinId, const std::string& tomlPath) { + // Find the skin and update its image paths from the current UISchema values + SkinInfo* skin = nullptr; + for (auto& s : skins_) { + if (s.id == skinId) { + skin = &s; + break; + } + } + + fs::path imgDir = resolveImgDir(skin); + resolveAndFireCallback(skin, imgDir); +} + +// --------------------------------------------------------------------------- +// Gradient mode +// --------------------------------------------------------------------------- + +void SkinManager::setGradientMode(bool enabled) { + if (gradientMode_ == enabled) return; + gradientMode_ = enabled; + + // Re-resolve + reload for the currently active skin + const SkinInfo* skin = findById(activeSkinId_); + if (!skin) return; + + SkinInfo* mutableSkin = nullptr; + for (auto& s : skins_) { + if (s.id == activeSkinId_) { mutableSkin = &s; break; } + } + + fs::path imgDir = resolveImgDir(skin); + resolveAndFireCallback(mutableSkin, imgDir); + + effects::ImGuiAcrylic::InvalidateCapture(); +} + +// --------------------------------------------------------------------------- +// Private helpers +// --------------------------------------------------------------------------- + +fs::path SkinManager::resolveImgDir(const SkinInfo* skin) const { + if (!skin) { + return fs::path(getBundledSkinsDirectory()).parent_path() / "img"; + } + if (skin->bundled) { + fs::path themeDir = skin->path.empty() + ? fs::path(getBundledSkinsDirectory()) + : fs::path(skin->path).parent_path(); + return themeDir.parent_path() / "img"; + } + if (!skin->directory.empty()) { + return fs::path(skin->directory) / "img"; + } + if (!skin->path.empty()) { + return fs::path(skin->path).parent_path(); + } + return fs::path(getBundledSkinsDirectory()).parent_path() / "img"; +} + +std::string SkinManager::resolveGradientBg(const std::string& bgFilename, + const fs::path& imgDir, + bool isDark) const { + // Given bgFilename like "backgrounds/texture/drgx_bg.png", + // look for "backgrounds/gradient/gradient_drgx_bg.png". + fs::path bgRel(bgFilename); + std::string stem = bgRel.stem().string(); // "drgx_bg" + std::string ext = bgRel.extension().string(); // ".png" + + // Build the gradient candidate: backgrounds/gradient/gradient_ + std::string gradientRel = "backgrounds/gradient/gradient_" + stem + ext; + fs::path gradientPath = imgDir / gradientRel; + + if (fs::exists(gradientPath)) { + return gradientPath.string(); + } + + // Fallback: dark_gradient.png or light_gradient.png + std::string fallbackName = isDark ? "dark_gradient.png" : "light_gradient.png"; + std::string fallbackRel = "backgrounds/gradient/" + fallbackName; + fs::path fallbackPath = imgDir / fallbackRel; + + if (fs::exists(fallbackPath)) { + return fallbackPath.string(); + } + + // Last resort: pass the relative gradient filename for embedded lookup (Windows) + return gradientRel; +} + +void SkinManager::resolveAndFireCallback(SkinInfo* skin, const fs::path& imgDir) { + auto& schema = UISchema::instance(); + std::string bgFilename = schema.backgroundImagePath(); + std::string logoFilename = schema.logoImagePath(); + + std::string resolvedBg; + std::string resolvedLogo; + + if (!bgFilename.empty()) { + if (gradientMode_) { + resolvedBg = resolveGradientBg(bgFilename, imgDir, schema.isDarkTheme()); + } else { + fs::path bgPath = imgDir / bgFilename; + if (fs::exists(bgPath)) { + resolvedBg = bgPath.string(); + } else { + resolvedBg = bgFilename; + } + } + } + + if (!logoFilename.empty()) { + fs::path logoPath = imgDir / logoFilename; + if (fs::exists(logoPath)) { + resolvedLogo = logoPath.string(); + } else { + resolvedLogo = logoFilename; + } + } + + if (skin) { + skin->backgroundImagePath = resolvedBg; + skin->logoPath = resolvedLogo; + } + + DEBUG_LOGF("[SkinManager] Resolved images (gradient=%s): bg='%s', logo='%s'\n", + gradientMode_ ? "on" : "off", resolvedBg.c_str(), resolvedLogo.c_str()); + + if (imageReloadCb_) { + imageReloadCb_(resolvedBg, resolvedLogo); + } +} + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/skin_manager.h b/src/ui/schema/skin_manager.h new file mode 100644 index 0000000..2469972 --- /dev/null +++ b/src/ui/schema/skin_manager.h @@ -0,0 +1,192 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace schema { + +/** + * @brief Manages bundled and user-installed skins (unified TOML files) + * + * Responsibilities: + * - Enumerate bundled skins from res/themes/ directory (any .toml except ui.toml) + * - Enumerate user themes from ~/.config/ObsidianDragon/themes//theme.toml + * - Import / remove user skins + * - Validate skin TOML structure before import + * - Track active skin ID in settings + */ +class SkinManager { +public: + /** + * @brief Metadata about an available skin + */ + struct SkinInfo { + std::string id; ///< Unique identifier (folder name or filename stem) + std::string name; ///< Display name from theme.name + std::string author; ///< Author from theme.author + std::string path; ///< Full filesystem path to the TOML file + std::string directory; ///< Folder containing theme.toml (empty for bundled flat files) + std::string backgroundImagePath; ///< Resolved path to background image override (empty = use default) + std::string logoPath; ///< Resolved path to logo image override (empty = use default) + bool dark = true; ///< Dark mode flag from theme.dark + bool bundled = true; ///< true = shipped with app, false = user-installed + bool valid = true; ///< true if theme.toml passed validation + std::string validationError; ///< Error message if !valid + }; + + /** + * @brief Result of a skin validation + */ + struct ValidationResult { + bool valid = false; + std::string error; ///< Error message if !valid + }; + + /** + * @brief Get the singleton instance + */ + static SkinManager& instance(); + + /** + * @brief Scan for available skins (bundled + user) + * + * Re-scans both the bundled res/ directory and the user skins directory. + * Call this on startup and after import/remove operations. + */ + void refresh(); + + /** + * @brief Get the list of available skins + * @return Sorted list: bundled skins first (with "dragonx" at top), then user skins + */ + const std::vector& available() const { return skins_; } + + /** + * @brief Find a skin by ID + * @return Pointer to SkinInfo, or nullptr if not found + */ + const SkinInfo* findById(const std::string& id) const; + + /** + * @brief Validate a skin TOML file + * @param path Path to the TOML file + * @return Validation result with error message if invalid + * + * Validation rules: + * 1. File must be valid TOML + * 2. Must contain [theme] table + * 3. theme.name must be a non-empty string + * 4. theme.palette must be a table with at least --primary and --background + * 5. If [globals] exists, it must be a table + */ + static ValidationResult validateSkinFile(const std::string& path); + + /** + * @brief Import a skin file into the user skins directory + * @param sourcePath Path to the source TOML file + * @return true if imported successfully + * + * Validates the file first. Copies to user skins directory. + * Calls refresh() on success. + */ + bool importSkin(const std::string& sourcePath); + + /** + * @brief Remove a user-installed skin + * @param id Skin ID to remove + * @return true if removed successfully + * + * Cannot remove bundled skins. Calls refresh() on success. + */ + bool removeSkin(const std::string& id); + + /** + * @brief Apply a skin by ID + * @param id Skin ID to activate + * @return true if skin was found and loaded + * + * Loads the skin file into UISchema and applies ImGui colors. + */ + bool setActiveSkin(const std::string& id); + + /** + * @brief Get the currently active skin ID + */ + const std::string& activeSkinId() const { return activeSkinId_; } + + /** + * @brief Get the bundled skins directory path + */ + static std::string getBundledSkinsDirectory(); + + /** + * @brief Get the user skins directory path + */ + static std::string getUserSkinsDirectory(); + + /** + * @brief Set callback invoked after skin changes (for image reloading) + * @param cb Callback receiving backgroundImagePath and logoPath (empty = use default) + */ + void setImageReloadCallback(std::function cb) { + imageReloadCb_ = std::move(cb); + } + + /** + * @brief Re-resolve image paths from UISchema and trigger reload callback + * + * Called by UISchema hot-reload when [theme.images] values change. + * Updates the active SkinInfo's image paths and fires imageReloadCb_. + * + * @param skinId Active skin ID to update + * @param tomlPath Path to the TOML file whose images section changed + */ + void resolveAndReloadImages(const std::string& skinId, const std::string& tomlPath); + + /** + * @brief Enable/disable gradient background mode + * + * When enabled, theme backgrounds are replaced with their gradient + * variants (e.g. "gradient_drgx_bg.png" instead of "drgx_bg.png"). + * Falls back to dark_gradient.png or light_gradient.png when no + * theme-specific gradient exists. + */ + void setGradientMode(bool enabled); + bool isGradientMode() const { return gradientMode_; } + +private: + SkinManager() = default; + ~SkinManager() = default; + SkinManager(const SkinManager&) = delete; + SkinManager& operator=(const SkinManager&) = delete; + + void scanDirectory(const std::string& dir, bool bundled); + + /// Resolve the image directory for a given skin + std::filesystem::path resolveImgDir(const SkinInfo* skin) const; + + /// Given an original bg relative path and img dir, resolve the gradient variant + std::string resolveGradientBg(const std::string& bgFilename, + const std::filesystem::path& imgDir, + bool isDark) const; + + /// Common helper: resolve bg (optionally gradient) and logo, fire callback + void resolveAndFireCallback(SkinInfo* skin, const std::filesystem::path& imgDir); + + std::vector skins_; + std::string activeSkinId_ = "dragonx"; + bool gradientMode_ = false; + std::function imageReloadCb_; +}; + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/ui_schema.cpp b/src/ui/schema/ui_schema.cpp new file mode 100644 index 0000000..53b6e40 --- /dev/null +++ b/src/ui/schema/ui_schema.cpp @@ -0,0 +1,852 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "ui_schema.h" +#include "skin_manager.h" +#include "color_var_resolver.h" +#include "element_styles.h" +#include "../material/typography.h" +#include "../material/color_theme.h" +#include "../theme.h" +#include "../theme_loader.h" +#include "../effects/imgui_acrylic.h" +#include +#include +#include +#include +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { +namespace schema { + +// ============================================================================ +// Singleton +// ============================================================================ + +UISchema& UISchema::instance() { + static UISchema s; + return s; +} + +// ============================================================================ +// Load +// ============================================================================ + +bool UISchema::loadFromFile(const std::string& path) { + toml::table root; + try { + root = toml::parse_file(path); + } catch (const toml::parse_error& e) { + DEBUG_LOGF("[UISchema] TOML parse error in %s: %s\n", path.c_str(), e.what()); + return false; + } + + // Clear previous data + elements_.clear(); + backgroundImagePath_.clear(); + logoImagePath_.clear(); + + // Parse top-level sections + if (auto* theme = root["theme"].as_table()) { + parseTheme(static_cast(theme)); + } + + if (auto* bp = root["breakpoints"].as_table()) { + parseBreakpoints(static_cast(bp)); + } + + if (auto* globals = root["globals"].as_table()) { + parseGlobals(static_cast(globals)); + } + + // Parse tabs, dialogs, components sections → store elements + if (auto* tabs = root["tabs"].as_table()) { + parseSections(static_cast(tabs), "tabs"); + } + + if (auto* dialogs = root["dialogs"].as_table()) { + parseSections(static_cast(dialogs), "dialogs"); + } + + if (auto* components = root["components"].as_table()) { + parseSections(static_cast(components), "components"); + } + + // Parse flat sections (2-level: sectionName.elementName → {style object}) + for (const auto& flatSection : {"business", "animations", "console", + "backdrop", "shutdown", "notifications", "status-bar", + "qr-code", "content-area", "style", "responsive", + "spacing", "spacing-tokens", "button", "input", "fonts", + "inline-dialogs", "sidebar", "panels", "typography", "effects"}) { + if (auto* sec = root[flatSection].as_table()) { + parseFlatSection(static_cast(sec), flatSection); + } + } + + currentPath_ = path; + if (basePath_.empty()) { + basePath_ = path; // Only set on first load (the true base) + } + overlayPath_.clear(); // No overlay yet + loaded_ = true; + dirty_ = false; + + // Record initial modification time + try { + lastModTime_ = std::filesystem::last_write_time(path); + if (path == basePath_) { + baseModTime_ = lastModTime_; + } + } catch (const std::filesystem::filesystem_error&) { + // Non-fatal + } + + DEBUG_LOGF("[UISchema] Loaded: %s (theme: %s, %s, %zu elements, gen=%u)\n", + path.c_str(), themeName_.c_str(), + darkTheme_ ? "dark" : "light", + elements_.size(), generation_); + + return true; +} + +bool UISchema::loadFromString(const std::string& tomlStr, const std::string& label) { + toml::table root; + try { + root = toml::parse(tomlStr); + } catch (const toml::parse_error& e) { + DEBUG_LOGF("[UISchema] TOML parse error (%s): %s\n", label.c_str(), e.what()); + return false; + } + + // Store the raw TOML string so the base can be reloaded later + // (needed when no file-based basePath_ is available, e.g., Windows embedded) + embeddedTomlStr_ = tomlStr; + + // Clear previous data + elements_.clear(); + backgroundImagePath_.clear(); + logoImagePath_.clear(); + + // Parse top-level sections + if (auto* theme = root["theme"].as_table()) { + parseTheme(static_cast(theme)); + } + + if (auto* bp = root["breakpoints"].as_table()) { + parseBreakpoints(static_cast(bp)); + } + + if (auto* globals = root["globals"].as_table()) { + parseGlobals(static_cast(globals)); + } + + if (auto* tabs = root["tabs"].as_table()) { + parseSections(static_cast(tabs), "tabs"); + } + + if (auto* dialogs = root["dialogs"].as_table()) { + parseSections(static_cast(dialogs), "dialogs"); + } + + if (auto* components = root["components"].as_table()) { + parseSections(static_cast(components), "components"); + } + + // Parse flat sections (2-level: sectionName.elementName → {style object}) + for (const auto& flatSection : {"business", "animations", "console", + "backdrop", "shutdown", "notifications", "status-bar", + "qr-code", "content-area", "style", "responsive", + "spacing", "spacing-tokens", "button", "input", "fonts", + "inline-dialogs", "sidebar", "panels", "typography", "effects"}) { + if (auto* sec = root[flatSection].as_table()) { + parseFlatSection(static_cast(sec), flatSection); + } + } + + overlayPath_.clear(); // No overlay when loading a full base + currentPath_ = label; // Track what is loaded (for logging) + loaded_ = true; + dirty_ = false; + ++generation_; + + DEBUG_LOGF("[UISchema] Loaded from %s (theme: %s, %s, %zu elements)\n", + label.c_str(), themeName_.c_str(), + darkTheme_ ? "dark" : "light", + elements_.size()); + + return true; +} + +// ============================================================================ +// Overlay merge (visual-only: theme + backdrop) +// ============================================================================ + +bool UISchema::mergeOverlayFromFile(const std::string& path) { + if (!loaded_) { + DEBUG_LOGF("[UISchema] mergeOverlay called before base load — falling back to full load\n"); + return loadFromFile(path); + } + + std::ifstream file(path); + if (!file.is_open()) { + DEBUG_LOGF("[UISchema] Failed to open overlay: %s\n", path.c_str()); + return false; + } + + toml::table root; + try { + root = toml::parse_file(path); + } catch (const toml::parse_error& e) { + DEBUG_LOGF("[UISchema] TOML parse error in overlay %s: %s\n", path.c_str(), e.what()); + return false; + } + + // Merge theme section (palette, elevation, images, dark flag, name) + if (auto* theme = root["theme"].as_table()) { + parseTheme(static_cast(theme)); + } + + // Merge backdrop section (gradient colors, alpha/transparency values) + if (auto* sec = root["backdrop"].as_table()) { + parseFlatSection(static_cast(sec), "backdrop"); + } + + // Merge effects section (theme visual effects configuration) + if (auto* sec = root["effects"].as_table()) { + parseFlatSection(static_cast(sec), "effects"); + } + + overlayPath_ = path; + // Track overlay file for hot-reload + currentPath_ = path; + ++generation_; + try { + lastModTime_ = std::filesystem::last_write_time(path); + } catch (const std::filesystem::filesystem_error&) {} + + DEBUG_LOGF("[UISchema] Merged overlay: %s (theme: %s, %s)\n", + path.c_str(), themeName_.c_str(), + darkTheme_ ? "dark" : "light"); + + return true; +} + +// ============================================================================ +// Reload base theme (from file or embedded string) +// ============================================================================ + +bool UISchema::reloadBase() { + // Prefer file-based reload when a basePath is available + if (!basePath_.empty()) { + return loadFromFile(basePath_); + } + // Fallback: reload from stored embedded string + if (!embeddedTomlStr_.empty()) { + return loadFromString(embeddedTomlStr_, "embedded-reload"); + } + DEBUG_LOGF("[UISchema] reloadBase: no base path or embedded data available\n"); + return false; +} + +// ============================================================================ +// Theme parsing +// ============================================================================ + +void UISchema::parseTheme(const void* dataObj) { + const toml::table& t = *static_cast(dataObj); + + if (auto name = t["name"].value()) { + themeName_ = *name; + } + if (auto dark = t["dark"].value()) { + darkTheme_ = *dark; + } + + // Parse palette → ColorVarResolver + if (auto* palette = t["palette"].as_table()) { + std::unordered_map paletteMap; + for (auto&& [key, val] : *palette) { + if (!val.is_string()) continue; + ImU32 color = 0; + std::string colorStr = *val.value(); + + // Palette values are direct hex or rgba — not var() references + if (ColorVarResolver::parseHex(colorStr, color)) { + paletteMap[std::string(key.str())] = color; + } else if (ColorVarResolver::parseRgba(colorStr, color)) { + paletteMap[std::string(key.str())] = color; + } else if (colorStr == "transparent") { + paletteMap[std::string(key.str())] = IM_COL32(0, 0, 0, 0); + } else { + DEBUG_LOGF("[UISchema] Warning: unparseable palette color '%s': %s\n", + std::string(key.str()).c_str(), colorStr.c_str()); + } + } + colorResolver_.setPalette(paletteMap); + } + + // Parse elevation (optional) + if (auto* elevation = t["elevation"].as_table()) { + // Elevation colors go into the same palette + auto paletteMap = colorResolver_.palette(); + for (auto&& [key, val] : *elevation) { + if (!val.is_string()) continue; + ImU32 color = 0; + std::string colorStr = *val.value(); + if (ColorVarResolver::parseHex(colorStr, color)) { + paletteMap[std::string(key.str())] = color; + } + } + colorResolver_.setPalette(paletteMap); + } + + // Parse image overrides (resolved relative to theme directory by SkinManager) + if (auto* images = t["images"].as_table()) { + if (auto bg = (*images)["background_image"].value()) { + backgroundImagePath_ = *bg; + } + if (auto logo = (*images)["logo"].value()) { + logoImagePath_ = *logo; + } + } +} + +// ============================================================================ +// Globals parsing +// ============================================================================ + +void UISchema::parseGlobals(const void* dataObj) { + const toml::table& t = *static_cast(dataObj); + + if (auto* btn = t["button"].as_table()) { + detail::parseButtonStyle(static_cast(btn), globalButton_); + } + if (auto* inp = t["input"].as_table()) { + detail::parseInputStyle(static_cast(inp), globalInput_); + } + if (auto* lbl = t["label"].as_table()) { + detail::parseLabelStyle(static_cast(lbl), globalLabel_); + } + if (auto* tbl = t["table"].as_table()) { + detail::parseTableStyle(static_cast(tbl), globalTable_); + } + if (auto* cb = t["checkbox"].as_table()) { + detail::parseCheckboxStyle(static_cast(cb), globalCheckbox_); + } + if (auto* cmb = t["combo"].as_table()) { + detail::parseComboStyle(static_cast(cmb), globalCombo_); + } + if (auto* sld = t["slider"].as_table()) { + detail::parseSliderStyle(static_cast(sld), globalSlider_); + } + if (auto* win = t["window"].as_table()) { + detail::parseWindowStyle(static_cast(win), globalWindow_); + } + if (auto* sep = t["separator"].as_table()) { + detail::parseSeparatorStyle(static_cast(sep), globalSeparator_); + } +} + +// ============================================================================ +// Section parsing — store TOML tables for lazy access +// ============================================================================ + +void UISchema::parseSections(const void* dataObj, const std::string& prefix) { + const toml::table& t = *static_cast(dataObj); + + for (auto&& [sectionName, sectionNode] : t) { + auto* sectionTable = sectionNode.as_table(); + if (!sectionTable) continue; + + std::string sectionPath = prefix + "." + std::string(sectionName.str()); + + for (auto&& [elemName, elemNode] : *sectionTable) { + auto* elemTable = elemNode.as_table(); + if (!elemTable) continue; + + std::string key = sectionPath + "." + std::string(elemName.str()); + elements_[key] = StoredElement{ toml::table(*elemTable) }; + + // Recurse into nested sub-sections (3rd level) + // e.g., tabs.balance.classic.logo-opacity → stored as + // "tabs.balance.classic.logo-opacity" + for (auto&& [innerName, innerNode] : *elemTable) { + if (auto* innerTable = innerNode.as_table()) { + std::string innerKey = key + "." + std::string(innerName.str()); + elements_[innerKey] = StoredElement{ toml::table(*innerTable) }; + } + } + } + } +} + +void UISchema::parseFlatSection(const void* dataObj, const std::string& prefix) { + const toml::table& t = *static_cast(dataObj); + + for (auto&& [elemName, elemNode] : t) { + std::string key = prefix + "." + std::string(elemName.str()); + + if (auto* elemTable = elemNode.as_table()) { + // Check if this is a leaf element (values are primitives) + // or a nested sub-section (values are objects) + bool hasNestedObjects = false; + for (auto&& [innerName, innerNode] : *elemTable) { + if (innerNode.is_table()) { + hasNestedObjects = true; + break; + } + } + + if (hasNestedObjects) { + // Nested sub-section (e.g., inline-dialogs.about.{width,height,...}) + // Store each inner object as prefix.elemName.innerName + for (auto&& [innerName, innerNode] : *elemTable) { + if (auto* innerTable = innerNode.as_table()) { + std::string innerKey = key + "." + std::string(innerName.str()); + elements_[innerKey] = StoredElement{ toml::table(*innerTable) }; + } + } + // Also store the sub-section itself as a flat element + elements_[key] = StoredElement{ toml::table(*elemTable) }; + } else { + // Leaf element (e.g., business.block-reward: {"size": 1.5625}) + elements_[key] = StoredElement{ toml::table(*elemTable) }; + } + } else if (elemNode.is_integer() || elemNode.is_floating_point()) { + // Auto-wrap scalar number → {size = value} + toml::table wrapped; + wrapped.insert("size", elemNode.value().value_or(0.0)); + elements_[key] = StoredElement{ std::move(wrapped) }; + } else if (elemNode.is_string()) { + // Auto-wrap string → {font = value} or {color = value} + std::string s = *elemNode.value(); + toml::table wrapped; + if (s.find("var(") == 0 || s.find("#") == 0 || s.find("rgba") == 0) { + wrapped.insert("color", s); + } else { + wrapped.insert("font", s); + } + elements_[key] = StoredElement{ std::move(wrapped) }; + } else if (auto* arr = elemNode.as_array(); arr && arr->size() >= 2) { + // Auto-wrap [x, y] array → {width = x, height = y} + toml::table wrapped; + wrapped.insert("width", (*arr)[0].value().value_or(0.0)); + wrapped.insert("height", (*arr)[1].value().value_or(0.0)); + elements_[key] = StoredElement{ std::move(wrapped) }; + } + } +} + +// ============================================================================ +// Breakpoint parsing +// ============================================================================ + +void UISchema::parseBreakpoints(const void* jsonObj) { + detail::parseBreakpointConfig(jsonObj, breakpoints_); +} + +// ============================================================================ +// Element lookup — find stored TOML table by key +// ============================================================================ + +const void* UISchema::findElement(const std::string& section, const std::string& name) const { + std::string key = section + "." + name; + auto it = elements_.find(key); + if (it == elements_.end()) { + return nullptr; + } + // Return pointer to the stored toml::table via std::any_cast + return std::any_cast(&it->second.data); +} + +// ============================================================================ +// Hot-reload +// ============================================================================ + +void UISchema::pollForChanges() { + if (!loaded_ || currentPath_.empty()) return; + + double now = ImGui::GetTime(); + if (now - lastPollTime_ < pollInterval_) return; + lastPollTime_ = now; + + try { + auto mtime = std::filesystem::last_write_time(currentPath_); + if (mtime != lastModTime_) { + lastModTime_ = mtime; + dirty_ = true; + } + // Also check base file when an overlay is active + if (!dirty_ && !overlayPath_.empty() && !basePath_.empty() && basePath_ != currentPath_) { + auto btime = std::filesystem::last_write_time(basePath_); + if (btime != baseModTime_) { + baseModTime_ = btime; + dirty_ = true; + } + } + } catch (const std::filesystem::filesystem_error&) { + // File might be mid-write — ignore + } +} + +void UISchema::applyIfDirty() { + if (!dirty_) return; + dirty_ = false; + + // Snapshot font sizes before reload for change detection + static const char* fontKeys[] = { + "h1", "h2", "h3", "h4", "h5", "h6", + "subtitle1", "subtitle2", "body1", "body2", + "button", "button-sm", "button-lg", + "caption", "overline", "scale" + }; + float prevFonts[16]; + for (int i = 0; i < 16; ++i) { + prevFonts[i] = drawElement("fonts", fontKeys[i]).size; + } + + // Snapshot image paths before reload for change detection + std::string prevBgImage = backgroundImagePath_; + std::string prevLogoImage = logoImagePath_; + + DEBUG_LOGF("[UISchema] Hot-reload: re-parsing %s\n", currentPath_.c_str()); + + // If an overlay is active, reload base first then re-merge overlay + if (!overlayPath_.empty() && !basePath_.empty()) { + loadFromFile(basePath_); + mergeOverlayFromFile(overlayPath_); + } else { + loadFromFile(currentPath_); + } + + // Detect font size changes + for (int i = 0; i < 16; ++i) { + float cur = drawElement("fonts", fontKeys[i]).size; + if (cur != prevFonts[i]) { + fonts_changed_ = true; + DEBUG_LOGF("[UISchema] Font sizes changed, atlas rebuild needed\n"); + break; + } + } + + // Re-apply Material Design colors to ImGui from the reloaded palette + reapplyColorsToImGui(); + + // Detect image path changes and update SkinManager + trigger reload + if (backgroundImagePath_ != prevBgImage || logoImagePath_ != prevLogoImage) { + DEBUG_LOGF("[UISchema] Hot-reload: image paths changed (bg: '%s' → '%s', logo: '%s' → '%s')\n", + prevBgImage.c_str(), backgroundImagePath_.c_str(), + prevLogoImage.c_str(), logoImagePath_.c_str()); + + auto& skinMgr = SkinManager::instance(); + std::string activeId = skinMgr.activeSkinId(); + if (!activeId.empty()) { + // Re-resolve image paths from the new filenames + skinMgr.resolveAndReloadImages(activeId, currentPath_); + } + } +} + +// ============================================================================ +// Color resolution +// ============================================================================ + +ImU32 UISchema::resolveColor(const std::string& ref, ImU32 fallback) const { + return colorResolver_.resolve(ref, fallback); +} + +void UISchema::reapplyColorsToImGui() { + // Build a ColorTheme from the current palette + const auto& pal = colorResolver_.palette(); + + auto get = [&](const std::string& key, ImU32 fallback = 0) -> ImU32 { + auto it = pal.find(key); + return it != pal.end() ? it->second : fallback; + }; + + material::ColorTheme theme{}; + theme.primary = get("--primary"); + theme.primaryVariant = get("--primary-variant"); + theme.primaryLight = get("--primary-light"); + theme.secondary = get("--secondary"); + theme.secondaryVariant = get("--secondary-variant"); + theme.secondaryLight = get("--secondary-light"); + theme.background = get("--background"); + theme.surface = get("--surface"); + theme.surfaceVariant = get("--surface-variant"); + theme.onPrimary = get("--on-primary"); + theme.onSecondary = get("--on-secondary"); + theme.onBackground = get("--on-background"); + theme.onSurface = get("--on-surface"); + theme.onSurfaceMedium = get("--on-surface-medium"); + theme.onSurfaceDisabled= get("--on-surface-disabled"); + theme.error = get("--error"); + theme.onError = get("--on-error"); + theme.success = get("--success"); + theme.onSuccess = get("--on-success"); + theme.warning = get("--warning"); + theme.onWarning = get("--on-warning"); + theme.divider = get("--divider"); + theme.outline = get("--outline"); + theme.scrim = get("--scrim"); + + // Fill missing fields with defaults + ThemeLoader::computeDefaults(theme, darkTheme_); + + // Apply to ImGui and update acrylic theme + material::ApplyColorThemeToImGui(theme); + SetCurrentAcrylicTheme(ThemeLoader::deriveAcrylicTheme(theme)); + + // Background colors changed — re-capture on next frame + effects::ImGuiAcrylic::InvalidateCapture(); + + DEBUG_LOGF("[UISchema] Hot-reload: re-applied colors to ImGui\n"); +} + +// ============================================================================ +// Font resolution +// ============================================================================ + +ImFont* UISchema::resolveFont(const std::string& fontName) const { + if (fontName.empty()) return nullptr; + + auto& typo = material::Typography::instance(); + if (!typo.isLoaded()) return nullptr; + + // Match font name strings to Typography accessors + if (fontName == "h1") return typo.h1(); + if (fontName == "h2") return typo.h2(); + if (fontName == "h3") return typo.h3(); + if (fontName == "h4") return typo.h4(); + if (fontName == "h5") return typo.h5(); + if (fontName == "h6") return typo.h6(); + if (fontName == "subtitle1") return typo.subtitle1(); + if (fontName == "subtitle2") return typo.subtitle2(); + if (fontName == "body1") return typo.body1(); + if (fontName == "body2") return typo.body2(); + if (fontName == "button") return typo.button(); + if (fontName == "button-sm") return typo.buttonSm(); + if (fontName == "button-lg") return typo.buttonLg(); + if (fontName == "caption") return typo.caption(); + if (fontName == "overline") return typo.overline(); + + DEBUG_LOGF("[UISchema] Warning: unknown font name '%s'\n", fontName.c_str()); + return nullptr; +} + +// ============================================================================ +// Responsive breakpoint +// ============================================================================ + +Breakpoint UISchema::currentBreakpoint() const { + ImVec2 size = ImGui::GetMainViewport()->Size; + + // Check compact (must satisfy ALL specified constraints) + const auto& c = breakpoints_.compact; + bool isCompact = false; + if (c.maxWidth > 0 || c.maxHeight > 0) { + isCompact = true; + if (c.maxWidth > 0 && size.x > c.maxWidth) isCompact = false; + if (c.maxHeight > 0 && size.y > c.maxHeight) isCompact = false; + } + if (isCompact) return Breakpoint::Compact; + + // Check expanded + const auto& e = breakpoints_.expanded; + bool isExpanded = false; + if (e.minWidth > 0 || e.minHeight > 0) { + isExpanded = true; + if (e.minWidth > 0 && size.x < e.minWidth) isExpanded = false; + if (e.minHeight > 0 && size.y < e.minHeight) isExpanded = false; + } + if (isExpanded) return Breakpoint::Expanded; + + return Breakpoint::Normal; +} + +// ============================================================================ +// Element lookups with merge +// ============================================================================ + +ButtonStyle UISchema::button(const std::string& section, const std::string& name) const { + // Start with global defaults + ButtonStyle result = globalButton_; + + // Overlay section-specific values + const void* elem = findElement(section, name); + if (elem) { + ButtonStyle sectionStyle; + detail::parseButtonStyle(elem, sectionStyle); + mergeButton(result, sectionStyle); + + // Check for responsive overrides + const toml::table& t = *static_cast(elem); + Breakpoint bp = currentBreakpoint(); + if (bp == Breakpoint::Compact) { + if (auto* compactTable = t["@compact"].as_table()) { + ResponsiveButtonOverride ovr; + detail::parseResponsiveButtonOverride(static_cast(compactTable), ovr); + applyResponsiveButton(result, ovr); + } + } else if (bp == Breakpoint::Expanded) { + if (auto* expandedTable = t["@expanded"].as_table()) { + ResponsiveButtonOverride ovr; + detail::parseResponsiveButtonOverride(static_cast(expandedTable), ovr); + applyResponsiveButton(result, ovr); + } + } + } + + return result; +} + +InputStyle UISchema::input(const std::string& section, const std::string& name) const { + InputStyle result = globalInput_; + + const void* elem = findElement(section, name); + if (elem) { + InputStyle sectionStyle; + detail::parseInputStyle(elem, sectionStyle); + mergeInput(result, sectionStyle); + } + + return result; +} + +LabelStyle UISchema::label(const std::string& section, const std::string& name) const { + LabelStyle result = globalLabel_; + + const void* elem = findElement(section, name); + if (elem) { + LabelStyle sectionStyle; + detail::parseLabelStyle(elem, sectionStyle); + mergeLabel(result, sectionStyle); + } + + return result; +} + +TableStyle UISchema::table(const std::string& section, const std::string& name) const { + TableStyle result = globalTable_; + + const void* elem = findElement(section, name); + if (elem) { + TableStyle sectionStyle; + detail::parseTableStyle(elem, sectionStyle); + + // Merge table fields + if (sectionStyle.minHeight >= 0) result.minHeight = sectionStyle.minHeight; + if (sectionStyle.heightRatio >= 0) result.heightRatio = sectionStyle.heightRatio; + if (sectionStyle.bottomReserve >= 0) result.bottomReserve = sectionStyle.bottomReserve; + if (sectionStyle.rowHeight >= 0) result.rowHeight = sectionStyle.rowHeight; + if (!sectionStyle.headerFont.empty()) result.headerFont = sectionStyle.headerFont; + if (!sectionStyle.cellFont.empty()) result.cellFont = sectionStyle.cellFont; + if (!sectionStyle.borderColor.empty()) result.borderColor = sectionStyle.borderColor; + if (!sectionStyle.stripeColor.empty()) result.stripeColor = sectionStyle.stripeColor; + // Columns: section columns override/extend global columns + for (auto& [colName, colStyle] : sectionStyle.columns) { + result.columns[colName] = colStyle; + } + } + + return result; +} + +CheckboxStyle UISchema::checkbox(const std::string& section, const std::string& name) const { + CheckboxStyle result = globalCheckbox_; + + const void* elem = findElement(section, name); + if (elem) { + CheckboxStyle sectionStyle; + detail::parseCheckboxStyle(elem, sectionStyle); + if (!sectionStyle.font.empty()) result.font = sectionStyle.font; + if (!sectionStyle.color.empty()) result.color = sectionStyle.color; + if (!sectionStyle.checkColor.empty()) result.checkColor = sectionStyle.checkColor; + if (!sectionStyle.background.empty()) result.background = sectionStyle.background; + } + + return result; +} + +ComboStyle UISchema::combo(const std::string& section, const std::string& name) const { + ComboStyle result = globalCombo_; + + const void* elem = findElement(section, name); + if (elem) { + ComboStyle sectionStyle; + detail::parseComboStyle(elem, sectionStyle); + if (sectionStyle.width > 0) result.width = sectionStyle.width; + if (!sectionStyle.font.empty()) result.font = sectionStyle.font; + if (!sectionStyle.color.empty()) result.color = sectionStyle.color; + if (!sectionStyle.background.empty()) result.background = sectionStyle.background; + if (sectionStyle.borderRadius >= 0) result.borderRadius = sectionStyle.borderRadius; + if (sectionStyle.truncate > 0) result.truncate = sectionStyle.truncate; + } + + return result; +} + +SliderStyle UISchema::slider(const std::string& section, const std::string& name) const { + SliderStyle result = globalSlider_; + + const void* elem = findElement(section, name); + if (elem) { + SliderStyle sectionStyle; + detail::parseSliderStyle(elem, sectionStyle); + if (sectionStyle.width > 0) result.width = sectionStyle.width; + if (!sectionStyle.trackColor.empty()) result.trackColor = sectionStyle.trackColor; + if (!sectionStyle.fillColor.empty()) result.fillColor = sectionStyle.fillColor; + if (!sectionStyle.thumbColor.empty()) result.thumbColor = sectionStyle.thumbColor; + if (sectionStyle.thumbRadius >= 0) result.thumbRadius = sectionStyle.thumbRadius; + } + + return result; +} + +WindowStyle UISchema::window(const std::string& section, const std::string& name) const { + WindowStyle result = globalWindow_; + + const void* elem = findElement(section, name); + if (elem) { + WindowStyle sectionStyle; + detail::parseWindowStyle(elem, sectionStyle); + mergeWindow(result, sectionStyle); + } + + return result; +} + +SeparatorStyle UISchema::separator(const std::string& section, const std::string& name) const { + SeparatorStyle result = globalSeparator_; + + const void* elem = findElement(section, name); + if (elem) { + SeparatorStyle sectionStyle; + detail::parseSeparatorStyle(elem, sectionStyle); + if (!sectionStyle.color.empty()) result.color = sectionStyle.color; + if (sectionStyle.thickness >= 0) result.thickness = sectionStyle.thickness; + if (sectionStyle.margin[0] > 0 || sectionStyle.margin[1] > 0) { + result.margin[0] = sectionStyle.margin[0]; + result.margin[1] = sectionStyle.margin[1]; + } + } + + return result; +} + +DrawElementStyle UISchema::drawElement(const std::string& section, const std::string& name) const { + DrawElementStyle result; + + const void* elem = findElement(section, name); + if (elem) { + detail::parseDrawElementStyle(elem, result); + } + + return result; +} + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/schema/ui_schema.h b/src/ui/schema/ui_schema.h new file mode 100644 index 0000000..0831a7a --- /dev/null +++ b/src/ui/schema/ui_schema.h @@ -0,0 +1,375 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "color_var_resolver.h" +#include "element_styles.h" +#include "imgui.h" +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace schema { + +/** + * @brief Responsive breakpoint state + */ +enum class Breakpoint { + Compact, // Small window (e.g., < 500px wide) + Normal, // Default + Expanded // Large window (e.g., > 900px wide) +}; + +/** + * @brief Unified UI schema singleton + * + * Loads theme palette, globals, and per-section element styles from a single + * TOML file. Provides merged lookups (section → globals → fallback) and + * poll-based hot-reload. + * + * Usage: + * auto& UI = UISchema::instance(); + * UI.loadFromFile("res/themes/ui.toml"); + * + * // In main loop: + * UI.pollForChanges(); + * UI.applyIfDirty(); + * + * // Lookups: + * auto btn = UI.button("dialogs.about", "close-button"); + * auto win = UI.window("dialogs.about"); + * ImU32 col = UI.resolveColor("var(--primary)"); + */ +class UISchema { +public: + /** + * @brief Get the singleton instance + */ + static UISchema& instance(); + + /** + * @brief Load a unified skin file + * @param path Path to TOML skin file (e.g., "res/themes/ui.toml") + * @return true if loaded successfully + */ + bool loadFromFile(const std::string& path); + + /** + * @brief Load from a TOML string (e.g., embedded data fallback) + * @param tomlStr Raw TOML text + * @param label Human-readable label for log messages + * @return true if parsed successfully + */ + bool loadFromString(const std::string& tomlStr, const std::string& label = "embedded"); + + /** + * @brief Merge a theme overlay on top of the currently loaded base. + * + * Only replaces visual properties (theme palette/elevation/images and + * backdrop section). Layout values from the base are preserved. + * + * @param path Path to the overlay TOML (e.g., dark.toml, light.toml) + * @return true if overlay was parsed and merged successfully + */ + bool mergeOverlayFromFile(const std::string& path); + + /** + * @brief Check if a schema file has been loaded successfully + */ + bool isLoaded() const { return loaded_; } + + /** + * @brief Get the path of the currently loaded file + */ + const std::string& currentPath() const { return currentPath_; } + + /** + * @brief Get the base layout file path (ui.toml) + */ + const std::string& basePath() const { return basePath_; } + + /** + * @brief Check if the base theme was loaded from an embedded string. + * When true, reloadBase() uses the stored embedded data instead of a file. + */ + bool hasEmbeddedBase() const { return !embeddedTomlStr_.empty(); } + + /** + * @brief Reload the base theme (ui.toml) from file or embedded data. + * Used by SkinManager before merging an overlay to ensure layout values + * are always restored from the authoritative base, even on platforms + * where ui.toml is embedded (e.g., single-file Windows distribution). + * @return true if base was reloaded successfully + */ + bool reloadBase(); + + /** + * @brief Get the active overlay file path (empty if no overlay) + */ + const std::string& overlayPath() const { return overlayPath_; } + + // ==================================================================== + // Hot-reload + // ==================================================================== + + /** + * @brief Poll for file changes (call from main loop) + * + * Checks file modification time every pollInterval_ seconds. + * Sets dirty flag if file has changed. + */ + void pollForChanges(); + + /** + * @brief Check if the schema needs re-applying + */ + bool isDirty() const { return dirty_; } + + /** + * @brief Re-parse and apply if file has changed + */ + void applyIfDirty(); + + /** + * @brief Check and consume the fonts-changed flag. + * Returns true once after a hot-reload that changed font sizes. + */ + bool consumeFontsChanged() { + bool v = fonts_changed_; + fonts_changed_ = false; + return v; + } + + /** + * @brief Re-apply Material Design colors from schema palette to ImGui + * + * Builds a ColorTheme from the current palette and applies to ImGui style. + * Called automatically during hot-reload. + */ + void reapplyColorsToImGui(); + + /** + * @brief Set the poll interval in seconds (default 0.5) + */ + void setPollInterval(float seconds) { pollInterval_ = seconds; } + + // ==================================================================== + // Color resolution + // ==================================================================== + + /** + * @brief Get the color variable resolver (for direct access) + */ + const ColorVarResolver& colors() const { return colorResolver_; } + + /** + * @brief Resolve a color string to ImU32 + * @param ref Color string: "var(--primary)", "#hex", "rgba(...)", etc. + * @param fallback Value if resolution fails + */ + ImU32 resolveColor(const std::string& ref, ImU32 fallback = IM_COL32(0,0,0,0)) const; + + // ==================================================================== + // Font resolution + // ==================================================================== + + /** + * @brief Resolve a font name string to ImFont* + * @param fontName e.g., "button", "button-sm", "button-lg", "h4", "body1" + * @return ImFont* pointer, or nullptr if name is empty/unknown + */ + ImFont* resolveFont(const std::string& fontName) const; + + // ==================================================================== + // Responsive + // ==================================================================== + + /** + * @brief Get current breakpoint based on window/viewport size + */ + Breakpoint currentBreakpoint() const; + + /** + * @brief Get the breakpoint config + */ + const BreakpointConfig& breakpoints() const { return breakpoints_; } + + // ==================================================================== + // Element lookups — merged (section → globals → C++ default) + // ==================================================================== + + /** + * @brief Look up a button style + * @param section Dot-separated section path: "dialogs.about", "tabs.send" + * @param name Element name within the section: "close-button" + * @return Merged ButtonStyle (responsive overrides already applied) + */ + ButtonStyle button(const std::string& section, const std::string& name) const; + + /** + * @brief Look up an input style + */ + InputStyle input(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a label style + */ + LabelStyle label(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a table style + */ + TableStyle table(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a checkbox style + */ + CheckboxStyle checkbox(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a combo style + */ + ComboStyle combo(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a slider style + */ + SliderStyle slider(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a window/dialog style + * @param section Section path: "dialogs.about" + * @param name Defaults to "window" — the window block within that section + */ + WindowStyle window(const std::string& section, const std::string& name = "window") const; + + /** + * @brief Look up a separator style + */ + SeparatorStyle separator(const std::string& section, const std::string& name) const; + + /** + * @brief Look up a DrawList custom element style + */ + DrawElementStyle drawElement(const std::string& section, const std::string& name) const; + + /** + * @brief Find a raw stored element by section and name. + * Returns an opaque pointer to the stored data (toml::table* at runtime), + * or nullptr if not found. Consumer must cast via + * static_cast(ptr) after including . + */ + const void* findElement(const std::string& section, const std::string& name) const; + + // ==================================================================== + // Global defaults access + // ==================================================================== + + const ButtonStyle& defaultButton() const { return globalButton_; } + const InputStyle& defaultInput() const { return globalInput_; } + const LabelStyle& defaultLabel() const { return globalLabel_; } + const TableStyle& defaultTable() const { return globalTable_; } + const CheckboxStyle& defaultCheckbox() const { return globalCheckbox_; } + const ComboStyle& defaultCombo() const { return globalCombo_; } + const SliderStyle& defaultSlider() const { return globalSlider_; } + const WindowStyle& defaultWindow() const { return globalWindow_; } + const SeparatorStyle& defaultSeparator() const { return globalSeparator_; } + + // ==================================================================== + // Theme metadata + // ==================================================================== + + const std::string& themeName() const { return themeName_; } + bool isDarkTheme() const { return darkTheme_; } + + /** + * @brief Monotonically increasing generation counter. + * Incremented on every loadFromFile / mergeOverlay / applyIfDirty. + * Downstream caches compare against this to invalidate. + */ + uint32_t generation() const { return generation_; } + + /** + * @brief Get theme-specified background image path (empty = use default) + */ + const std::string& backgroundImagePath() const { return backgroundImagePath_; } + + /** + * @brief Get theme-specified logo image path (empty = use default) + */ + const std::string& logoImagePath() const { return logoImagePath_; } + +private: + UISchema() = default; + ~UISchema() = default; + UISchema(const UISchema&) = delete; + UISchema& operator=(const UISchema&) = delete; + + // Parse top-level sections from a TOML table (passed as opaque void*) + void parseTheme(const void* dataObj); + void parseGlobals(const void* dataObj); + void parseSections(const void* dataObj, const std::string& prefix); + void parseFlatSection(const void* dataObj, const std::string& prefix); + void parseBreakpoints(const void* dataObj); + + // ==================================================================== + // State + // ==================================================================== + + bool loaded_ = false; + std::string currentPath_; ///< Path currently loaded (base or overlay for hot-reload) + std::string basePath_; ///< Path to the base layout file (ui.toml) + std::string overlayPath_; ///< Path to active overlay file (empty if base-only) + std::string embeddedTomlStr_; ///< Raw TOML string from loadFromString (for reload) + + // Hot-reload + float pollInterval_ = 0.5f; + double lastPollTime_ = 0; + std::filesystem::file_time_type lastModTime_; + std::filesystem::file_time_type baseModTime_; ///< Track base file changes when overlay active + bool dirty_ = false; + bool fonts_changed_ = false; + + // Theme + std::string themeName_; + bool darkTheme_ = true; + std::string backgroundImagePath_; + std::string logoImagePath_; + ColorVarResolver colorResolver_; + uint32_t generation_ = 0; ///< bumped on every load/merge/reload + + // Breakpoints + BreakpointConfig breakpoints_; + + // Global defaults + ButtonStyle globalButton_; + InputStyle globalInput_; + LabelStyle globalLabel_; + TableStyle globalTable_; + CheckboxStyle globalCheckbox_; + ComboStyle globalCombo_; + SliderStyle globalSlider_; + WindowStyle globalWindow_; + SeparatorStyle globalSeparator_; + + // Per-section element storage + // Key: "section.elementName" → stored TOML table (accessed via std::any_cast) + // This avoids storing every possible style struct up front — + // we only parse what's actually looked up. + struct StoredElement { + std::any data; // holds toml::table at runtime + }; + std::unordered_map elements_; +}; + +// Convenience alias +inline UISchema& UI() { return UISchema::instance(); } + +} // namespace schema +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/confirmation_dialog.h b/src/ui/screens/confirmation_dialog.h new file mode 100644 index 0000000..a91f190 --- /dev/null +++ b/src/ui/screens/confirmation_dialog.h @@ -0,0 +1,352 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Confirmation Dialog +// ============================================================================ +// Material Design confirmation dialog for critical actions + +/** + * @brief Confirmation dialog type + */ +enum class ConfirmationType { + Info, + Warning, + Danger, + Transaction +}; + +/** + * @brief Transaction confirmation details + */ +struct TransactionConfirmation { + std::string toAddress; + double amount; + double fee; + std::string memo; + bool isShielded; +}; + +/** + * @brief Confirmation dialog manager + */ +class ConfirmationDialog { +public: + static ConfirmationDialog& instance() { + static ConfirmationDialog s_instance; + return s_instance; + } + + /** + * @brief Show a simple confirmation dialog + */ + void show(const std::string& title, + const std::string& message, + ConfirmationType type, + std::function callback) { + m_title = title; + m_message = message; + m_type = type; + m_callback = callback; + m_isOpen = true; + m_isTransaction = false; + } + + /** + * @brief Show transaction confirmation dialog + */ + void showTransaction(const TransactionConfirmation& tx, + std::function callback) { + m_title = "Confirm Transaction"; + m_type = ConfirmationType::Transaction; + m_transaction = tx; + m_callback = callback; + m_isOpen = true; + m_isTransaction = true; + } + + /** + * @brief Render the dialog (call every frame) + */ + void render(); + + /** + * @brief Check if dialog is currently open + */ + bool isOpen() const { return m_isOpen; } + +private: + ConfirmationDialog() = default; + + void renderSimpleDialog(); + void renderTransactionDialog(); + + std::string m_title; + std::string m_message; + ConfirmationType m_type = ConfirmationType::Info; + TransactionConfirmation m_transaction; + std::function m_callback; + bool m_isOpen = false; + bool m_isTransaction = false; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void ConfirmationDialog::render() { + if (!m_isOpen) return; + + if (m_isTransaction) { + renderTransactionDialog(); + } else { + renderSimpleDialog(); + } +} + +inline void ConfirmationDialog::renderSimpleDialog() { + DialogSpec dialogSpec; + dialogSpec.title = m_title.c_str(); + dialogSpec.maxWidth = 400.0f; + + DialogResult result = BeginDialog("confirm_dialog", dialogSpec); + + if (result.isOpen) { + // Icon based on type + ImGui::BeginGroup(); + { + ImVec4 iconColor; + const char* icon; + + switch (m_type) { + case ConfirmationType::Info: + iconColor = colors::Blue500; + icon = ICON_MD_INFO; + break; + case ConfirmationType::Warning: + iconColor = Secondary(); + icon = ICON_MD_WARNING; + break; + case ConfirmationType::Danger: + iconColor = Error(); + icon = ICON_MD_DANGEROUS; + break; + default: + iconColor = Primary(); + icon = ICON_MD_HELP; + break; + } + + Typography::instance().textColored(TypeStyle::H4, iconColor, icon); + ImGui::SameLine(); + + ImGui::BeginGroup(); + ImGui::TextWrapped("%s", m_message.c_str()); + ImGui::EndGroup(); + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Buttons + float availWidth = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - 200); + + if (TextButton("CANCEL")) { + m_isOpen = false; + if (m_callback) m_callback(false); + } + + ImGui::SameLine(0, spacing::dp(2)); + + // Confirm button color based on type + if (m_type == ConfirmationType::Danger) { + ImGui::PushStyleColor(ImGuiCol_Button, Error()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::Red400); + } + + if (ContainedButton("CONFIRM")) { + m_isOpen = false; + if (m_callback) m_callback(true); + } + + if (m_type == ConfirmationType::Danger) { + ImGui::PopStyleColor(2); + } + + EndDialog(); + } + + if (result.dismissed) { + m_isOpen = false; + if (m_callback) m_callback(false); + } +} + +inline void ConfirmationDialog::renderTransactionDialog() { + DialogSpec dialogSpec; + dialogSpec.title = "Confirm Transaction"; + dialogSpec.maxWidth = 500.0f; + + DialogResult result = BeginDialog("tx_confirm_dialog", dialogSpec); + + if (result.isOpen) { + // Transaction type badge + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filled; + + if (m_transaction.isShielded) { + chipSpec.color = Primary(); + Chip(ICON_MD_SHIELD " Shielded Transaction", chipSpec); + } else { + chipSpec.color = Secondary(); + Chip(ICON_MD_DESCRIPTION " Transparent Transaction", chipSpec); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Amount (large, prominent) + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "AMOUNT"); + char amountStr[64]; + snprintf(amountStr, sizeof(amountStr), "%.8f DRGX", m_transaction.amount); + Typography::instance().textColored(TypeStyle::H4, Primary(), amountStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Recipient + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TO ADDRESS"); + ImGui::TextWrapped("%s", m_transaction.toAddress.c_str()); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Fee + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NETWORK FEE"); + char feeStr[64]; + snprintf(feeStr, sizeof(feeStr), "%.8f DRGX", m_transaction.fee); + Typography::instance().text(TypeStyle::Body1, feeStr); + + // Memo if present + if (!m_transaction.memo.empty()) { + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MEMO (ENCRYPTED)"); + ImGui::TextWrapped("%s", m_transaction.memo.c_str()); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Total + ImVec2 divPos = ImGui::GetCursorScreenPos(); + float availWidth = ImGui::GetContentRegionAvail().x; + ImGui::GetWindowDrawList()->AddLine( + divPos, + ImVec2(divPos.x + availWidth, divPos.y), + ImGui::GetColorU32(Divider()) + ); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL"); + char totalStr[64]; + snprintf(totalStr, sizeof(totalStr), "%.8f DRGX", m_transaction.amount + m_transaction.fee); + Typography::instance().text(TypeStyle::H5, totalStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Warning for shielded transactions + if (m_transaction.isShielded) { + CardSpec warningCard; + warningCard.elevation = 0; + warningCard.padding = spacing::dp(2); + warningCard.outlined = true; + + ImGui::PushStyleColor(ImGuiCol_Border, colors::withAlpha(Secondary(), 0.5f)); + if (BeginCard(warningCard)) { + Typography::instance().textColored(TypeStyle::Body2, Secondary(), + ICON_MD_WARNING " Shielded transactions are private but take longer to process."); + EndCard(); + } + ImGui::PopStyleColor(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + } + + // Buttons + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - 220); + + if (OutlinedButton("CANCEL")) { + m_isOpen = false; + if (m_callback) m_callback(false); + } + + ImGui::SameLine(0, spacing::dp(2)); + + if (ContainedButton("SEND NOW")) { + m_isOpen = false; + if (m_callback) m_callback(true); + } + + EndDialog(); + } + + if (result.dismissed) { + m_isOpen = false; + if (m_callback) m_callback(false); + } +} + +// ============================================================================ +// Quick Confirmation Helpers +// ============================================================================ + +/** + * @brief Show a simple confirmation dialog + */ +inline void ShowConfirmation(const std::string& title, + const std::string& message, + std::function callback) { + ConfirmationDialog::instance().show(title, message, ConfirmationType::Info, callback); +} + +/** + * @brief Show a warning confirmation dialog + */ +inline void ShowWarningConfirmation(const std::string& title, + const std::string& message, + std::function callback) { + ConfirmationDialog::instance().show(title, message, ConfirmationType::Warning, callback); +} + +/** + * @brief Show a danger confirmation dialog + */ +inline void ShowDangerConfirmation(const std::string& title, + const std::string& message, + std::function callback) { + ConfirmationDialog::instance().show(title, message, ConfirmationType::Danger, callback); +} + +/** + * @brief Show a transaction confirmation dialog + */ +inline void ShowTransactionConfirmation(const TransactionConfirmation& tx, + std::function callback) { + ConfirmationDialog::instance().showTransaction(tx, callback); +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/home_screen.h b/src/ui/screens/home_screen.h new file mode 100644 index 0000000..2712152 --- /dev/null +++ b/src/ui/screens/home_screen.h @@ -0,0 +1,304 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Balance/Home Screen +// ============================================================================ +// Main dashboard showing wallet balances and recent activity + +/** + * @brief Balance information for display + */ +struct BalanceInfo { + double total = 0.0; + double shielded = 0.0; + double transparent = 0.0; + double pending = 0.0; + double fiatValue = 0.0; + std::string fiatCurrency = "USD"; +}; + +/** + * @brief Recent transaction summary + */ +struct RecentTransaction { + std::string txid; + std::string type; // "sent", "received", "mined" + std::string address; // Truncated address + double amount; + std::string time; // Relative time "2 hours ago" + bool confirmed; +}; + +/** + * @brief Render the home/balance screen + */ +class HomeScreen { +public: + void setBalance(const BalanceInfo& balance) { m_balance = balance; } + void setRecentTransactions(const std::vector& txns) { m_recentTxns = txns; } + void setOnSendClick(std::function callback) { m_onSendClick = callback; } + void setOnReceiveClick(std::function callback) { m_onReceiveClick = callback; } + void setOnTransactionClick(std::function callback) { m_onTxClick = callback; } + + void render(); + +private: + void renderBalanceCard(); + void renderQuickActions(); + void renderShieldedCard(); + void renderTransparentCard(); + void renderRecentTransactions(); + + BalanceInfo m_balance; + std::vector m_recentTxns; + std::function m_onSendClick; + std::function m_onReceiveClick; + std::function m_onTxClick; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void HomeScreen::render() { + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing::dp(2), spacing::dp(2))); + + // Two-column layout + float availWidth = ImGui::GetContentRegionAvail().x; + float cardWidth = (availWidth - spacing::dp(2)) * 0.5f; + + // Row 1: Total Balance + Recent Transactions + ImGui::BeginGroup(); + { + // Total Balance Card + ImGui::BeginGroup(); + renderBalanceCard(); + ImGui::EndGroup(); + + ImGui::SameLine(); + + // Recent Transactions Card + ImGui::BeginGroup(); + renderRecentTransactions(); + ImGui::EndGroup(); + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Row 2: Shielded + Transparent + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + renderShieldedCard(); + ImGui::EndGroup(); + + ImGui::SameLine(); + + ImGui::BeginGroup(); + renderTransparentCard(); + ImGui::EndGroup(); + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Quick Actions + renderQuickActions(); + + ImGui::PopStyleVar(); +} + +inline void HomeScreen::renderBalanceCard() { + float cardWidth = (ImGui::GetContentRegionAvail().x - spacing::dp(2)) * 0.5f; + + CardSpec spec; + spec.elevation = 2; + spec.padding = spacing::dp(3); + + ImGui::PushID("balance_card"); + if (BeginCard(spec)) { + // Overline + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL BALANCE"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Balance amount + char balanceStr[64]; + snprintf(balanceStr, sizeof(balanceStr), "%.8f", m_balance.total); + Typography::instance().text(TypeStyle::H4, balanceStr); + + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::H6, OnSurfaceMedium(), "DRGX"); + + // Fiat value + if (m_balance.fiatValue > 0) { + ImGui::Dummy(ImVec2(0, spacing::dp(0.5f))); + char fiatStr[64]; + snprintf(fiatStr, sizeof(fiatStr), "≈ $%.2f %s", m_balance.fiatValue, m_balance.fiatCurrency.c_str()); + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), fiatStr); + } + + // Pending indicator + if (m_balance.pending > 0) { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + char pendingStr[64]; + snprintf(pendingStr, sizeof(pendingStr), ICON_MD_HOURGLASS_EMPTY " %.8f pending", m_balance.pending); + Typography::instance().textColored(TypeStyle::Caption, Secondary(), pendingStr); + } + + EndCard(); + } + ImGui::PopID(); +} + +inline void HomeScreen::renderQuickActions() { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + float buttonWidth = 120.0f; + float availWidth = ImGui::GetContentRegionAvail().x; + float startX = (availWidth - buttonWidth * 2 - spacing::dp(2)) * 0.5f; + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + startX); + + if (ContainedButton(ICON_MD_CALL_MADE " SEND")) { + if (m_onSendClick) m_onSendClick(); + } + + ImGui::SameLine(0, spacing::dp(2)); + + if (OutlinedButton(ICON_MD_CALL_RECEIVED " RECEIVE")) { + if (m_onReceiveClick) m_onReceiveClick(); + } +} + +inline void HomeScreen::renderShieldedCard() { + CardSpec spec; + spec.elevation = 1; + spec.padding = spacing::dp(2); + + ImGui::PushID("shielded_card"); + if (BeginCard(spec)) { + // Icon and label + ImGui::BeginGroup(); + Typography::instance().textColored(TypeStyle::Body2, Primary(), ICON_MD_SHIELD); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SHIELDED (PRIVATE)"); + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Amount + char amountStr[64]; + snprintf(amountStr, sizeof(amountStr), "%.8f", m_balance.shielded); + Typography::instance().text(TypeStyle::H5, amountStr); + + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "DRGX"); + + EndCard(); + } + ImGui::PopID(); +} + +inline void HomeScreen::renderTransparentCard() { + CardSpec spec; + spec.elevation = 1; + spec.padding = spacing::dp(2); + + ImGui::PushID("transparent_card"); + if (BeginCard(spec)) { + // Icon and label + ImGui::BeginGroup(); + Typography::instance().textColored(TypeStyle::Body2, Secondary(), ICON_MD_CONTENT_COPY); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TRANSPARENT"); + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Amount + char amountStr[64]; + snprintf(amountStr, sizeof(amountStr), "%.8f", m_balance.transparent); + Typography::instance().text(TypeStyle::H5, amountStr); + + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "DRGX"); + + EndCard(); + } + ImGui::PopID(); +} + +inline void HomeScreen::renderRecentTransactions() { + CardSpec spec; + spec.elevation = 1; + spec.padding = spacing::dp(2); + + ImGui::PushID("recent_txns"); + if (BeginCard(spec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT TRANSACTIONS"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + if (m_recentTxns.empty()) { + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), "No recent transactions"); + } else { + BeginList("recent_list", false); + + int count = 0; + for (const auto& tx : m_recentTxns) { + if (count >= 5) break; // Show max 5 + + ListItemSpec itemSpec; + + // Icon based on type + if (tx.type == "received") { + itemSpec.leadingIcon = ICON_MD_CALL_RECEIVED; + } else if (tx.type == "sent") { + itemSpec.leadingIcon = ICON_MD_CALL_MADE; + } else { + itemSpec.leadingIcon = ICON_MD_CONSTRUCTION; + } + + // Amount as primary text + char amountStr[32]; + snprintf(amountStr, sizeof(amountStr), "%+.4f DRGX", + tx.type == "sent" ? -tx.amount : tx.amount); + itemSpec.primaryText = amountStr; + itemSpec.secondaryText = tx.time.c_str(); + itemSpec.dividerBelow = (count < 4 && count < (int)m_recentTxns.size() - 1); + + if (ListItem(itemSpec)) { + if (m_onTxClick) m_onTxClick(tx.txid); + } + + count++; + } + + EndList(); + } + + EndCard(); + } + ImGui::PopID(); +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/main_layout.h b/src/ui/screens/main_layout.h new file mode 100644 index 0000000..c8045b1 --- /dev/null +++ b/src/ui/screens/main_layout.h @@ -0,0 +1,553 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "../schema/ui_schema.h" +#include "home_screen.h" +#include "send_screen.h" +#include "receive_screen.h" +#include "transactions_screen.h" +#include "mining_screen.h" +#include "peers_screen.h" +#include "settings_screen.h" +#include "imgui.h" +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Main Application Layout +// ============================================================================ +// Combines app bar, navigation drawer, content area, and status bar + +/** + * @brief Navigation destinations + */ +enum class NavDestination { + Home, + Send, + Receive, + Transactions, + Mining, + Peers, + Settings +}; + +/** + * @brief Connection status for status bar + */ +struct ConnectionStatus { + bool connected = false; + int blockHeight = 0; + int peers = 0; + double networkHashrate = 0.0; + bool syncing = false; + float syncProgress = 0.0f; + std::string statusMessage; +}; + +/** + * @brief Main application layout with Material Design structure + */ +class MainLayout { +public: + MainLayout() = default; + + void setConnectionStatus(const ConnectionStatus& status) { m_status = status; } + + void setOnNavigation(std::function callback) { + m_onNavigation = callback; + } + + void setOnSearch(std::function callback) { + m_onSearch = callback; + } + + void setOnSettingsClick(std::function callback) { + m_onSettingsClick = callback; + } + + void navigateTo(NavDestination dest) { + m_currentDestination = dest; + m_drawerOpen = false; // Close drawer on navigation + } + + NavDestination getCurrentDestination() const { return m_currentDestination; } + + // Screen access + HomeScreen& homeScreen() { return m_homeScreen; } + SendScreen& sendScreen() { return m_sendScreen; } + ReceiveScreen& receiveScreen() { return m_receiveScreen; } + TransactionsScreen& transactionsScreen() { return m_transactionsScreen; } + MiningScreen& miningScreen() { return m_miningScreen; } + PeersScreen& peersScreen() { return m_peersScreen; } + SettingsScreen& settingsScreen() { return m_settingsScreen; } + + void render(); + +private: + void renderAppBar(); + void renderNavigationDrawer(); + void renderContent(); + void renderStatusBar(); + void renderSearchOverlay(); + + NavDestination m_currentDestination = NavDestination::Home; + ConnectionStatus m_status; + + std::function m_onNavigation; + std::function m_onSearch; + std::function m_onSettingsClick; + + // Navigation drawer state + bool m_drawerOpen = false; + AnimatedValue m_drawerAnimation{0.0f}; + + // Search state + bool m_searchOpen = false; + char m_searchBuffer[256] = {0}; + + // Screens + HomeScreen m_homeScreen; + SendScreen m_sendScreen; + ReceiveScreen m_receiveScreen; + TransactionsScreen m_transactionsScreen; + MiningScreen m_miningScreen; + PeersScreen m_peersScreen; + SettingsScreen m_settingsScreen; + + // Layout values — read from ui.toml schema at runtime + static float APP_BAR_HEIGHT; + static float STATUS_BAR_HEIGHT; + static float DRAWER_WIDTH; + + static void initLayoutConstants() { + APP_BAR_HEIGHT = schema::UI().drawElement("components.main-layout", "app-bar-height").size; + STATUS_BAR_HEIGHT = schema::UI().drawElement("components.main-layout", "status-bar-height").size; + DRAWER_WIDTH = schema::UI().drawElement("components.main-layout", "drawer-width").size; + if (APP_BAR_HEIGHT <= 0) APP_BAR_HEIGHT = 64.0f; + if (STATUS_BAR_HEIGHT <= 0) STATUS_BAR_HEIGHT = 32.0f; + if (DRAWER_WIDTH <= 0) DRAWER_WIDTH = 256.0f; + } +}; + +// Static member definitions +inline float MainLayout::APP_BAR_HEIGHT = 64.0f; +inline float MainLayout::STATUS_BAR_HEIGHT = 32.0f; +inline float MainLayout::DRAWER_WIDTH = 256.0f; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void MainLayout::render() { + static bool layoutInitialized = false; + if (!layoutInitialized) { + initLayoutConstants(); + layoutInitialized = true; + } + + ImGuiIO& io = ImGui::GetIO(); + float windowWidth = io.DisplaySize.x; + float windowHeight = io.DisplaySize.y; + + // Full-screen window + ImGui::SetNextWindowPos(ImVec2(0, 0)); + ImGui::SetNextWindowSize(ImVec2(windowWidth, windowHeight)); + + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleColor(ImGuiCol_WindowBg, Background()); + + if (ImGui::Begin("MainLayout", nullptr, windowFlags)) { + // App bar + renderAppBar(); + + // Content area with optional drawer + float contentY = APP_BAR_HEIGHT; + float contentHeight = windowHeight - APP_BAR_HEIGHT - STATUS_BAR_HEIGHT; + + // Update drawer animation + float targetDrawer = m_drawerOpen ? 1.0f : 0.0f; + m_drawerAnimation.animateTo(targetDrawer, duration::Medium); + m_drawerAnimation.update(io.DeltaTime); + float drawerProgress = m_drawerAnimation.value(); + + // Navigation drawer (slides in from left) + if (drawerProgress > 0.01f) { + renderNavigationDrawer(); + } + + // Content offset based on drawer + float contentX = drawerProgress * DRAWER_WIDTH; + + // Content area + ImGui::SetCursorPos(ImVec2(contentX, contentY)); + ImGui::BeginChild("Content", ImVec2(windowWidth - contentX, contentHeight), false, + ImGuiWindowFlags_NoScrollbar); + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(spacing::dp(3), spacing::dp(3))); + renderContent(); + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + + // Status bar + ImGui::SetCursorPos(ImVec2(0, windowHeight - STATUS_BAR_HEIGHT)); + renderStatusBar(); + + // Search overlay + if (m_searchOpen) { + renderSearchOverlay(); + } + + // Click outside drawer to close + if (m_drawerOpen && ImGui::IsMouseClicked(0)) { + ImVec2 mousePos = ImGui::GetMousePos(); + if (mousePos.x > DRAWER_WIDTH) { + m_drawerOpen = false; + } + } + } + ImGui::End(); + + ImGui::PopStyleColor(); + ImGui::PopStyleVar(2); +} + +inline void MainLayout::renderAppBar() { + ImGuiIO& io = ImGui::GetIO(); + float windowWidth = io.DisplaySize.x; + + // App bar background + ImVec2 appBarPos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled( + appBarPos, + ImVec2(appBarPos.x + windowWidth, appBarPos.y + APP_BAR_HEIGHT), + ImGui::GetColorU32(Surface()) + ); + + // Elevation shadow + DrawShadow(ImVec2(appBarPos.x, appBarPos.y + APP_BAR_HEIGHT - 4), + ImVec2(windowWidth, 4), 4); + + ImGui::SetCursorPos(ImVec2(spacing::dp(1), (APP_BAR_HEIGHT - schema::UI().drawElement("components.main-layout", "app-bar-button-size").size) / 2)); + + // Menu button + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(OnSurface(), 0.08f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("components.main-layout", "app-bar-btn-rounding").size); + + float appBarBtnSz = schema::UI().drawElement("components.main-layout", "app-bar-button-size").size; + if (ImGui::Button(ICON_MD_MENU, ImVec2(appBarBtnSz, appBarBtnSz))) { + m_drawerOpen = !m_drawerOpen; + } + + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); + + // Title + ImGui::SameLine(0, spacing::dp(2)); + ImGui::SetCursorPosY((APP_BAR_HEIGHT - schema::UI().drawElement("components.main-layout", "title-font-height").size) / 2); + Typography::instance().text(TypeStyle::H6, "DragonX Wallet"); + + // Right actions + float rightOffset = windowWidth - spacing::dp(1) - appBarBtnSz; + + // Settings button + ImGui::SameLine(rightOffset); + ImGui::SetCursorPosY((APP_BAR_HEIGHT - appBarBtnSz) / 2); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(OnSurface(), 0.08f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("components.main-layout", "app-bar-btn-rounding").size); + + if (ImGui::Button(ICON_MD_SETTINGS, ImVec2(appBarBtnSz, appBarBtnSz))) { + navigateTo(NavDestination::Settings); + } + + // Search button + ImGui::SameLine(rightOffset - 48); + ImGui::SetCursorPosY((APP_BAR_HEIGHT - appBarBtnSz) / 2); + + if (ImGui::Button(ICON_MD_SEARCH, ImVec2(appBarBtnSz, appBarBtnSz))) { + m_searchOpen = !m_searchOpen; + } + + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); +} + +inline void MainLayout::renderNavigationDrawer() { + ImGuiIO& io = ImGui::GetIO(); + float windowHeight = io.DisplaySize.y; + float drawerProgress = m_drawerAnimation.value(); + + // Scrim (semi-transparent overlay) + if (drawerProgress > 0.01f) { + ImVec2 scrimStart = ImVec2(DRAWER_WIDTH, APP_BAR_HEIGHT); + ImVec2 scrimEnd = ImVec2(io.DisplaySize.x, windowHeight - STATUS_BAR_HEIGHT); + + ImGui::GetWindowDrawList()->AddRectFilled( + scrimStart, scrimEnd, + ImGui::GetColorU32(ImVec4(0, 0, 0, 0.5f * drawerProgress)) + ); + } + + // Drawer background + float drawerX = (drawerProgress - 1.0f) * DRAWER_WIDTH; + ImVec2 drawerStart = ImVec2(0, APP_BAR_HEIGHT); + ImVec2 drawerEnd = ImVec2(DRAWER_WIDTH, windowHeight - STATUS_BAR_HEIGHT); + + ImGui::SetCursorPos(ImVec2(drawerX, APP_BAR_HEIGHT)); + ImGui::BeginChild("NavDrawer", ImVec2(DRAWER_WIDTH, windowHeight - APP_BAR_HEIGHT - STATUS_BAR_HEIGHT), + false, ImGuiWindowFlags_NoScrollbar); + { + // Drawer surface + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled( + pos, + ImVec2(pos.x + DRAWER_WIDTH, pos.y + windowHeight), + ImGui::GetColorU32(Surface()) + ); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Navigation items + auto navItem = [this](const char* icon, const char* label, NavDestination dest) { + bool selected = (m_currentDestination == dest); + + NavItemSpec spec; + spec.icon = icon; + spec.label = label; + spec.selected = selected; + + if (NavItem(spec)) { + navigateTo(dest); + if (m_onNavigation) m_onNavigation(dest); + } + }; + + navItem(ICON_MD_HOME, "Home", NavDestination::Home); + navItem(ICON_MD_CALL_MADE, "Send", NavDestination::Send); + navItem(ICON_MD_CALL_RECEIVED, "Receive", NavDestination::Receive); + navItem(ICON_MD_RECEIPT, "Transactions", NavDestination::Transactions); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Divider + ImVec2 divStart = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddLine( + ImVec2(divStart.x + spacing::dp(2), divStart.y), + ImVec2(divStart.x + DRAWER_WIDTH - spacing::dp(2), divStart.y), + ImGui::GetColorU32(Divider()) + ); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + navItem(ICON_MD_CONSTRUCTION, "Mining", NavDestination::Mining); + navItem(ICON_MD_HUB, "Network", NavDestination::Peers); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Another divider + divStart = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddLine( + ImVec2(divStart.x + spacing::dp(2), divStart.y), + ImVec2(divStart.x + DRAWER_WIDTH - spacing::dp(2), divStart.y), + ImGui::GetColorU32(Divider()) + ); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + navItem(ICON_MD_SETTINGS, "Settings", NavDestination::Settings); + } + ImGui::EndChild(); +} + +inline void MainLayout::renderContent() { + // Padding + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + switch (m_currentDestination) { + case NavDestination::Home: + m_homeScreen.render(); + break; + case NavDestination::Send: + m_sendScreen.render(); + break; + case NavDestination::Receive: + m_receiveScreen.render(); + break; + case NavDestination::Transactions: + m_transactionsScreen.render(); + break; + case NavDestination::Mining: + m_miningScreen.render(); + break; + case NavDestination::Peers: + m_peersScreen.render(); + break; + case NavDestination::Settings: + m_settingsScreen.render(); + break; + } +} + +inline void MainLayout::renderStatusBar() { + ImGuiIO& io = ImGui::GetIO(); + float windowWidth = io.DisplaySize.x; + + // Status bar background + ImVec2 statusPos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled( + statusPos, + ImVec2(statusPos.x + windowWidth, statusPos.y + STATUS_BAR_HEIGHT), + ImGui::GetColorU32(SurfaceVariant()) + ); + + // Top border + ImGui::GetWindowDrawList()->AddLine( + statusPos, + ImVec2(statusPos.x + windowWidth, statusPos.y), + ImGui::GetColorU32(Divider()) + ); + + ImGui::SetCursorPos(ImVec2(spacing::dp(2), ImGui::GetCursorPosY() + 6)); + + // Connection status + if (m_status.connected) { + Typography::instance().textColored(TypeStyle::Caption, colors::Green500, ICON_MD_FIBER_MANUAL_RECORD " Connected"); + } else { + Typography::instance().textColored(TypeStyle::Caption, colors::Red500, ICON_MD_FIBER_MANUAL_RECORD " Disconnected"); + } + + ImGui::SameLine(0, spacing::dp(3)); + + // Block height + char heightStr[64]; + snprintf(heightStr, sizeof(heightStr), "Block: %d", m_status.blockHeight); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), heightStr); + + ImGui::SameLine(0, spacing::dp(3)); + + // Peer count + char peerStr[32]; + snprintf(peerStr, sizeof(peerStr), "Peers: %d", m_status.peers); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), peerStr); + + // Sync progress (if syncing) + if (m_status.syncing) { + ImGui::SameLine(0, spacing::dp(3)); + + // Mini progress bar + ImVec2 progressPos = ImGui::GetCursorScreenPos(); + float progressWidth = schema::UI().drawElement("components.main-layout", "sync-bar-width").size; + float progressHeight = schema::UI().drawElement("components.main-layout", "sync-bar-height").size; + + progressPos.y += 6; + + // Background + ImGui::GetWindowDrawList()->AddRectFilled( + progressPos, + ImVec2(progressPos.x + progressWidth, progressPos.y + progressHeight), + ImGui::GetColorU32(Divider()), + 2.0f + ); + + // Progress + ImGui::GetWindowDrawList()->AddRectFilled( + progressPos, + ImVec2(progressPos.x + progressWidth * m_status.syncProgress, progressPos.y + progressHeight), + ImGui::GetColorU32(Primary()), + 2.0f + ); + + ImGui::Dummy(ImVec2(progressWidth, 0)); + ImGui::SameLine(); + + char syncStr[32]; + snprintf(syncStr, sizeof(syncStr), "%.1f%%", m_status.syncProgress * 100.0f); + ImU32 syncTextColor = IsDarkTheme() ? Primary() : PrimaryVariant(); + Typography::instance().textColored(TypeStyle::Caption, syncTextColor, syncStr); + } + + // Network hashrate (right aligned) + if (m_status.networkHashrate > 0) { + char hashrateStr[64]; + if (m_status.networkHashrate > 1e9) { + snprintf(hashrateStr, sizeof(hashrateStr), "Network: %.2f GH/s", + m_status.networkHashrate / 1e9); + } else if (m_status.networkHashrate > 1e6) { + snprintf(hashrateStr, sizeof(hashrateStr), "Network: %.2f MH/s", + m_status.networkHashrate / 1e6); + } else { + snprintf(hashrateStr, sizeof(hashrateStr), "Network: %.2f KH/s", + m_status.networkHashrate / 1e3); + } + + ImVec2 textSize = ImGui::CalcTextSize(hashrateStr); + ImGui::SameLine(windowWidth - textSize.x - spacing::dp(2)); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), hashrateStr); + } +} + +inline void MainLayout::renderSearchOverlay() { + ImGuiIO& io = ImGui::GetIO(); + float windowWidth = io.DisplaySize.x; + + // Search bar at top (below app bar) + ImGui::SetCursorPos(ImVec2(0, APP_BAR_HEIGHT)); + + CardSpec cardSpec; + cardSpec.elevation = 8; + cardSpec.padding = spacing::dp(2); + cardSpec.width = windowWidth; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(spacing::dp(2), spacing::dp(2))); + + if (BeginCard(cardSpec)) { + ImGui::SetNextItemWidth(windowWidth - spacing::dp(8)); + + TextFieldSpec textSpec; + textSpec.placeholder = "Search transactions, addresses..."; + textSpec.variant = TextFieldVariant::Filled; + textSpec.leadingIcon = ICON_MD_SEARCH; + textSpec.width = windowWidth - spacing::dp(12); + + TextFieldResult result = TextField("global_search", m_searchBuffer, + sizeof(m_searchBuffer), textSpec); + + if (result.submitted && strlen(m_searchBuffer) > 0) { + if (m_onSearch) m_onSearch(m_searchBuffer); + m_searchOpen = false; + } + + // Close on escape + if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { + m_searchOpen = false; + memset(m_searchBuffer, 0, sizeof(m_searchBuffer)); + } + + EndCard(); + } + + ImGui::PopStyleVar(); +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/mining_screen.h b/src/ui/screens/mining_screen.h new file mode 100644 index 0000000..a9b8b65 --- /dev/null +++ b/src/ui/screens/mining_screen.h @@ -0,0 +1,371 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Mining Screen +// ============================================================================ +// Mining controls and statistics display + +/** + * @brief Mining statistics + */ +struct MiningStats { + bool isMining = false; + int threads = 0; + int maxThreads = 8; + double hashrate = 0.0; // Hashes per second + double networkHashrate = 0.0; // Network hashrate + int blocksFound = 0; + double totalMined = 0.0; + std::string miningAddress; + int currentHeight = 0; + double networkDifficulty = 0.0; + std::string estimatedTimeToBlock; +}; + +/** + * @brief Recent mined block + */ +struct MinedBlock { + int height; + double reward; + std::string time; + std::string txid; +}; + +/** + * @brief Mining screen with controls and stats + */ +class MiningScreen { +public: + void setStats(const MiningStats& stats) { m_stats = stats; } + void setMinedBlocks(const std::vector& blocks) { m_minedBlocks = blocks; } + + void setOnStartMining(std::function callback) { + m_onStartMining = callback; + } + void setOnStopMining(std::function callback) { + m_onStopMining = callback; + } + void setOnSetAddress(std::function callback) { + m_onSetAddress = callback; + } + + void render(); + +private: + void renderMiningControls(); + void renderStatsCards(); + void renderMinedBlocksList(); + + MiningStats m_stats; + std::vector m_minedBlocks; + + std::function m_onStartMining; + std::function m_onStopMining; + std::function m_onSetAddress; + + int m_selectedThreads = 4; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void MiningScreen::render() { + // Title + ImGui::BeginGroup(); + { + Typography::instance().text(TypeStyle::H5, "Mining"); + + ImGui::SameLine(); + + // Mining status indicator + if (m_stats.isMining) { + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filled; + chipSpec.color = colors::Green500; + Chip(ICON_MD_HARDWARE " Mining Active", chipSpec); + } + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Mining controls card + renderMiningControls(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Stats cards row + renderStatsCards(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Mined blocks history + renderMinedBlocksList(); +} + +inline void MiningScreen::renderMiningControls() { + CardSpec cardSpec; + cardSpec.elevation = 2; + cardSpec.padding = spacing::dp(3); + + ImGui::PushID("mining_controls"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MINING CONTROLS"); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Thread selector + ImGui::BeginGroup(); + { + Typography::instance().text(TypeStyle::Body1, "Mining Threads:"); + ImGui::SameLine(); + + ImGui::SetNextItemWidth(150.0f); + ImGui::SliderInt("##threads", &m_selectedThreads, 1, m_stats.maxThreads); + + ImGui::SameLine(); + + char threadInfo[64]; + snprintf(threadInfo, sizeof(threadInfo), "(%d available)", m_stats.maxThreads); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), threadInfo); + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Mining address display + if (!m_stats.miningAddress.empty()) { + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), "Mining to:"); + + std::string displayAddr = m_stats.miningAddress; + if (displayAddr.length() > 50) { + displayAddr = displayAddr.substr(0, 25) + "..." + + displayAddr.substr(displayAddr.length() - 20); + } + Typography::instance().text(TypeStyle::Body2, displayAddr.c_str()); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Start/Stop buttons + if (m_stats.isMining) { + // Stop button (red) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(colors::Red700.x, colors::Red700.y, colors::Red700.z, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(colors::Red500.x, colors::Red500.y, colors::Red500.z, 1.0f)); + + if (ImGui::Button("⏹ STOP MINING", ImVec2(150, 40))) { + if (m_onStopMining) m_onStopMining(); + } + + ImGui::PopStyleColor(2); + + ImGui::SameLine(); + + // Live hashrate display + char hashrateStr[64]; + if (m_stats.hashrate > 1000000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f MH/s", m_stats.hashrate / 1000000.0); + } else if (m_stats.hashrate > 1000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f KH/s", m_stats.hashrate / 1000.0); + } else { + snprintf(hashrateStr, sizeof(hashrateStr), "%.0f H/s", m_stats.hashrate); + } + + Typography::instance().textColored(TypeStyle::H6, Primary(), hashrateStr); + } else { + // Start button (green) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(colors::Green700.x, colors::Green700.y, colors::Green700.z, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(colors::Green500.x, colors::Green500.y, colors::Green500.z, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1)); + + if (ImGui::Button(ICON_MD_PLAY_ARROW " START MINING", ImVec2(150, 40))) { + if (m_onStartMining) m_onStartMining(m_selectedThreads); + } + + ImGui::PopStyleColor(3); + } + + EndCard(); + } + ImGui::PopID(); +} + +inline void MiningScreen::renderStatsCards() { + float availWidth = ImGui::GetContentRegionAvail().x; + float cardWidth = (availWidth - spacing::dp(2) * 2) / 3.0f; + + // Hashrate card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("hashrate_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "YOUR HASHRATE"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char hashrateStr[64]; + if (m_stats.hashrate > 1000000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f", m_stats.hashrate / 1000000.0); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "MH/s"); + } else if (m_stats.hashrate > 1000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f", m_stats.hashrate / 1000.0); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "KH/s"); + } else { + snprintf(hashrateStr, sizeof(hashrateStr), "%.0f", m_stats.hashrate); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "H/s"); + } + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Network hashrate card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("network_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NETWORK HASHRATE"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char hashrateStr[64]; + if (m_stats.networkHashrate > 1000000000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f", m_stats.networkHashrate / 1000000000.0); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "GH/s"); + } else if (m_stats.networkHashrate > 1000000) { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f", m_stats.networkHashrate / 1000000.0); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "MH/s"); + } else { + snprintf(hashrateStr, sizeof(hashrateStr), "%.2f", m_stats.networkHashrate / 1000.0); + Typography::instance().text(TypeStyle::H4, hashrateStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "KH/s"); + } + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Total mined card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("mined_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL MINED"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char minedStr[64]; + snprintf(minedStr, sizeof(minedStr), "%.4f", m_stats.totalMined); + Typography::instance().text(TypeStyle::H4, minedStr); + ImGui::SameLine(); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "DRGX"); + + ImGui::Dummy(ImVec2(0, spacing::dp(0.5f))); + + char blocksStr[32]; + snprintf(blocksStr, sizeof(blocksStr), "%d blocks found", m_stats.blocksFound); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), blocksStr); + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); +} + +inline void MiningScreen::renderMinedBlocksList() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + + ImGui::PushID("mined_blocks"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "BLOCKS YOU MINED"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + if (m_minedBlocks.empty()) { + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), + "No blocks mined yet. Keep mining!"); + } else { + BeginList("mined_list", false); + + for (size_t i = 0; i < m_minedBlocks.size() && i < 10; i++) { + const auto& block = m_minedBlocks[i]; + + ListItemSpec itemSpec; + itemSpec.leadingIcon = "🏆"; + + char primaryStr[64]; + snprintf(primaryStr, sizeof(primaryStr), "Block #%d", block.height); + itemSpec.primaryText = primaryStr; + + char secondaryStr[64]; + snprintf(secondaryStr, sizeof(secondaryStr), "+%.4f DRGX • %s", + block.reward, block.time.c_str()); + itemSpec.secondaryText = secondaryStr; + + itemSpec.dividerBelow = (i < m_minedBlocks.size() - 1 && i < 9); + + ListItem(itemSpec); + } + + EndList(); + } + + EndCard(); + } + ImGui::PopID(); +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/peers_screen.h b/src/ui/screens/peers_screen.h new file mode 100644 index 0000000..706e7aa --- /dev/null +++ b/src/ui/screens/peers_screen.h @@ -0,0 +1,462 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Peers Screen +// ============================================================================ +// Display connected peers with Material list + +/** + * @brief Peer connection info + */ +struct PeerInfo { + int id; + std::string address; + std::string subversion; + int startingHeight; + int currentHeight; + int latency; // ms + int64_t bytesSent; + int64_t bytesReceived; + std::string connTime; // Connection duration + bool isInbound; +}; + +/** + * @brief Network statistics + */ +struct NetworkStats { + int totalConnections; + int inboundCount; + int outboundCount; + int64_t totalBytesSent; + int64_t totalBytesReceived; + int currentHeight; + std::string networkName; +}; + +/** + * @brief Peers screen with network info + */ +class PeersScreen { +public: + void setPeers(const std::vector& peers) { m_peers = peers; } + void setNetworkStats(const NetworkStats& stats) { m_networkStats = stats; } + + void setOnDisconnectPeer(std::function callback) { + m_onDisconnectPeer = callback; + } + void setOnAddNode(std::function callback) { + m_onAddNode = callback; + } + + void render(); + +private: + void renderNetworkStats(); + void renderPeersList(); + void renderPeerDetails(); + void renderAddNodeDialog(); + + std::vector m_peers; + NetworkStats m_networkStats; + + std::function m_onDisconnectPeer; + std::function m_onAddNode; + + int m_selectedPeerId = -1; + bool m_showDetails = false; + bool m_showAddNode = false; + char m_addNodeBuffer[256] = {0}; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void PeersScreen::render() { + // Title + ImGui::BeginGroup(); + { + Typography::instance().text(TypeStyle::H5, "Network Peers"); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 120); + + if (OutlinedButton("+ ADD NODE")) { + m_showAddNode = true; + } + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Network stats cards + renderNetworkStats(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Peers list + renderPeersList(); + + // Dialogs + if (m_showDetails) { + renderPeerDetails(); + } + + if (m_showAddNode) { + renderAddNodeDialog(); + } +} + +inline void PeersScreen::renderNetworkStats() { + float availWidth = ImGui::GetContentRegionAvail().x; + float cardWidth = (availWidth - spacing::dp(2) * 3) / 4.0f; + + // Connections card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("conn_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "CONNECTIONS"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char connStr[32]; + snprintf(connStr, sizeof(connStr), "%d", m_networkStats.totalConnections); + Typography::instance().text(TypeStyle::H4, connStr); + + char detailStr[64]; + snprintf(detailStr, sizeof(detailStr), ICON_MD_ARROW_DOWNWARD "%d in " ICON_MD_ARROW_UPWARD "%d out", + m_networkStats.inboundCount, m_networkStats.outboundCount); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), detailStr); + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Block height card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("height_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "BLOCK HEIGHT"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char heightStr[32]; + snprintf(heightStr, sizeof(heightStr), "%d", m_networkStats.currentHeight); + Typography::instance().text(TypeStyle::H4, heightStr); + + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), + m_networkStats.networkName.c_str()); + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Data sent card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("sent_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "DATA SENT"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char dataStr[32]; + double mb = m_networkStats.totalBytesSent / (1024.0 * 1024.0); + if (mb > 1024) { + snprintf(dataStr, sizeof(dataStr), "%.1f GB", mb / 1024.0); + } else { + snprintf(dataStr, sizeof(dataStr), "%.1f MB", mb); + } + Typography::instance().text(TypeStyle::H5, dataStr); + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Data received card + ImGui::BeginGroup(); + { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(2); + cardSpec.width = cardWidth; + + ImGui::PushID("recv_card"); + if (BeginCard(cardSpec)) { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "DATA RECEIVED"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + char dataStr[32]; + double mb = m_networkStats.totalBytesReceived / (1024.0 * 1024.0); + if (mb > 1024) { + snprintf(dataStr, sizeof(dataStr), "%.1f GB", mb / 1024.0); + } else { + snprintf(dataStr, sizeof(dataStr), "%.1f MB", mb); + } + Typography::instance().text(TypeStyle::H5, dataStr); + + EndCard(); + } + ImGui::PopID(); + } + ImGui::EndGroup(); +} + +inline void PeersScreen::renderPeersList() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + if (m_peers.empty()) { + ImGui::Dummy(ImVec2(0, spacing::dp(4))); + float availWidth = ImGui::GetContentRegionAvail().x; + + const char* emptyText = "No peers connected"; + ImVec2 textSize = ImGui::CalcTextSize(emptyText); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - textSize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), emptyText); + + ImGui::Dummy(ImVec2(0, spacing::dp(4))); + } else { + BeginList("peers_list", false); + + for (const auto& peer : m_peers) { + ListItemSpec itemSpec; + + // Direction icon + itemSpec.leadingIcon = peer.isInbound ? ICON_MD_ARROW_DOWNWARD : ICON_MD_ARROW_UPWARD; + + // Address as primary + itemSpec.primaryText = peer.address.c_str(); + + // Version + latency as secondary + char secondaryStr[128]; + snprintf(secondaryStr, sizeof(secondaryStr), "%s • %dms • Height: %d", + peer.subversion.c_str(), peer.latency, peer.currentHeight); + itemSpec.secondaryText = secondaryStr; + + itemSpec.trailingIcon = ICON_MD_INFO; + itemSpec.dividerBelow = true; + + char peerId[16]; + snprintf(peerId, sizeof(peerId), "peer_%d", peer.id); + ImGui::PushID(peerId); + + if (ListItem(itemSpec)) { + m_selectedPeerId = peer.id; + m_showDetails = true; + } + + ImGui::PopID(); + } + + EndList(); + } + + EndCard(); + } +} + +inline void PeersScreen::renderPeerDetails() { + // Find selected peer + const PeerInfo* selected = nullptr; + for (const auto& peer : m_peers) { + if (peer.id == m_selectedPeerId) { + selected = &peer; + break; + } + } + + if (!selected) { + m_showDetails = false; + return; + } + + DialogSpec dialogSpec; + dialogSpec.title = "Peer Details"; + dialogSpec.maxWidth = 450.0f; + + DialogResult result = BeginDialog("peer_details", dialogSpec); + + if (result.isOpen) { + const PeerInfo& peer = *selected; + + // Direction badge + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filled; + chipSpec.color = peer.isInbound ? colors::Blue500 : colors::Orange500; + Chip(peer.isInbound ? ICON_MD_ARROW_DOWNWARD " Inbound" : ICON_MD_ARROW_UPWARD " Outbound", chipSpec); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Address + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "ADDRESS"); + Typography::instance().text(TypeStyle::Body1, peer.address.c_str()); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Client + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "CLIENT"); + Typography::instance().text(TypeStyle::Body2, peer.subversion.c_str()); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Height + char heightStr[64]; + snprintf(heightStr, sizeof(heightStr), "%d (started at %d)", + peer.currentHeight, peer.startingHeight); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "BLOCK HEIGHT"); + Typography::instance().text(TypeStyle::Body2, heightStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Latency + char latencyStr[32]; + snprintf(latencyStr, sizeof(latencyStr), "%d ms", peer.latency); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "LATENCY"); + Typography::instance().text(TypeStyle::Body2, latencyStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Connected time + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "CONNECTED"); + Typography::instance().text(TypeStyle::Body2, peer.connTime.c_str()); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Data transferred + char dataStr[64]; + snprintf(dataStr, sizeof(dataStr), ICON_MD_ARROW_UPWARD " %.2f MB " ICON_MD_ARROW_DOWNWARD " %.2f MB", + peer.bytesSent / (1024.0 * 1024.0), + peer.bytesReceived / (1024.0 * 1024.0)); + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "DATA TRANSFERRED"); + Typography::instance().text(TypeStyle::Body2, dataStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Actions + float availWidth = ImGui::GetContentRegionAvail().x; + + // Disconnect button (danger) + ImGui::PushStyleColor(ImGuiCol_Button, colors::withAlpha(colors::Red500, 0.1f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(colors::Red500, 0.2f)); + ImGui::PushStyleColor(ImGuiCol_Text, colors::Red500); + + if (ImGui::Button("DISCONNECT", ImVec2(120, 36))) { + if (m_onDisconnectPeer) m_onDisconnectPeer(peer.id); + m_showDetails = false; + } + + ImGui::PopStyleColor(3); + + ImGui::SameLine(availWidth - 80); + + if (ContainedButton("CLOSE")) { + m_showDetails = false; + } + + EndDialog(); + } + + if (result.dismissed) { + m_showDetails = false; + } +} + +inline void PeersScreen::renderAddNodeDialog() { + DialogSpec dialogSpec; + dialogSpec.title = "Add Node"; + dialogSpec.maxWidth = 400.0f; + + DialogResult result = BeginDialog("add_node", dialogSpec); + + if (result.isOpen) { + Typography::instance().text(TypeStyle::Body1, + "Enter the IP address or hostname of a node to connect to:"); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + TextFieldSpec textSpec; + textSpec.label = "Node Address"; + textSpec.placeholder = "192.168.1.1:18030 or node.example.com"; + textSpec.variant = TextFieldVariant::Outlined; + textSpec.width = -1; + + TextField("add_node_addr", m_addNodeBuffer, sizeof(m_addNodeBuffer), textSpec); + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + float availWidth = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - 200); + + if (TextButton("CANCEL")) { + m_showAddNode = false; + memset(m_addNodeBuffer, 0, sizeof(m_addNodeBuffer)); + } + + ImGui::SameLine(0, spacing::dp(2)); + + bool canAdd = strlen(m_addNodeBuffer) > 0; + ImGui::BeginDisabled(!canAdd); + if (ContainedButton("ADD")) { + if (m_onAddNode) m_onAddNode(m_addNodeBuffer); + m_showAddNode = false; + memset(m_addNodeBuffer, 0, sizeof(m_addNodeBuffer)); + } + ImGui::EndDisabled(); + + EndDialog(); + } + + if (result.dismissed) { + m_showAddNode = false; + } +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/receive_screen.h b/src/ui/screens/receive_screen.h new file mode 100644 index 0000000..004bd42 --- /dev/null +++ b/src/ui/screens/receive_screen.h @@ -0,0 +1,318 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Receive Screen +// ============================================================================ +// Display receiving addresses with QR codes + +/** + * @brief Wallet address for receiving + */ +struct WalletAddress { + std::string address; + std::string label; + std::string type; // "shielded" or "transparent" + double balance; + bool isDefault; +}; + +/** + * @brief Receive screen with address cards + */ +class ReceiveScreen { +public: + void setAddresses(const std::vector& addresses) { + m_addresses = addresses; + } + + void setOnCopyAddress(std::function callback) { + m_onCopyAddress = callback; + } + + void setOnNewAddress(std::function callback) { + m_onNewAddress = callback; + } + + void setOnShowQR(std::function callback) { + m_onShowQR = callback; + } + + void setOnEditLabel(std::function callback) { + m_onEditLabel = callback; + } + + void render(); + +private: + void renderAddressCard(const WalletAddress& addr, int index); + void renderNewAddressButton(); + void renderQRCodePopup(); + + std::vector m_addresses; + std::function m_onCopyAddress; + std::function m_onNewAddress; + std::function m_onShowQR; + std::function m_onEditLabel; + + std::string m_selectedQRAddress; + bool m_showQRPopup = false; + int m_selectedTab = 0; // 0 = shielded, 1 = transparent +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void ReceiveScreen::render() { + // Title + Typography::instance().text(TypeStyle::H5, "Receive DRGX"); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Tab selection + TabSpec tabSpec; + tabSpec.variant = TabVariant::Fixed; + + if (BeginTabs("receive_tabs", tabSpec)) { + if (Tab(ICON_MD_SHIELD " Shielded", m_selectedTab == 0)) { + m_selectedTab = 0; + } + if (Tab(ICON_MD_DESCRIPTION " Transparent", m_selectedTab == 1)) { + m_selectedTab = 1; + } + EndTabs(); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Filter addresses by type + std::string filterType = m_selectedTab == 0 ? "shielded" : "transparent"; + + // Display filtered addresses + int visibleCount = 0; + for (size_t i = 0; i < m_addresses.size(); i++) { + if (m_addresses[i].type == filterType) { + renderAddressCard(m_addresses[i], static_cast(i)); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + visibleCount++; + } + } + + // Empty state + if (visibleCount == 0) { + CardSpec emptySpec; + emptySpec.elevation = 1; + emptySpec.padding = spacing::dp(4); + + if (BeginCard(emptySpec)) { + float availWidth = ImGui::GetContentRegionAvail().x; + + // Center text + const char* emptyText = m_selectedTab == 0 ? + "No shielded addresses yet" : "No transparent addresses yet"; + + ImVec2 textSize = ImGui::CalcTextSize(emptyText); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - textSize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), emptyText); + + EndCard(); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + } + + // New address button + renderNewAddressButton(); + + // QR popup + if (m_showQRPopup) { + renderQRCodePopup(); + } +} + +inline void ReceiveScreen::renderAddressCard(const WalletAddress& addr, int index) { + CardSpec cardSpec; + cardSpec.elevation = addr.isDefault ? 3 : 1; + cardSpec.padding = spacing::dp(2); + + char cardId[32]; + snprintf(cardId, sizeof(cardId), "addr_card_%d", index); + ImGui::PushID(cardId); + + if (BeginCard(cardSpec)) { + // Header row: Label + Default badge + ImGui::BeginGroup(); + { + if (!addr.label.empty()) { + Typography::instance().text(TypeStyle::Subtitle1, addr.label.c_str()); + } else { + Typography::instance().textColored(TypeStyle::Subtitle1, OnSurfaceMedium(), "Unnamed Address"); + } + + if (addr.isDefault) { + ImGui::SameLine(); + + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filled; + chipSpec.color = Primary(); + + Chip("DEFAULT", chipSpec); + } + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Address (truncated with copy) + ImGui::BeginGroup(); + { + // Show truncated address + std::string displayAddr = addr.address; + if (displayAddr.length() > 40) { + displayAddr = displayAddr.substr(0, 20) + "..." + + displayAddr.substr(displayAddr.length() - 16); + } + + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), + displayAddr.c_str()); + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Balance + if (addr.balance > 0) { + char balanceStr[64]; + snprintf(balanceStr, sizeof(balanceStr), "Balance: %.8f DRGX", addr.balance); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), balanceStr); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + } + + // Action buttons + ImGui::BeginGroup(); + { + if (OutlinedButton(ICON_MD_CONTENT_COPY " COPY")) { + if (m_onCopyAddress) m_onCopyAddress(addr.address); + } + + ImGui::SameLine(0, spacing::dp(1)); + + if (OutlinedButton(ICON_MD_QR_CODE " QR")) { + m_selectedQRAddress = addr.address; + m_showQRPopup = true; + } + + ImGui::SameLine(0, spacing::dp(1)); + + if (TextButton(ICON_MD_EDIT " EDIT")) { + // Would trigger edit label dialog + if (m_onEditLabel) m_onEditLabel(addr.address, addr.label); + } + } + ImGui::EndGroup(); + + EndCard(); + } + + ImGui::PopID(); +} + +inline void ReceiveScreen::renderNewAddressButton() { + // Floating action button style + float buttonWidth = 200.0f; + float availWidth = ImGui::GetContentRegionAvail().x; + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - buttonWidth) * 0.5f); + + if (ContainedButton("+ NEW ADDRESS")) { + if (m_onNewAddress) { + m_onNewAddress(m_selectedTab == 0); // true for shielded + } + } +} + +inline void ReceiveScreen::renderQRCodePopup() { + DialogSpec dialogSpec; + dialogSpec.title = "QR Code"; + dialogSpec.maxWidth = 400.0f; + + DialogResult result = BeginDialog("qr_popup", dialogSpec); + + if (result.isOpen) { + // QR code placeholder (actual QR generation would be separate) + float qrSize = 250.0f; + float availWidth = ImGui::GetContentRegionAvail().x; + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - qrSize) * 0.5f); + + // QR placeholder box + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled( + pos, + ImVec2(pos.x + qrSize, pos.y + qrSize), + ImGui::GetColorU32(Surface()) + ); + ImGui::GetWindowDrawList()->AddRect( + pos, + ImVec2(pos.x + qrSize, pos.y + qrSize), + ImGui::GetColorU32(Divider()), + 4.0f + ); + + // Center text in QR box + const char* qrText = "QR CODE"; + ImVec2 textSize = ImGui::CalcTextSize(qrText); + ImGui::SetCursorScreenPos(ImVec2( + pos.x + (qrSize - textSize.x) * 0.5f, + pos.y + (qrSize - textSize.y) * 0.5f + )); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), qrText); + + ImGui::Dummy(ImVec2(qrSize, qrSize + spacing::dp(2))); + + // Address below QR + ImGui::TextWrapped("%s", m_selectedQRAddress.c_str()); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Actions + float btnWidth = 100.0f; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - btnWidth * 2 - spacing::dp(2)) * 0.5f); + + if (OutlinedButton("COPY")) { + if (m_onCopyAddress) m_onCopyAddress(m_selectedQRAddress); + } + + ImGui::SameLine(0, spacing::dp(2)); + + if (ContainedButton("CLOSE")) { + m_showQRPopup = false; + } + + EndDialog(); + } + + if (result.dismissed) { + m_showQRPopup = false; + } +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/screens.h b/src/ui/screens/screens.h new file mode 100644 index 0000000..5c42cc2 --- /dev/null +++ b/src/ui/screens/screens.h @@ -0,0 +1,91 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +/** + * @file screens.h + * @brief Unified include for all wallet screens + * + * Phase 7: Component Redesign + * + * This header provides access to all Material Design wallet screens: + * - HomeScreen: Dashboard with balances and quick actions + * - SendScreen: Material form for sending DRGX + * - ReceiveScreen: Address cards with QR codes + * - TransactionsScreen: Transaction history list + * - MiningScreen: Mining controls and stats + * - PeersScreen: Network peer information + * - SettingsScreen: Application settings + * - MainLayout: Full application layout with navigation + * - ConfirmationDialog: Modal confirmations for critical actions + * + * Usage: + * @code + * #include "ui/screens/screens.h" + * using namespace dragonx::ui::screens; + * + * // Create main layout + * MainLayout layout; + * + * // Set up data + * BalanceInfo balance; + * balance.total = 12345.67; + * layout.homeScreen().setBalance(balance); + * + * // Render (in main loop) + * layout.render(); + * + * // Handle confirmations + * ConfirmationDialog::instance().render(); + * @endcode + */ + +#pragma once + +// Material Design system +#include "../material/material.h" + +// Individual screens +#include "home_screen.h" +#include "send_screen.h" +#include "receive_screen.h" +#include "transactions_screen.h" +#include "mining_screen.h" +#include "peers_screen.h" +#include "settings_screen.h" + +// Main layout and navigation +#include "main_layout.h" + +// Dialogs +#include "confirmation_dialog.h" + +namespace dragonx { +namespace ui { +namespace screens { + +/** + * @brief Initialize all screen systems + * + * Call this once at application startup to initialize + * any global screen state. + */ +inline void InitializeScreens() { + // Currently no global initialization needed + // Reserved for future use +} + +/** + * @brief Shutdown all screen systems + * + * Call this at application shutdown to clean up + * any global screen state. + */ +inline void ShutdownScreens() { + // Currently no global cleanup needed + // Reserved for future use +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/send_screen.h b/src/ui/screens/send_screen.h new file mode 100644 index 0000000..4dd1c03 --- /dev/null +++ b/src/ui/screens/send_screen.h @@ -0,0 +1,430 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "../../config/version.h" +#include "imgui.h" +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Send Screen +// ============================================================================ +// Material Design form for sending DRGX + +/** + * @brief Address book entry + */ +struct AddressBookEntry { + std::string label; + std::string address; +}; + +/** + * @brief Send form data + */ +struct SendFormData { + char toAddress[512] = {0}; + char amount[32] = {0}; + char memo[512] = {0}; + bool useShielded = true; + double fee = DRAGONX_DEFAULT_FEE; + + // Validation state + bool addressValid = false; + bool amountValid = false; + std::string addressError; + std::string amountError; +}; + +/** + * @brief Send screen with Material form + */ +class SendScreen { +public: + SendScreen() = default; + + void setAvailableBalance(double shielded, double transparent) { + m_shieldedBalance = shielded; + m_transparentBalance = transparent; + } + + void setAddressBook(const std::vector& entries) { + m_addressBook = entries; + } + + void setOnSend(std::function callback) { + m_onSend = callback; + } + + void setOnCancel(std::function callback) { + m_onCancel = callback; + } + + void setOnValidateAddress(std::function callback) { + m_onValidateAddress = callback; + } + + void clear() { + memset(m_formData.toAddress, 0, sizeof(m_formData.toAddress)); + memset(m_formData.amount, 0, sizeof(m_formData.amount)); + memset(m_formData.memo, 0, sizeof(m_formData.memo)); + m_formData.useShielded = true; + m_formData.addressValid = false; + m_formData.amountValid = false; + m_formData.addressError.clear(); + m_formData.amountError.clear(); + } + + void render(); + +private: + void renderFromSelector(); + void renderAddressField(); + void renderAmountField(); + void renderMemoField(); + void renderFeeDisplay(); + void renderActions(); + void validateForm(); + + SendFormData m_formData; + double m_shieldedBalance = 0.0; + double m_transparentBalance = 0.0; + std::vector m_addressBook; + + std::function m_onSend; + std::function m_onCancel; + std::function m_onValidateAddress; + + bool m_showAddressBook = false; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void SendScreen::render() { + float availWidth = ImGui::GetContentRegionAvail().x; + float formWidth = std::min(availWidth, 500.0f); + float offsetX = (availWidth - formWidth) * 0.5f; + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX); + ImGui::BeginGroup(); + { + // Title + Typography::instance().text(TypeStyle::H5, "Send DRGX"); + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Form card + CardSpec cardSpec; + cardSpec.elevation = 2; + cardSpec.padding = spacing::dp(3); + cardSpec.width = formWidth; + + if (BeginCard(cardSpec)) { + // From selector (shielded vs transparent) + renderFromSelector(); + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // To address field + renderAddressField(); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Amount field + renderAmountField(); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Memo field (only for shielded) + if (m_formData.useShielded) { + renderMemoField(); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + } + + // Fee display + renderFeeDisplay(); + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Divider + ImGui::GetWindowDrawList()->AddLine( + ImVec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y), + ImVec2(ImGui::GetCursorScreenPos().x + formWidth - spacing::dp(6), ImGui::GetCursorScreenPos().y), + ImGui::GetColorU32(Divider()), + 1.0f + ); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Action buttons + renderActions(); + + EndCard(); + } + } + ImGui::EndGroup(); +} + +inline void SendScreen::renderFromSelector() { + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SEND FROM"); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + float buttonWidth = 200.0f; + + // Shielded option + ImGui::PushID("from_shielded"); + { + bool selected = m_formData.useShielded; + ImVec4 bgColor = selected ? colors::withAlpha(Primary(), 0.12f) : Surface(); + ImVec4 borderColor = selected ? Primary() : Divider(); + + ImGui::PushStyleColor(ImGuiCol_Button, bgColor); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(Primary(), 0.16f)); + ImGui::PushStyleColor(ImGuiCol_Border, borderColor); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, selected ? 2.0f : 1.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f); + + char label[128]; + snprintf(label, sizeof(label), ICON_MD_SHIELD " Shielded\n%.4f DRGX", m_shieldedBalance); + + if (ImGui::Button(label, ImVec2(buttonWidth, 60))) { + m_formData.useShielded = true; + } + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + } + ImGui::PopID(); + + ImGui::SameLine(0, spacing::dp(2)); + + // Transparent option + ImGui::PushID("from_transparent"); + { + bool selected = !m_formData.useShielded; + ImVec4 bgColor = selected ? colors::withAlpha(Secondary(), 0.12f) : Surface(); + ImVec4 borderColor = selected ? Secondary() : Divider(); + + ImGui::PushStyleColor(ImGuiCol_Button, bgColor); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors::withAlpha(Secondary(), 0.16f)); + ImGui::PushStyleColor(ImGuiCol_Border, borderColor); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, selected ? 2.0f : 1.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0f); + + char label[128]; + snprintf(label, sizeof(label), ICON_MD_DESCRIPTION " Transparent\n%.4f DRGX", m_transparentBalance); + + if (ImGui::Button(label, ImVec2(buttonWidth, 60))) { + m_formData.useShielded = false; + } + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + } + ImGui::PopID(); +} + +inline void SendScreen::renderAddressField() { + TextFieldSpec spec; + spec.label = "Recipient Address"; + spec.placeholder = "Enter DRGX address..."; + spec.variant = TextFieldVariant::Outlined; + spec.width = -1; // Full width + spec.hasError = !m_formData.addressError.empty(); + spec.helperText = m_formData.addressError.empty() ? + "z-address (shielded) or t-address (transparent)" : + m_formData.addressError.c_str(); + spec.leadingIcon = ICON_MD_MARKUNREAD_MAILBOX; + spec.trailingIcon = ICON_MD_MENU_BOOK; // Address book + + TextFieldResult result = TextField("send_address", m_formData.toAddress, + sizeof(m_formData.toAddress), spec); + + if (result.trailingIconClicked) { + m_showAddressBook = !m_showAddressBook; + } + + if (result.changed) { + // Validate address + if (m_onValidateAddress) { + m_formData.addressValid = m_onValidateAddress(m_formData.toAddress); + if (!m_formData.addressValid && strlen(m_formData.toAddress) > 10) { + m_formData.addressError = "Invalid address format"; + } else { + m_formData.addressError.clear(); + } + } + } + + // Address book dropdown + if (m_showAddressBook && !m_addressBook.empty()) { + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + CardSpec cardSpec; + cardSpec.elevation = 8; + cardSpec.padding = spacing::dp(1); + + if (BeginCard(cardSpec)) { + BeginList("address_book_list", false); + + for (const auto& entry : m_addressBook) { + ListItemSpec itemSpec; + itemSpec.leadingIcon = "👤"; + itemSpec.primaryText = entry.label.c_str(); + itemSpec.secondaryText = entry.address.substr(0, 20).c_str(); + itemSpec.dividerBelow = true; + + if (ListItem(itemSpec)) { + strncpy(m_formData.toAddress, entry.address.c_str(), + sizeof(m_formData.toAddress) - 1); + m_formData.addressValid = true; + m_formData.addressError.clear(); + m_showAddressBook = false; + } + } + + EndList(); + EndCard(); + } + } +} + +inline void SendScreen::renderAmountField() { + TextFieldSpec spec; + spec.label = "Amount"; + spec.placeholder = "0.00000000"; + spec.variant = TextFieldVariant::Outlined; + spec.width = 200.0f; + spec.hasError = !m_formData.amountError.empty(); + spec.helperText = m_formData.amountError.c_str(); + spec.suffix = "DRGX"; + + TextFieldResult result = TextField("send_amount", m_formData.amount, + sizeof(m_formData.amount), spec); + + if (result.changed) { + // Validate amount + double amt = atof(m_formData.amount); + double maxBalance = m_formData.useShielded ? m_shieldedBalance : m_transparentBalance; + + if (amt <= 0) { + m_formData.amountValid = false; + if (strlen(m_formData.amount) > 0) { + m_formData.amountError = "Amount must be greater than 0"; + } + } else if (amt > maxBalance - m_formData.fee) { + m_formData.amountValid = false; + m_formData.amountError = "Insufficient balance"; + } else { + m_formData.amountValid = true; + m_formData.amountError.clear(); + } + } + + ImGui::SameLine(); + + // Max button + if (TextButton("MAX")) { + double maxBalance = m_formData.useShielded ? m_shieldedBalance : m_transparentBalance; + double maxAmount = maxBalance - m_formData.fee; + if (maxAmount > 0) { + snprintf(m_formData.amount, sizeof(m_formData.amount), "%.8f", maxAmount); + m_formData.amountValid = true; + m_formData.amountError.clear(); + } + } +} + +inline void SendScreen::renderMemoField() { + TextFieldSpec spec; + spec.label = "Memo (encrypted)"; + spec.placeholder = "Optional private message..."; + spec.variant = TextFieldVariant::Outlined; + spec.width = -1; + spec.multiline = true; + spec.helperText = "512 characters max. Only visible to recipient."; + spec.maxLength = 512; + + TextField("send_memo", m_formData.memo, sizeof(m_formData.memo), spec); +} + +inline void SendScreen::renderFeeDisplay() { + ImGui::BeginGroup(); + { + Typography::instance().textColored(TypeStyle::Body2, OnSurfaceMedium(), "Network Fee:"); + ImGui::SameLine(); + + char feeStr[32]; + snprintf(feeStr, sizeof(feeStr), "%.8f DRGX", m_formData.fee); + Typography::instance().text(TypeStyle::Body2, feeStr); + } + ImGui::EndGroup(); + + // Total if amount is valid + if (m_formData.amountValid) { + double amt = atof(m_formData.amount); + double total = amt + m_formData.fee; + + ImGui::BeginGroup(); + { + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), "Total:"); + ImGui::SameLine(); + + char totalStr[32]; + snprintf(totalStr, sizeof(totalStr), "%.8f DRGX", total); + Typography::instance().textColored(TypeStyle::Body1, Primary(), totalStr); + } + ImGui::EndGroup(); + } +} + +inline void SendScreen::renderActions() { + float buttonWidth = 120.0f; + float availWidth = ImGui::GetContentRegionAvail().x; + + // Right-align buttons + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - buttonWidth * 2 - spacing::dp(2)); + + // Cancel button + if (TextButton("CANCEL")) { + if (m_onCancel) m_onCancel(); + } + + ImGui::SameLine(0, spacing::dp(2)); + + // Send button + bool canSend = m_formData.addressValid && m_formData.amountValid; + + ImGui::BeginDisabled(!canSend); + if (ContainedButton("SEND")) { + if (m_onSend) m_onSend(m_formData); + } + ImGui::EndDisabled(); +} + +inline void SendScreen::validateForm() { + // Address validation + if (strlen(m_formData.toAddress) == 0) { + m_formData.addressValid = false; + m_formData.addressError = "Address is required"; + } + + // Amount validation + if (strlen(m_formData.amount) == 0) { + m_formData.amountValid = false; + m_formData.amountError = "Amount is required"; + } +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/settings_screen.h b/src/ui/screens/settings_screen.h new file mode 100644 index 0000000..a583610 --- /dev/null +++ b/src/ui/screens/settings_screen.h @@ -0,0 +1,560 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../config/version.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Settings Screen +// ============================================================================ +// Application settings with Material list items + +/** + * @brief Setting category + */ +enum class SettingsCategory { + Wallet, + Display, + Network, + Privacy, + Advanced +}; + +/** + * @brief Settings data + */ +struct SettingsData { + // Wallet + bool autoShield = true; + double defaultFee = DRAGONX_DEFAULT_FEE; + + // Display + std::string theme = "dark"; + std::string language = "en"; + std::string fiatCurrency = "USD"; + bool showBalanceInFiat = true; + bool hideEmptyAddresses = true; + + // Network + std::string proxyAddress; + int proxyPort = 9050; + bool useTor = false; + int maxConnections = 125; + + // Privacy + bool rememberAddresses = true; + bool autoLock = true; + int autoLockTimeout = 5; // minutes + + // Advanced + int confirmations = 10; + std::string dataDir; + bool debugMode = false; +}; + +/** + * @brief Settings screen with Material list + */ +class SettingsScreen { +public: + void setSettings(const SettingsData& settings) { m_settings = settings; } + const SettingsData& getSettings() const { return m_settings; } + + void setOnSettingsChanged(std::function callback) { + m_onSettingsChanged = callback; + } + + void setOnBackupWallet(std::function callback) { + m_onBackupWallet = callback; + } + + void setOnExportKeys(std::function callback) { + m_onExportKeys = callback; + } + + void setOnRescan(std::function callback) { + m_onRescan = callback; + } + + void render(); + +private: + void renderWalletSettings(); + void renderDisplaySettings(); + void renderNetworkSettings(); + void renderPrivacySettings(); + void renderAdvancedSettings(); + void renderAboutSection(); + + void notifySettingsChanged(); + + SettingsData m_settings; + std::function m_onSettingsChanged; + std::function m_onBackupWallet; + std::function m_onExportKeys; + std::function m_onRescan; + + SettingsCategory m_selectedCategory = SettingsCategory::Wallet; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void SettingsScreen::render() { + // Title + Typography::instance().text(TypeStyle::H5, "Settings"); + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Category tabs + TabSpec tabSpec; + tabSpec.variant = TabVariant::Scrollable; + + if (BeginTabs("settings_tabs", tabSpec)) { + if (Tab(ICON_MD_ACCOUNT_BALANCE_WALLET " Wallet", m_selectedCategory == SettingsCategory::Wallet)) { + m_selectedCategory = SettingsCategory::Wallet; + } + if (Tab(ICON_MD_PALETTE " Display", m_selectedCategory == SettingsCategory::Display)) { + m_selectedCategory = SettingsCategory::Display; + } + if (Tab(ICON_MD_PUBLIC " Network", m_selectedCategory == SettingsCategory::Network)) { + m_selectedCategory = SettingsCategory::Network; + } + if (Tab(ICON_MD_LOCK " Privacy", m_selectedCategory == SettingsCategory::Privacy)) { + m_selectedCategory = SettingsCategory::Privacy; + } + if (Tab(ICON_MD_SETTINGS " Advanced", m_selectedCategory == SettingsCategory::Advanced)) { + m_selectedCategory = SettingsCategory::Advanced; + } + EndTabs(); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Settings content + switch (m_selectedCategory) { + case SettingsCategory::Wallet: + renderWalletSettings(); + break; + case SettingsCategory::Display: + renderDisplaySettings(); + break; + case SettingsCategory::Network: + renderNetworkSettings(); + break; + case SettingsCategory::Privacy: + renderPrivacySettings(); + break; + case SettingsCategory::Advanced: + renderAdvancedSettings(); + break; + } + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // About section (always visible) + renderAboutSection(); +} + +inline void SettingsScreen::renderWalletSettings() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("wallet_settings", false); + + // Auto-shield toggle + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Auto-Shield Transparent Funds"; + itemSpec.secondaryText = "Automatically move transparent balance to shielded"; + itemSpec.dividerBelow = true; + + ImGui::PushID("auto_shield"); + ListItem(itemSpec); + + // Toggle positioned at end + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.autoShield)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + // Default fee + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Default Transaction Fee"; + + char feeStr[32]; + snprintf(feeStr, sizeof(feeStr), "%.8f DRGX", m_settings.defaultFee); + itemSpec.secondaryText = feeStr; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Backup wallet + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = ICON_MD_SAVE; + itemSpec.primaryText = "Backup Wallet"; + itemSpec.secondaryText = "Export wallet backup file"; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + if (ListItem(itemSpec)) { + if (m_onBackupWallet) m_onBackupWallet(); + } + } + + // Export keys + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = ICON_MD_KEY; + itemSpec.primaryText = "Export Private Keys"; + itemSpec.secondaryText = "Export viewing and spending keys"; + itemSpec.trailingIcon = ">"; + + if (ListItem(itemSpec)) { + if (m_onExportKeys) m_onExportKeys(); + } + } + + EndList(); + EndCard(); + } +} + +inline void SettingsScreen::renderDisplaySettings() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("display_settings", false); + + // Theme selection + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Theme"; + itemSpec.secondaryText = m_settings.theme == "dark" ? "Dark" : "Light"; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Language + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Language"; + itemSpec.secondaryText = "English"; // Would map from code + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Fiat currency + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Fiat Currency"; + itemSpec.secondaryText = m_settings.fiatCurrency.c_str(); + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Show balance in fiat toggle + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Show Balance in Fiat"; + itemSpec.secondaryText = "Display fiat equivalent on home screen"; + itemSpec.dividerBelow = true; + + ImGui::PushID("show_fiat"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.showBalanceInFiat)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + // Hide empty addresses + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Hide Empty Addresses"; + itemSpec.secondaryText = "Don't show addresses with zero balance"; + + ImGui::PushID("hide_empty"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.hideEmptyAddresses)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + EndList(); + EndCard(); + } +} + +inline void SettingsScreen::renderNetworkSettings() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("network_settings", false); + + // Use Tor + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = "🧅"; + itemSpec.primaryText = "Use Tor Network"; + itemSpec.secondaryText = "Route connections through Tor for privacy"; + itemSpec.dividerBelow = true; + + ImGui::PushID("use_tor"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.useTor)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + // Proxy settings (shown if Tor enabled) + if (m_settings.useTor) { + ListItemSpec itemSpec; + itemSpec.primaryText = "Proxy Address"; + + char proxyStr[128]; + snprintf(proxyStr, sizeof(proxyStr), "%s:%d", + m_settings.proxyAddress.empty() ? "127.0.0.1" : m_settings.proxyAddress.c_str(), + m_settings.proxyPort); + itemSpec.secondaryText = proxyStr; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Max connections + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Maximum Connections"; + + char connStr[32]; + snprintf(connStr, sizeof(connStr), "%d peers", m_settings.maxConnections); + itemSpec.secondaryText = connStr; + itemSpec.trailingIcon = ">"; + + ListItem(itemSpec); + } + + EndList(); + EndCard(); + } +} + +inline void SettingsScreen::renderPrivacySettings() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("privacy_settings", false); + + // Remember addresses + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Remember Addresses"; + itemSpec.secondaryText = "Save recently used addresses"; + itemSpec.dividerBelow = true; + + ImGui::PushID("remember_addr"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.rememberAddresses)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + // Auto-lock + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Auto-Lock Wallet"; + itemSpec.secondaryText = "Lock wallet after inactivity"; + itemSpec.dividerBelow = true; + + ImGui::PushID("auto_lock"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.autoLock)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + // Lock timeout (if auto-lock enabled) + if (m_settings.autoLock) { + ListItemSpec itemSpec; + itemSpec.primaryText = "Lock Timeout"; + + char timeoutStr[32]; + snprintf(timeoutStr, sizeof(timeoutStr), "%d minutes", m_settings.autoLockTimeout); + itemSpec.secondaryText = timeoutStr; + itemSpec.trailingIcon = ">"; + + ListItem(itemSpec); + } + + EndList(); + EndCard(); + } +} + +inline void SettingsScreen::renderAdvancedSettings() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("advanced_settings", false); + + // Required confirmations + { + ListItemSpec itemSpec; + itemSpec.primaryText = "Required Confirmations"; + + char confStr[32]; + snprintf(confStr, sizeof(confStr), "%d blocks", m_settings.confirmations); + itemSpec.secondaryText = confStr; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Data directory + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = "📁"; + itemSpec.primaryText = "Data Directory"; + itemSpec.secondaryText = m_settings.dataDir.empty() ? + "(default)" : m_settings.dataDir.c_str(); + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + ListItem(itemSpec); + } + + // Rescan blockchain + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = ICON_MD_SYNC; + itemSpec.primaryText = "Rescan Blockchain"; + itemSpec.secondaryText = "Rebuild transaction history from blockchain"; + itemSpec.trailingIcon = ">"; + itemSpec.dividerBelow = true; + + if (ListItem(itemSpec)) { + if (m_onRescan) m_onRescan(); + } + } + + // Debug mode + { + ListItemSpec itemSpec; + itemSpec.leadingIcon = "🐛"; + itemSpec.primaryText = "Debug Mode"; + itemSpec.secondaryText = "Enable verbose logging"; + + ImGui::PushID("debug_mode"); + ListItem(itemSpec); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 60); + if (Switch("##toggle", m_settings.debugMode)) { + notifySettingsChanged(); + } + ImGui::PopID(); + } + + EndList(); + EndCard(); + } +} + +inline void SettingsScreen::renderAboutSection() { + CardSpec cardSpec; + cardSpec.elevation = 0; + cardSpec.padding = spacing::dp(3); + cardSpec.outlined = true; + + if (BeginCard(cardSpec)) { + float availWidth = ImGui::GetContentRegionAvail().x; + + // App name and version centered + const char* appName = "ObsidianDragon"; + ImVec2 nameSize = ImGui::CalcTextSize(appName); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - nameSize.x) * 0.5f); + Typography::instance().text(TypeStyle::H6, appName); + + const char* version = "Version 1.0.0-imgui"; + ImVec2 versionSize = ImGui::CalcTextSize(version); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - versionSize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), version); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + const char* copyright = "© 2024-2026 The Hush Developers"; + ImVec2 copySize = ImGui::CalcTextSize(copyright); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - copySize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), copyright); + + const char* license = "Released under GPLv3"; + ImVec2 licenseSize = ImGui::CalcTextSize(license); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - licenseSize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), license); + + EndCard(); + } +} + +inline void SettingsScreen::notifySettingsChanged() { + if (m_onSettingsChanged) { + m_onSettingsChanged(m_settings); + } +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/screens/transactions_screen.h b/src/ui/screens/transactions_screen.h new file mode 100644 index 0000000..97ea435 --- /dev/null +++ b/src/ui/screens/transactions_screen.h @@ -0,0 +1,419 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../material/material.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include + +namespace dragonx { +namespace ui { +namespace screens { + +using namespace material; + +// ============================================================================ +// Transactions Screen +// ============================================================================ +// Display transaction history with Material list + +/** + * @brief Transaction details + */ +struct Transaction { + std::string txid; + std::string type; // "sent", "received", "mined", "self" + std::string fromAddress; + std::string toAddress; + double amount; + double fee; + std::string memo; + std::string datetime; + int confirmations; + int blockHeight; + bool isShielded; +}; + +/** + * @brief Transaction filter options + */ +enum class TxFilter { + All, + Sent, + Received, + Mined +}; + +/** + * @brief Transactions screen with Material list + */ +class TransactionsScreen { +public: + void setTransactions(const std::vector& txns) { + m_transactions = txns; + } + + void setOnTransactionClick(std::function callback) { + m_onTxClick = callback; + } + + void setOnCopyTxid(std::function callback) { + m_onCopyTxid = callback; + } + + void setOnExport(std::function callback) { + m_onExport = callback; + } + + void render(); + +private: + void renderFilters(); + void renderTransactionList(); + void renderTransactionItem(const Transaction& tx, int index); + void renderTransactionDetails(); + void renderEmptyState(); + + std::vector m_transactions; + std::function m_onTxClick; + std::function m_onCopyTxid; + std::function m_onExport; + + TxFilter m_filter = TxFilter::All; + std::string m_searchQuery; + char m_searchBuffer[256] = {0}; + + std::string m_selectedTxid; + bool m_showDetails = false; +}; + +// ============================================================================ +// Implementation +// ============================================================================ + +inline void TransactionsScreen::render() { + // Title and export button + ImGui::BeginGroup(); + { + Typography::instance().text(TypeStyle::H5, "Transactions"); + + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 100); + + if (OutlinedButton("📥 EXPORT")) { + if (m_onExport) m_onExport(); + } + } + ImGui::EndGroup(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Filters + renderFilters(); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Transaction list or empty state + std::vector filtered; + for (const auto& tx : m_transactions) { + // Apply type filter + if (m_filter != TxFilter::All) { + if (m_filter == TxFilter::Sent && tx.type != "sent") continue; + if (m_filter == TxFilter::Received && tx.type != "received") continue; + if (m_filter == TxFilter::Mined && tx.type != "mined") continue; + } + + // Apply search filter + if (strlen(m_searchBuffer) > 0) { + std::string search = m_searchBuffer; + if (tx.txid.find(search) == std::string::npos && + tx.toAddress.find(search) == std::string::npos && + tx.fromAddress.find(search) == std::string::npos && + tx.memo.find(search) == std::string::npos) { + continue; + } + } + + filtered.push_back(tx); + } + + if (filtered.empty()) { + renderEmptyState(); + } else { + // Scrollable list + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = 0; + + if (BeginCard(cardSpec)) { + BeginList("tx_list", false); + + for (size_t i = 0; i < filtered.size(); i++) { + renderTransactionItem(filtered[i], static_cast(i)); + } + + EndList(); + EndCard(); + } + } + + // Details popup + if (m_showDetails) { + renderTransactionDetails(); + } +} + +inline void TransactionsScreen::renderFilters() { + // Search field + TextFieldSpec searchSpec; + searchSpec.label = "Search"; + searchSpec.placeholder = "Search by address, txid, memo..."; + searchSpec.variant = TextFieldVariant::Outlined; + searchSpec.width = 300.0f; + searchSpec.leadingIcon = ICON_MD_SEARCH; + + TextField("tx_search", m_searchBuffer, sizeof(m_searchBuffer), searchSpec); + + ImGui::SameLine(0, spacing::dp(3)); + + // Filter chips + ImGui::BeginGroup(); + { + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filter; + chipSpec.selectable = true; + + chipSpec.selected = (m_filter == TxFilter::All); + if (FilterChip("All", chipSpec)) { + m_filter = TxFilter::All; + } + + ImGui::SameLine(0, spacing::dp(1)); + + chipSpec.selected = (m_filter == TxFilter::Sent); + if (FilterChip(ICON_MD_CALL_MADE " Sent", chipSpec)) { + m_filter = TxFilter::Sent; + } + + ImGui::SameLine(0, spacing::dp(1)); + + chipSpec.selected = (m_filter == TxFilter::Received); + if (FilterChip(ICON_MD_CALL_RECEIVED " Received", chipSpec)) { + m_filter = TxFilter::Received; + } + + ImGui::SameLine(0, spacing::dp(1)); + + chipSpec.selected = (m_filter == TxFilter::Mined); + if (FilterChip(ICON_MD_CONSTRUCTION " Mined", chipSpec)) { + m_filter = TxFilter::Mined; + } + } + ImGui::EndGroup(); +} + +inline void TransactionsScreen::renderTransactionItem(const Transaction& tx, int index) { + ListItemSpec itemSpec; + + // Icon based on type + if (tx.type == "received") { + itemSpec.leadingIcon = ICON_MD_CALL_RECEIVED; + } else if (tx.type == "sent") { + itemSpec.leadingIcon = ICON_MD_CALL_MADE; + } else if (tx.type == "mined") { + itemSpec.leadingIcon = ICON_MD_CONSTRUCTION; + } else { + itemSpec.leadingIcon = ICON_MD_SWAP_HORIZ; // Self transfer + } + + // Amount formatting + char amountStr[64]; + if (tx.type == "sent") { + snprintf(amountStr, sizeof(amountStr), "-%.8f DRGX", tx.amount); + } else { + snprintf(amountStr, sizeof(amountStr), "+%.8f DRGX", tx.amount); + } + itemSpec.primaryText = amountStr; + + // Secondary: date + confirmations + char secondaryStr[128]; + if (tx.confirmations == 0) { + snprintf(secondaryStr, sizeof(secondaryStr), "%s • " ICON_MD_HOURGLASS_EMPTY " Pending", tx.datetime.c_str()); + } else if (tx.confirmations < 10) { + snprintf(secondaryStr, sizeof(secondaryStr), "%s • %d confirmations", + tx.datetime.c_str(), tx.confirmations); + } else { + snprintf(secondaryStr, sizeof(secondaryStr), "%s • " ICON_MD_CHECK " Confirmed", tx.datetime.c_str()); + } + itemSpec.secondaryText = secondaryStr; + + // Privacy indicator + if (tx.isShielded) { + itemSpec.trailingIcon = ICON_MD_SHIELD; + } + + itemSpec.dividerBelow = true; + + char itemId[32]; + snprintf(itemId, sizeof(itemId), "tx_%d", index); + ImGui::PushID(itemId); + + if (ListItem(itemSpec)) { + m_selectedTxid = tx.txid; + m_showDetails = true; + } + + ImGui::PopID(); +} + +inline void TransactionsScreen::renderTransactionDetails() { + // Find the selected transaction + const Transaction* selected = nullptr; + for (const auto& tx : m_transactions) { + if (tx.txid == m_selectedTxid) { + selected = &tx; + break; + } + } + + if (!selected) { + m_showDetails = false; + return; + } + + DialogSpec dialogSpec; + dialogSpec.title = "Transaction Details"; + dialogSpec.maxWidth = 500.0f; + + DialogResult result = BeginDialog("tx_details", dialogSpec); + + if (result.isOpen) { + const Transaction& tx = *selected; + + // Type badge + ChipSpec chipSpec; + chipSpec.variant = ChipVariant::Filled; + + if (tx.type == "received") { + chipSpec.color = colors::Green500; + Chip(ICON_MD_CALL_RECEIVED " Received", chipSpec); + } else if (tx.type == "sent") { + chipSpec.color = colors::Red500; + Chip(ICON_MD_CALL_MADE " Sent", chipSpec); + } else if (tx.type == "mined") { + chipSpec.color = Secondary(); + Chip(ICON_MD_CONSTRUCTION " Mined", chipSpec); + } + + if (tx.isShielded) { + ImGui::SameLine(); + chipSpec.color = Primary(); + Chip(ICON_MD_SHIELD " Shielded", chipSpec); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Amount + Typography::instance().textColored(TypeStyle::Overline, OnSurfaceMedium(), "AMOUNT"); + char amountStr[64]; + snprintf(amountStr, sizeof(amountStr), "%.8f DRGX", tx.amount); + Typography::instance().text(TypeStyle::H5, amountStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Details grid + auto detailRow = [](const char* label, const char* value, bool canCopy = false) { + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), label); + Typography::instance().text(TypeStyle::Body2, value); + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + }; + + detailRow("DATE", tx.datetime.c_str()); + + char confStr[32]; + if (tx.confirmations == 0) { + snprintf(confStr, sizeof(confStr), "Pending"); + } else { + snprintf(confStr, sizeof(confStr), "%d confirmations", tx.confirmations); + } + detailRow("STATUS", confStr); + + if (tx.blockHeight > 0) { + char blockStr[32]; + snprintf(blockStr, sizeof(blockStr), "%d", tx.blockHeight); + detailRow("BLOCK", blockStr); + } + + char feeStr[32]; + snprintf(feeStr, sizeof(feeStr), "%.8f DRGX", tx.fee); + detailRow("FEE", feeStr); + + ImGui::Dummy(ImVec2(0, spacing::dp(1))); + + // Transaction ID + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), "TRANSACTION ID"); + ImGui::TextWrapped("%s", tx.txid.c_str()); + + if (TextButton(ICON_MD_CONTENT_COPY " COPY TXID")) { + if (m_onCopyTxid) m_onCopyTxid(tx.txid); + } + + // Memo if present + if (!tx.memo.empty()) { + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + Typography::instance().textColored(TypeStyle::Caption, OnSurfaceMedium(), "MEMO"); + ImGui::TextWrapped("%s", tx.memo.c_str()); + } + + ImGui::Dummy(ImVec2(0, spacing::dp(3))); + + // Close button + float availWidth = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + availWidth - 100); + + if (ContainedButton("CLOSE")) { + m_showDetails = false; + } + + EndDialog(); + } + + if (result.dismissed) { + m_showDetails = false; + } +} + +inline void TransactionsScreen::renderEmptyState() { + CardSpec cardSpec; + cardSpec.elevation = 1; + cardSpec.padding = spacing::dp(6); + + if (BeginCard(cardSpec)) { + float availWidth = ImGui::GetContentRegionAvail().x; + + // Icon + const char* icon = ICON_MD_RECEIPT; + ImVec2 iconSize = ImGui::CalcTextSize(icon); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - iconSize.x) * 0.5f); + Typography::instance().text(TypeStyle::H3, icon); + + ImGui::Dummy(ImVec2(0, spacing::dp(2))); + + // Message + const char* message = m_filter == TxFilter::All ? + "No transactions yet" : "No matching transactions"; + ImVec2 textSize = ImGui::CalcTextSize(message); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (availWidth - textSize.x) * 0.5f); + Typography::instance().textColored(TypeStyle::Body1, OnSurfaceMedium(), message); + + EndCard(); + } +} + +} // namespace screens +} // namespace ui +} // namespace dragonx diff --git a/src/ui/sidebar.h b/src/ui/sidebar.h new file mode 100644 index 0000000..1dc9ecd --- /dev/null +++ b/src/ui/sidebar.h @@ -0,0 +1,815 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" +#include "material/type.h" +#include "material/colors.h" +#include "material/draw_helpers.h" +#include "layout.h" +#include "schema/ui_schema.h" +#include "../embedded/IconsMaterialDesign.h" +#include +#include + +namespace dragonx { +namespace ui { + +// Navigation pages — order matches sidebar display order +enum class NavPage { + Overview = 0, + Send, + Receive, + History, + // --- separator --- + Mining, + Market, + // --- separator --- + Console, + Peers, + Settings, + Count_ +}; + +struct NavItem { + const char* label; + NavPage page; + const char* section_label; // if non-null, render section label above this item +}; + +inline const NavItem kNavItems[] = { + { "Overview", NavPage::Overview, nullptr }, + { "Send", NavPage::Send, nullptr }, + { "Receive", NavPage::Receive, nullptr }, + { "History", NavPage::History, nullptr }, + { "Mining", NavPage::Mining, "TOOLS" }, + { "Market", NavPage::Market, nullptr }, + { "Console", NavPage::Console, "ADVANCED" }, + { "Network", NavPage::Peers, nullptr }, + { "Settings", NavPage::Settings, nullptr }, +}; +static_assert(sizeof(kNavItems) / sizeof(kNavItems[0]) == (int)NavPage::Count_, + "kNavItems must match NavPage::Count_"); + +// Get the Material Design icon string for a navigation page. +inline const char* GetNavIconMD(NavPage page) +{ + switch (page) { + case NavPage::Overview: return ICON_MD_HOME; + case NavPage::Send: return ICON_MD_CALL_MADE; + case NavPage::Receive: return ICON_MD_CALL_RECEIVED; + case NavPage::History: return ICON_MD_HISTORY; + case NavPage::Mining: return ICON_MD_CONSTRUCTION; + case NavPage::Market: return ICON_MD_TRENDING_UP; + case NavPage::Console: return ICON_MD_TERMINAL; + case NavPage::Peers: return ICON_MD_HUB; + case NavPage::Settings: return ICON_MD_SETTINGS; + default: return ICON_MD_HOME; + } +} + +// Draw a Material Design icon centered at (cx, cy) with the given color. +// Uses the medium (18px) icon font from Typography. +inline void DrawNavIcon(ImDrawList* dl, NavPage page, float cx, float cy, float /*s*/, ImU32 col) +{ + ImFont* iconFont = material::Type().iconMed(); + const char* icon = GetNavIconMD(page); + ImVec2 sz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - sz.x * 0.5f, cy - sz.y * 0.5f), col, icon); +} + +// Lightweight badge / status data the caller provides each frame. +// Counts <= 0 mean "no badge". -1 means "show dot only" (no number). +struct SidebarStatus { + int unconfirmedTxCount = 0; // badge on History + bool miningActive = false; // green dot on Mining + int peerCount = 0; // badge on Peers + // Exit + bool exitClicked = false; + // Branding logo (optional — loaded at startup) + ImTextureID logoTexID = 0; + int logoW = 0; + int logoH = 0; + // Gradient overlay texture (optional) + ImTextureID gradientTexID = 0; +}; + +// Draw an inset cutout bevel around a button rect — the "channel" carved +// into the sidebar surface that the raised button sits inside. +// Highlights and shadows are flipped relative to the button bevel so the +// cutout looks like it is recessed into the material. Light source: top-left. +inline void DrawGlassCutout(ImDrawList* dl, ImVec2 mn, ImVec2 mx, + float rnd, float gap = 2.0f) +{ + float w = mx.x - mn.x + gap * 2.0f; + float h = mx.y - mn.y + gap * 2.0f; + if (w < 1.0f || h < 1.0f) return; + + // Cached cutout style — refreshed once per theme reload + struct CutoutStyleCache { + uint32_t gen = 0; + float shadowAlpha, highlightAlpha, lineW; + float glowExpand, glowAlpha, glowLineW; + }; + static CutoutStyleCache s_cc; + { + uint32_t g = schema::UI().generation(); + if (g != s_cc.gen) { + s_cc.gen = g; + auto rd = [](const char* key, float fb) { + auto e = schema::UI().drawElement("components.sidebar", key); + return e.size >= 0 ? e.size : fb; + }; + s_cc.shadowAlpha = rd("cutout-shadow-alpha", 55.0f); + s_cc.highlightAlpha = rd("cutout-highlight-alpha", 16.0f); + s_cc.lineW = rd("cutout-line-width", 0.75f); + s_cc.glowExpand = rd("cutout-glow-expand", 1.5f); + s_cc.glowAlpha = rd("cutout-glow-alpha", 35.0f); + s_cc.glowLineW = rd("cutout-glow-line-width", 1.5f); + } + } + + ImVec2 cMn(mn.x - gap, mn.y - gap); + ImVec2 cMx(mx.x + gap, mx.y + gap); + float cRnd = rnd + gap; + + float cx = (cMn.x + cMx.x) * 0.5f; + float cy = (cMn.y + cMx.y) * 0.5f; + + // Fast directional light factor — algebraic approximation of angular + // proximity to fixed light at -135°. Replaces atan2f per vertex with + // a dot-product + clamp (no trig, no sqrt). + float invHalfW = 2.0f / w; + float invHalfH = 2.0f / h; + auto lightFactor = [cx, cy, invHalfW, invHalfH](float px, float py) -> float { + float nx = (px - cx) * invHalfW; + float ny = (py - cy) * invHalfH; + return ImClamp(0.5f + 0.3536f * (-nx - ny), 0.0f, 1.0f); + }; + + float fadeStart = 0.30f, fadeEnd = 0.55f; + int shA = (int)s_cc.shadowAlpha; + int hiA = (int)s_cc.highlightAlpha; + float lineW = s_cc.lineW; + + // --- Outer glow pass: wider, softer dark edge on top-left --- + float glowExpand = s_cc.glowExpand; + int glowA = (int)s_cc.glowAlpha; + float glowLineW = s_cc.glowLineW; + { + ImVec2 gMn(cMn.x - glowExpand, cMn.y - glowExpand); + ImVec2 gMx(cMx.x + glowExpand, cMx.y + glowExpand); + float gRnd = cRnd + glowExpand; + int v0 = dl->VtxBuffer.Size; + dl->AddRect(gMn, gMx, IM_COL32(0, 0, 0, 1), gRnd, 0, glowLineW); + int v1 = dl->VtxBuffer.Size; + for (int i = v0; i < v1; i++) { + ImDrawVert& v = dl->VtxBuffer[i]; + float lf = lightFactor(v.pos.x, v.pos.y); + float fade = ImClamp((lf - 0.25f) / 0.30f, 0.0f, 1.0f); + int a = (int)(glowA * fade); + v.col = IM_COL32(0, 0, 0, (unsigned char)ImClamp(a, 0, 255)); + } + } + + // --- Crisp shadow pass (on light-facing edges — top-left dark edge) --- + { + int v0 = dl->VtxBuffer.Size; + dl->AddRect(cMn, cMx, IM_COL32(0, 0, 0, 1), cRnd, 0, lineW); + int v1 = dl->VtxBuffer.Size; + for (int i = v0; i < v1; i++) { + ImDrawVert& v = dl->VtxBuffer[i]; + float lf = lightFactor(v.pos.x, v.pos.y); + float fade = ImClamp((lf - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f); + int a = (int)(shA * fade); + v.col = IM_COL32(0, 0, 0, (unsigned char)ImClamp(a, 0, 255)); + } + } + + // --- Highlight pass (on shadow-facing edges — bottom-right highlight) --- + { + int v0 = dl->VtxBuffer.Size; + dl->AddRect(cMn, cMx, IM_COL32(255, 255, 255, 1), cRnd, 0, lineW); + int v1 = dl->VtxBuffer.Size; + for (int i = v0; i < v1; i++) { + ImDrawVert& v = dl->VtxBuffer[i]; + float lf = lightFactor(v.pos.x, v.pos.y); + float sf = 1.0f - lf; + float fade = ImClamp((sf - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f); + int a = (int)(hiA * fade); + v.col = IM_COL32(255, 255, 255, (unsigned char)ImClamp(a, 0, 255)); + } + } +} + +// Draw a neumorphic button molded from the sidebar surface itself. +// No contrasting fill — uses only shadows and highlights so the button +// appears to be the exact same material as the sidebar, just shaped. +// Light source: top-left. depth controls the press amount: +// 0.0 = fully raised / convex (normal idle state) +// 0.5 = half-pressed (hover state) +// 1.0 = fully pressed in (selected / clicked) +inline void DrawGlassBevelButton(ImDrawList* dl, ImVec2 mn, ImVec2 mx, + float rnd, float depth = 0.0f, int /*fillAlpha*/ = 18) +{ + float w = mx.x - mn.x; + float h = mx.y - mn.y; + if (w < 1.0f || h < 1.0f) return; + float inv = 1.0f - depth; // 1 raised, 0 pressed + + // ---- Directional bevel + neumorphic glow ---- + // Multiple concentric AddRect outline passes with directional vertex + // coloring. Wider outer passes (expanded rect) create soft shadow glow; + // inner pass gives crisp bevel edge. All use AddRect with rounding so + // every layer follows the rounded corners perfectly — no clip rects needed. + { + float cx = (mn.x + mx.x) * 0.5f; + float cy = (mn.y + mx.y) * 0.5f; + + // Fast directional light factor — algebraic dot-product approximation + // of angular proximity to fixed light at -135°. No trig, no sqrt. + float invHalfW = 2.0f / w; + float invHalfH = 2.0f / h; + auto lightFactor = [cx, cy, invHalfW, invHalfH](float px, float py) -> float { + float nx = (px - cx) * invHalfW; + float ny = (py - cy) * invHalfH; + return ImClamp(0.5f + 0.3536f * (-nx - ny), 0.0f, 1.0f); + }; + + struct BevelPass { float expand; float lineW; float fadeStart; float fadeEnd; }; + BevelPass passes[] = { + { 0.5f, 0.75f, 0.30f, 0.55f }, // Outer glow (thin) + { 0.0f, 0.75f, 0.38f, 0.58f }, // Inner crisp bevel + }; + + for (auto& bp : passes) { + // Compute directional alpha. + // Outer passes fade out when pressed; inner bevel swaps direction. + int hiA, shA; + if (bp.expand > 0.0f) { + float baseHi = (bp.expand > 1.0f) ? 12.0f : 18.0f; + float baseSh = (bp.expand > 1.0f) ? 20.0f : 30.0f; + hiA = (int)(baseHi * inv); + shA = (int)(baseSh * inv); + } else { + hiA = (int)(40.0f * inv + 15.0f * depth); + shA = (int)(45.0f * inv + 60.0f * depth); + } + + ImVec2 pMn(mn.x - bp.expand, mn.y - bp.expand); + ImVec2 pMx(mx.x + bp.expand, mx.y + bp.expand); + float pRnd = rnd + bp.expand; + + // Highlight pass (light-facing edges) + { + int v0 = dl->VtxBuffer.Size; + dl->AddRect(pMn, pMx, IM_COL32(255, 255, 255, 1), pRnd, 0, bp.lineW); + int v1 = dl->VtxBuffer.Size; + for (int i = v0; i < v1; i++) { + ImDrawVert& v = dl->VtxBuffer[i]; + float lf = lightFactor(v.pos.x, v.pos.y); + float fade = ImClamp((lf - bp.fadeStart) / (bp.fadeEnd - bp.fadeStart), 0.0f, 1.0f); + int targetA = (depth < 0.5f) ? hiA : shA; + int a = (int)(targetA * fade); + v.col = (depth < 0.5f) + ? IM_COL32(255, 255, 255, (unsigned char)ImClamp(a, 0, 255)) + : IM_COL32(0, 0, 0, (unsigned char)ImClamp(a, 0, 255)); + } + } + + // Shadow pass (shadow-facing edges) + { + int v0 = dl->VtxBuffer.Size; + dl->AddRect(pMn, pMx, IM_COL32(0, 0, 0, 1), pRnd, 0, bp.lineW); + int v1 = dl->VtxBuffer.Size; + for (int i = v0; i < v1; i++) { + ImDrawVert& v = dl->VtxBuffer[i]; + float lf = lightFactor(v.pos.x, v.pos.y); + float sf = 1.0f - lf; + float fade = ImClamp((sf - bp.fadeStart) / (bp.fadeEnd - bp.fadeStart), 0.0f, 1.0f); + int targetA = (depth < 0.5f) ? shA : hiA; + int a = (int)(targetA * fade); + v.col = (depth < 0.5f) + ? IM_COL32(0, 0, 0, (unsigned char)ImClamp(a, 0, 255)) + : IM_COL32(255, 255, 255, (unsigned char)ImClamp(a, 0, 255)); + } + } + } + } + + // ---- 3. Inset shadow (scales with depth, emanates from all edges inward) ---- + // Uses concentric rounded rects with decreasing alpha to avoid triangle + // interpolation artifacts that occur with single-rect vertex color hacking. + // Cached inset shadow style — refreshed once per theme reload + struct InsetCache { + uint32_t gen = 0; + float threshold, inset, maxAlpha, fadeRatio; + }; + static InsetCache s_ic; + { + uint32_t g = schema::UI().generation(); + if (g != s_ic.gen) { + s_ic.gen = g; + auto rd = [](const char* key, float fb) { + auto e = schema::UI().drawElement("components.sidebar", key); + return e.size >= 0 ? e.size : fb; + }; + s_ic.threshold = rd("inset-shadow-threshold", 0.1f); + s_ic.inset = rd("inset-shadow-inset", 1.0f); + s_ic.maxAlpha = rd("inset-shadow-max-alpha", 140.0f); + s_ic.fadeRatio = rd("inset-shadow-fade-ratio", 0.35f); + } + } + if (depth > s_ic.threshold) { + float baseInset = s_ic.inset; + int shadowMax = (int)(s_ic.maxAlpha * depth); + float fadeRatio = s_ic.fadeRatio; + float bW = mx.x - mn.x - baseInset * 2.0f; + float bH = mx.y - mn.y - baseInset * 2.0f; + if (bW > 0.0f && bH > 0.0f) { + float fadeDepth = ImMin(bW, bH) * fadeRatio; + const int steps = 8; + // Draw inside-out: innermost (lightest) first, then progressively + // larger/darker rects on top. Each outer rect extends further toward + // the edges, adding darkness only at the perimeter. + for (int s = steps - 1; s >= 0; s--) { + float t = (float)s / (float)(steps - 1); // 0 = edge, 1 = deepest + float shrink = baseInset + t * fadeDepth; + ImVec2 sMn(mn.x + shrink, mn.y + shrink); + ImVec2 sMx(mx.x - shrink, mx.y - shrink); + if (sMx.x <= sMn.x || sMx.y <= sMn.y) continue; + float sRnd = ImMax(rnd - shrink, 0.0f); + // Quadratic falloff: darkest at edge (t=0), zero at center (t=1) + float alpha01 = (1.0f - t) * (1.0f - t); + int a = (int)((float)shadowMax * alpha01); + if (a < 1) continue; + dl->AddRectFilled(sMn, sMx, IM_COL32(0, 0, 0, (unsigned char)ImClamp(a, 0, 255)), sRnd); + } + } + } + // (No specular highlight — same matte material as sidebar) +} + +// Render the sidebar navigation. Returns true if the page changed. +// collapsed: when true, sidebar is in icon-only mode (narrow width). +// The caller can toggle collapsed via a reference if a toggle button is desired. +inline bool RenderSidebar(NavPage& current, float sidebarWidth, float contentHeight, + SidebarStatus& status, bool& collapsed) +{ + using namespace material; + bool changed = false; + + // Collect button rects so we can punch holes in the glass panel fill + // to avoid opacity stacking (buttons should be same opacity as sidebar). + struct Rect { ImVec2 mn, mx; float rnd; }; + ImVector buttonRects; + + const auto& S = schema::UISchema::instance(); + + // Read sidebar layout from schema (with fallbacks) + // All TOML values are in logical pixels; multiply by DPI scale + // for correct physical pixel sizing on high-DPI displays. + const float dp = Layout::dpiScale(); + auto sde = [&](const char* key, float fallback) { + auto e = S.drawElement("components.sidebar", key); + return (e.size >= 0 ? e.size : fallback) * dp; + }; + const float sbWidth = sde("width", 160.0f); + const float sbCollapsedWidth = sde("collapsed-width", 64.0f); + const float glassMarginY = sde("glass-margin-y", 6.0f); + const float glassMarginL = sde("glass-margin-left", 6.0f); + const float glassMarginR = sde("glass-margin-right", 2.0f); + const float stripH = sde("strip-height", 20.0f); + const float btnPadCollapsed = sde("button-pad-collapsed", 8.0f); + const float btnPadExpanded = sde("button-pad-expanded", 14.0f); + const float iconHalfSize = sde("icon-half-size", 7.0f); + const float iconLabelGap = sde("icon-label-gap", 8.0f); + const float badgeRadiusDot = sde("badge-radius-dot", 4.0f); + const float badgeRadiusNumber = sde("badge-radius-number", 8.0f); + const float bottomPadding = sde("bottom-padding", 6.0f); + const float exitIconGap = sde("exit-icon-gap", 4.0f); + const float sbSectionLabelPadLeft = sde("section-label-pad-left", 16.0f); + const float sbItemPadX = sde("item-pad-x", 8.0f); + + // Base values for responsive scaling + const float baseItemHeight = sde("item-height", 46.0f); + const float baseNavGap = sde("nav-gap", 20.0f); + const float baseSectionGap = sde("section-gap", 12.0f); + const float baseButtonSpacing = sde("button-spacing", 3.0f); + + // Estimate total sidebar content height at base sizes to detect overflow. + // Fixed chrome: top margin + collapse strip + exit strip + bottom padding + const float fixedChrome = glassMarginY + stripH + stripH + bottomPadding; + // Section labels: 2 sections × (gap + label height + pad) + const float sectionLabelH = 2.0f * (baseSectionGap + 13.0f * dp); + // Nav items: 9 items × (height + spacing) + const float navItemsH = (float)(int)NavPage::Count_ * (baseItemHeight + baseButtonSpacing); + const float baseContentH = fixedChrome + baseNavGap + navItemsH + sectionLabelH; + + // Responsive shrink: if content would overflow, scale down flexible sizes. + // Clamp scale so buttons never shrink below what fits in the minimum + // sidebar height defined in ui.toml ("min-height"). + float sidebarMinHeight = sde("min-height", 360.0f); + float scaleFloor = 0.55f; + if (sidebarMinHeight > fixedChrome) { + float flexH = baseContentH - fixedChrome; + if (flexH > 0.0f) { + float minFlex = sidebarMinHeight - fixedChrome; + scaleFloor = std::max(0.55f, minFlex / flexH); + } + } + float sidebarScale = 1.0f; + if (baseContentH > contentHeight && contentHeight > fixedChrome) { + float flexH = baseContentH - fixedChrome; + float availFlex = contentHeight - fixedChrome; + sidebarScale = std::max(scaleFloor, availFlex / flexH); + } + + const float sbItemHeight = baseItemHeight * sidebarScale; + const float navGap = baseNavGap * sidebarScale; + const float sbSectionGap = baseSectionGap * sidebarScale; + const float buttonSpacing = baseButtonSpacing * sidebarScale; + + // How "expanded" are we? 0.0 = fully collapsed, 1.0 = fully expanded + float expandFrac = (sbWidth > sbCollapsedWidth) + ? (sidebarWidth - sbCollapsedWidth) / (sbWidth - sbCollapsedWidth) + : 1.0f; + if (expandFrac < 0.0f) expandFrac = 0.0f; + if (expandFrac > 1.0f) expandFrac = 1.0f; + bool showLabels = expandFrac > 0.3f; // hide labels during early part of animation + + // Glass panel rounding from responsive schema + float glassRounding = [&]() { + float v = S.drawElement("responsive", "glass-rounding").size; + return (v >= 0 ? v : 8.0f) * dp; + }(); + + ImGui::BeginChild("##Sidebar", ImVec2(sidebarWidth, contentHeight), false, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoBackground); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 wp = ImGui::GetWindowPos(); + + // Glass card background — inset with rounded corners, matching content cards + float sidebarMarginY = glassMarginY; // top & bottom inset + float sidebarMarginL = glassMarginL; // left inset + float sidebarMarginR = glassMarginR; // right inset (tighter on content side) + // Panel bounds + float panelLeft = wp.x + sidebarMarginL; + float panelRight = wp.x + sidebarWidth - sidebarMarginR; + + // Defer glass panel drawing until we know content height (channel 0 = background) + ImDrawListSplitter splitter; + splitter.Split(dl, 2); + splitter.SetCurrentChannel(dl, 1); + + // Top padding (just the margin — collapse button sits at panel top) + ImGui::Dummy(ImVec2(0, sidebarMarginY)); + + // ---- Collapse toggle — flush strip at top of sidebar panel ---- + { + ImVec2 savedCursor = ImGui::GetCursorScreenPos(); + float rnd = glassRounding; + // Strip spans full panel width, sits inside top of panel + float stripX = panelLeft; + float stripW = panelRight - panelLeft; + float stripY = wp.y + sidebarMarginY; + ImVec2 stripMin(stripX, stripY); + ImVec2 stripMax(stripX + stripW, stripY + stripH); + + ImGui::SetCursorScreenPos(stripMin); + if (ImGui::InvisibleButton("##SidebarCollapse", ImVec2(stripW, stripH))) { + collapsed = !collapsed; + } + bool btnHover = ImGui::IsItemHovered(); + + // Draw strip background — flush with panel top (no extra rounding, blends in) + ImU32 stripBg = btnHover ? schema::UI().resolveColor("var(--sidebar-hover)", IM_COL32(255, 255, 255, 25)) : IM_COL32(0, 0, 0, 0); + if (btnHover) { + dl->AddRectFilled(stripMin, stripMax, stripBg, + rnd, ImDrawFlags_RoundCornersTop); + } + // Subtle bottom separator + dl->AddLine(ImVec2(stripMin.x + rnd * 0.5f, stripMax.y), + ImVec2(stripMax.x - rnd * 0.5f, stripMax.y), + schema::UI().resolveColor("var(--sidebar-divider)", IM_COL32(255, 255, 255, 15)), 1.0f); + + if (btnHover) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Chevron icon centered in strip + ImU32 iconCol = btnHover ? OnSurface() : schema::UI().resolveColor("var(--sidebar-icon)", IM_COL32(255, 255, 255, 60)); + float cx = stripX + stripW * 0.5f; + float cy = stripY + stripH * 0.5f; + { + ImFont* iconFont = Type().iconSmall(); + const char* chevIcon = collapsed ? ICON_MD_CHEVRON_RIGHT : ICON_MD_CHEVRON_LEFT; + ImVec2 chevSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, chevIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - chevSz.x * 0.5f, cy - chevSz.y * 0.5f), iconCol, chevIcon); + } + + ImGui::SetCursorScreenPos(savedCursor); // restore — toggle is an overlay + } + + // Gap between collapse divider and first nav item + ImGui::Dummy(ImVec2(0, navGap)); + + // ---- Navigation items ---- + for (int i = 0; i < (int)NavPage::Count_; ++i) { + const NavItem& item = kNavItems[i]; + + // Section label (only when expanded) + if (item.section_label && showLabels) { + ImGui::Dummy(ImVec2(0, sbSectionGap)); + ImFont* olFont = Type().overline(); + float labelY = ImGui::GetCursorScreenPos().y; + ImVec4 olCol = ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium()); + olCol.w *= expandFrac; + dl->AddText(olFont, olFont->LegacySize, + ImVec2(wp.x + sbSectionLabelPadLeft, labelY), + ImGui::ColorConvertFloat4ToU32(olCol), item.section_label); + ImGui::Dummy(ImVec2(0, olFont->LegacySize + 2.0f)); + } else if (item.section_label && !showLabels) { + // Collapsed: thin separator instead of label + ImGui::Dummy(ImVec2(0, sbSectionGap * 0.4f)); + float sepY2 = ImGui::GetCursorScreenPos().y; + dl->AddLine(ImVec2(wp.x + btnPadCollapsed, sepY2), ImVec2(wp.x + sidebarWidth - btnPadCollapsed, sepY2), + Divider(), 1.0f); + ImGui::Dummy(ImVec2(0, sbSectionGap * 0.4f)); + } + + bool selected = (current == item.page); + + ImGui::PushID(i); + + float itemH = sbItemHeight; + float btnRnd = itemH * 0.22f; // moderate rounding + float btnPadX = collapsed ? btnPadCollapsed : btnPadExpanded; // tighter padding when collapsed + ImVec2 cursor = ImGui::GetCursorScreenPos(); + // Keep button height constant (itemH) so sidebar content height doesn't + // change during collapse animation, which would destabilize centering. + float btnH = itemH; + // Item bounds for icon/label placement (inset) + ImVec2 itemMin(wp.x + sbItemPadX, cursor.y); + ImVec2 itemMax(wp.x + sidebarWidth - sbItemPadX, cursor.y + btnH); + // Button bounds — inset from panel edges for spacing + ImVec2 indMin(panelLeft + btnPadX, cursor.y); + ImVec2 indMax(panelRight - btnPadX, cursor.y + btnH); + + // All buttons are embossed; hover presses halfway, selected presses fully + bool hovered = material::IsRectHovered(indMin, indMax); + { + float btnDepth = 0.0f; + if (selected) btnDepth = 1.0f; + else if (hovered) btnDepth = 0.5f; + + // Theme effects behind active button + if (selected) { + auto& fx = effects::ThemeEffects::instance(); + fx.drawGlowPulse(dl, indMin, indMax, btnRnd); + fx.drawEdgeTrace(dl, indMin, indMax, btnRnd); + fx.drawEmberRise(dl, indMin, indMax); + fx.drawShimmer(dl, indMin, indMax, btnRnd); + fx.drawGradientBorderShift(dl, indMin, indMax, btnRnd); + } + + DrawGlassCutout(dl, indMin, indMax, btnRnd, 1.5f); + DrawGlassBevelButton(dl, indMin, indMax, btnRnd, btnDepth, 18); + buttonRects.push_back({indMin, indMax, btnRnd}); + } + + if (hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + // Click detection + if (hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + current = item.page; + changed = true; + } + + // Icon + label — centered horizontally within button bounds + float iconS = iconHalfSize; // icon half-size in pixels + float iconCY = cursor.y + btnH * 0.5f; + float textY = cursor.y + (btnH - ImGui::GetTextLineHeight()) * 0.5f; + ImU32 textCol = selected ? Primary() : OnSurfaceMedium(); + + if (showLabels) { + // Measure total width of icon + gap + label, then center + ImFont* font = selected ? Type().subtitle2() : Type().body2(); + float gap = iconLabelGap; + ImVec2 labelSz = font->CalcTextSizeA(font->LegacySize, 1000.0f, 0.0f, item.label); + float totalW = iconS * 2.0f + gap + labelSz.x; + float btnCX = (indMin.x + indMax.x) * 0.5f; + float startX = btnCX - totalW * 0.5f; + + float iconCX = startX + iconS; + DrawNavIcon(dl, item.page, iconCX, iconCY, iconS, textCol); + + float labelX = startX + iconS * 2.0f + gap; + ImVec4 lc = ImGui::ColorConvertU32ToFloat4(textCol); + lc.w *= expandFrac; + dl->AddText(font, font->LegacySize, ImVec2(labelX, textY), + ImGui::ColorConvertFloat4ToU32(lc), item.label); + } else { + float iconCX = (indMin.x + indMax.x) * 0.5f; + DrawNavIcon(dl, item.page, iconCX, iconCY, iconS, textCol); + } + + // Tooltip when collapsed + hovered + if (!showLabels && hovered) { + ImGui::SetTooltip("%s", item.label); + } + + // ---- Badge indicator ---- + { + int badgeCount = 0; + bool dotOnly = false; + ImU32 badgeCol = Primary(); + ImU32 badgeTextCol = OnPrimary(); + + if (item.page == NavPage::History && status.unconfirmedTxCount > 0) { + badgeCount = status.unconfirmedTxCount; + badgeCol = Warning(); + badgeTextCol = OnWarning(); + } else if (item.page == NavPage::Mining && status.miningActive) { + dotOnly = true; + badgeCol = Success(); + } else if (item.page == NavPage::Peers && status.peerCount > 0) { + badgeCount = status.peerCount; + } + + if (badgeCount > 0 || dotOnly) { + float badgeR = dotOnly ? badgeRadiusDot : badgeRadiusNumber; + float badgeX, badgeY; + + // Upper-right corner of button, offset from edges + badgeX = indMax.x - badgeR - 6.0f; + badgeY = indMin.y + badgeR + 5.0f; + + dl->AddCircleFilled(ImVec2(badgeX, badgeY), badgeR, badgeCol); + + if (!dotOnly && showLabels) { + char buf[16]; + snprintf(buf, sizeof(buf), "%d", badgeCount > 99 ? 99 : badgeCount); + ImFont* capFont = Type().caption(); + ImVec2 ts = capFont->CalcTextSizeA(capFont->LegacySize, 1000.0f, 0.0f, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(badgeX - ts.x * 0.5f, badgeY - ts.y * 0.5f), + badgeTextCol, buf); + } + } + } + + ImGui::Dummy(ImVec2(sidebarWidth, btnH + buttonSpacing)); // extra vertical spacing between buttons + ImGui::PopID(); + } + + // (Pill indicator removed — glass bevel on active button is sufficient) + + // Reserve space for exit strip at panel bottom (drawn as overlay below) + ImGui::Dummy(ImVec2(0, stripH)); + + // ---- Keyboard navigation ---- + if (!ImGui::GetIO().WantTextInput && !ImGui::GetIO().KeyCtrl) { + int idx = static_cast(current); + bool nav = false; + + if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) || ImGui::IsKeyPressed(ImGuiKey_K)) { + if (idx > 0) { idx--; nav = true; } + } + if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) || ImGui::IsKeyPressed(ImGuiKey_J)) { + if (idx < (int)NavPage::Count_ - 1) { idx++; nav = true; } + } + + // Toggle collapse with [ key + if (ImGui::IsKeyPressed(ImGuiKey_LeftBracket)) { + collapsed = !collapsed; + } + + if (nav) { + current = static_cast(idx); + changed = true; + } + } + + // Bottom padding + ImGui::Dummy(ImVec2(0, bottomPadding)); + + // Measure total sidebar content height + float totalContentEndY = ImGui::GetCursorScreenPos().y; + + // Draw glass panel background — capped to sidebar bounds so corners are visible + float panelBottomY = totalContentEndY; + float panelTopY = wp.y + sidebarMarginY; + // Clamp bottom so rounded corners are never clipped by the child window + float maxPanelBottom = wp.y + contentHeight - sidebarMarginY; + if (panelBottomY > maxPanelBottom) panelBottomY = maxPanelBottom; + splitter.SetCurrentChannel(dl, 0); + { + float rnd = glassRounding; + ImVec2 panelMin(panelLeft, panelTopY); + ImVec2 panelMax(panelRight, panelBottomY); + GlassPanelSpec sidebarGlass; + sidebarGlass.rounding = rnd; + sidebarGlass.fillAlpha = 14; + sidebarGlass.borderAlpha = 25; + sidebarGlass.borderWidth = 1.0f; + // Record vertex range before drawing the glass panel fill + int glassVtx0 = dl->VtxBuffer.Size; + DrawGlassPanel(dl, panelMin, panelMax, sidebarGlass); + int glassVtx1 = dl->VtxBuffer.Size; + + // Punch holes: zero out glass panel vertices that fall inside + // any button rect so the button area doesn't double-up opacity. + for (int vi = glassVtx0; vi < glassVtx1; vi++) { + ImDrawVert& v = dl->VtxBuffer[vi]; + for (int bi = 0; bi < buttonRects.Size; bi++) { + const Rect& r = buttonRects[bi]; + // Inset test slightly (0.5px) to avoid killing edge pixels + if (v.pos.x > r.mn.x + 0.5f && v.pos.x < r.mx.x - 0.5f && + v.pos.y > r.mn.y + 0.5f && v.pos.y < r.mx.y - 0.5f) { + v.col = (v.col & 0x00FFFFFFu); // zero alpha + break; + } + } + } + } + + // ---- Exit button — flush strip at bottom of sidebar panel ---- + splitter.SetCurrentChannel(dl, 1); + { + float rnd = glassRounding; + float exitStripH = stripH; + float exitStripX = panelLeft; + float exitStripW = panelRight - panelLeft; + float exitStripY = panelBottomY - exitStripH; + ImVec2 exitMin(exitStripX, exitStripY); + ImVec2 exitMax(exitStripX + exitStripW, exitStripY + exitStripH); + + ImGui::SetCursorScreenPos(exitMin); + if (ImGui::InvisibleButton("##ExitBtn", ImVec2(exitStripW, exitStripH))) { + status.exitClicked = true; + } + bool exitHover = ImGui::IsItemHovered(); + + // Hover highlight with rounded bottom corners (matching panel) + if (exitHover) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + dl->AddRectFilled(exitMin, exitMax, schema::UI().resolveColor("var(--sidebar-hover)", IM_COL32(255, 255, 255, 25)), + rnd, ImDrawFlags_RoundCornersBottom); + } + + // Subtle top separator + dl->AddLine(ImVec2(exitMin.x + rnd * 0.5f, exitMin.y), + ImVec2(exitMax.x - rnd * 0.5f, exitMin.y), + schema::UI().resolveColor("var(--sidebar-divider)", IM_COL32(255, 255, 255, 15)), 1.0f); + + // Exit icon (+ label when expanded) centered in strip + ImU32 exitCol = exitHover ? Error() : schema::UI().resolveColor("var(--sidebar-icon)", IM_COL32(255, 255, 255, 60)); + float cx = exitStripX + exitStripW * 0.5f; + float cy = exitStripY + exitStripH * 0.5f; + + if (showLabels) { + ImFont* iconFont = Type().iconSmall(); + ImFont* font = Type().caption(); + const char* exitIcon = ICON_MD_EXIT_TO_APP; + ImVec2 iconSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, exitIcon); + ImVec2 labelSz = font->CalcTextSizeA(font->LegacySize, 1000.0f, 0.0f, "Exit"); + float gap = exitIconGap; + float totalW = iconSz.x + gap + labelSz.x; + float startX = cx - totalW * 0.5f; + + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(startX, cy - iconSz.y * 0.5f), exitCol, exitIcon); + + ImVec4 lc = ImGui::ColorConvertU32ToFloat4(exitCol); + lc.w *= expandFrac; + dl->AddText(font, font->LegacySize, + ImVec2(startX + iconSz.x + gap, cy - labelSz.y * 0.5f), + ImGui::ColorConvertFloat4ToU32(lc), "Exit"); + } else { + ImFont* iconFont = Type().iconSmall(); + const char* exitIcon = ICON_MD_EXIT_TO_APP; + ImVec2 iconSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, exitIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - iconSz.x * 0.5f, cy - iconSz.y * 0.5f), + exitCol, exitIcon); + } + + if (!showLabels && exitHover) { + ImGui::SetTooltip("Exit"); + } + } + + splitter.Merge(dl); + + ImGui::EndChild(); + return changed; +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/theme.cpp b/src/ui/theme.cpp new file mode 100644 index 0000000..2e1148e --- /dev/null +++ b/src/ui/theme.cpp @@ -0,0 +1,384 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "theme.h" +#include "material/color_theme.h" +#include "schema/ui_schema.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +// ============================================================================ +// Current Acrylic Theme State +// ============================================================================ + +static AcrylicTheme s_currentAcrylicTheme; +static bool s_acrylicThemeInitialized = false; + +// ============================================================================ +// Acrylic Theme Presets +// ============================================================================ + +AcrylicTheme GetDragonXAcrylicTheme() +{ + AcrylicTheme theme; + + // Sidebar: Deep navy tint (DragonX brand) + // #1B2432 ≈ (0.106, 0.141, 0.196) + theme.sidebar.tintColor = ImVec4(0.11f, 0.14f, 0.20f, 1.0f); + theme.sidebar.tintOpacity = 0.85f; + theme.sidebar.luminosityOpacity = 0.4f; + theme.sidebar.blurRadius = 40.0f; + theme.sidebar.noiseOpacity = 0.02f; + theme.sidebar.fallbackColor = ImVec4(0.07f, 0.08f, 0.13f, 0.85f); + theme.sidebar.enabled = true; + + // Popups: Dark navy with subtle blue tint + theme.popup.tintColor = ImVec4(0.09f, 0.11f, 0.16f, 1.0f); + theme.popup.tintOpacity = 0.80f; + theme.popup.luminosityOpacity = 0.5f; + theme.popup.blurRadius = 30.0f; + theme.popup.noiseOpacity = 0.02f; + theme.popup.fallbackColor = ImVec4(0.09f, 0.11f, 0.16f, 0.88f); + theme.popup.enabled = true; + + // Cards: Subtle navy tint + theme.card.tintColor = ImVec4(0.10f, 0.13f, 0.18f, 1.0f); + theme.card.tintOpacity = 0.65f; + theme.card.luminosityOpacity = 0.6f; + theme.card.blurRadius = 20.0f; + theme.card.noiseOpacity = 0.015f; + theme.card.fallbackColor = ImVec4(0.10f, 0.13f, 0.18f, 0.80f); + theme.card.enabled = true; + + // Context menus: Dark navy, crisp + theme.menu.tintColor = ImVec4(0.08f, 0.09f, 0.14f, 1.0f); + theme.menu.tintOpacity = 0.88f; + theme.menu.luminosityOpacity = 0.45f; + theme.menu.blurRadius = 25.0f; + theme.menu.noiseOpacity = 0.02f; + theme.menu.fallbackColor = ImVec4(0.08f, 0.09f, 0.14f, 0.88f); + theme.menu.enabled = true; + + // Tooltips: Very transparent navy + theme.tooltip.tintColor = ImVec4(0.07f, 0.08f, 0.12f, 1.0f); + theme.tooltip.tintOpacity = 0.75f; + theme.tooltip.luminosityOpacity = 0.5f; + theme.tooltip.blurRadius = 15.0f; + theme.tooltip.noiseOpacity = 0.01f; + theme.tooltip.fallbackColor = ImVec4(0.07f, 0.08f, 0.12f, 0.95f); + theme.tooltip.enabled = true; + + return theme; +} + +AcrylicTheme GetDarkAcrylicTheme() +{ + AcrylicTheme theme; + + // Sidebar: Neutral dark + theme.sidebar.tintColor = ImVec4(0.12f, 0.12f, 0.14f, 1.0f); + theme.sidebar.tintOpacity = 0.80f; + theme.sidebar.luminosityOpacity = 0.5f; + theme.sidebar.blurRadius = 35.0f; + theme.sidebar.noiseOpacity = 0.02f; + theme.sidebar.fallbackColor = ImVec4(0.12f, 0.12f, 0.14f, 0.85f); + theme.sidebar.enabled = true; + + // Popups + theme.popup.tintColor = ImVec4(0.14f, 0.14f, 0.16f, 1.0f); + theme.popup.tintOpacity = 0.78f; + theme.popup.luminosityOpacity = 0.5f; + theme.popup.blurRadius = 30.0f; + theme.popup.noiseOpacity = 0.02f; + theme.popup.fallbackColor = ImVec4(0.14f, 0.14f, 0.16f, 0.88f); + theme.popup.enabled = true; + + // Cards + theme.card.tintColor = ImVec4(0.15f, 0.15f, 0.17f, 1.0f); + theme.card.tintOpacity = 0.65f; + theme.card.luminosityOpacity = 0.55f; + theme.card.blurRadius = 20.0f; + theme.card.noiseOpacity = 0.015f; + theme.card.fallbackColor = ImVec4(0.15f, 0.15f, 0.17f, 0.80f); + theme.card.enabled = true; + + // Menus + theme.menu.tintColor = ImVec4(0.12f, 0.12f, 0.14f, 1.0f); + theme.menu.tintOpacity = 0.85f; + theme.menu.luminosityOpacity = 0.45f; + theme.menu.blurRadius = 25.0f; + theme.menu.noiseOpacity = 0.02f; + theme.menu.fallbackColor = ImVec4(0.12f, 0.12f, 0.14f, 0.88f); + theme.menu.enabled = true; + + // Tooltips + theme.tooltip.tintColor = ImVec4(0.10f, 0.10f, 0.12f, 1.0f); + theme.tooltip.tintOpacity = 0.75f; + theme.tooltip.luminosityOpacity = 0.5f; + theme.tooltip.blurRadius = 15.0f; + theme.tooltip.noiseOpacity = 0.01f; + theme.tooltip.fallbackColor = ImVec4(0.10f, 0.10f, 0.12f, 0.95f); + theme.tooltip.enabled = true; + + return theme; +} + +AcrylicTheme GetLightAcrylicTheme() +{ + AcrylicTheme theme; + + // Sidebar: Light with slight tint + theme.sidebar.tintColor = ImVec4(0.96f, 0.96f, 0.98f, 1.0f); + theme.sidebar.tintOpacity = 0.82f; + theme.sidebar.luminosityOpacity = 0.7f; + theme.sidebar.blurRadius = 30.0f; + theme.sidebar.noiseOpacity = 0.015f; + theme.sidebar.fallbackColor = ImVec4(0.96f, 0.96f, 0.98f, 0.85f); + theme.sidebar.enabled = true; + + // Popups + theme.popup.tintColor = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + theme.popup.tintOpacity = 0.85f; + theme.popup.luminosityOpacity = 0.75f; + theme.popup.blurRadius = 25.0f; + theme.popup.noiseOpacity = 0.015f; + theme.popup.fallbackColor = ImVec4(0.98f, 0.98f, 1.0f, 0.88f); + theme.popup.enabled = true; + + // Cards + theme.card.tintColor = ImVec4(0.98f, 0.98f, 1.0f, 1.0f); + theme.card.tintOpacity = 0.70f; + theme.card.luminosityOpacity = 0.75f; + theme.card.blurRadius = 18.0f; + theme.card.noiseOpacity = 0.01f; + theme.card.fallbackColor = ImVec4(0.98f, 0.98f, 1.0f, 0.80f); + theme.card.enabled = true; + + // Menus + theme.menu.tintColor = ImVec4(0.98f, 0.98f, 1.0f, 1.0f); + theme.menu.tintOpacity = 0.88f; + theme.menu.luminosityOpacity = 0.7f; + theme.menu.blurRadius = 22.0f; + theme.menu.noiseOpacity = 0.015f; + theme.menu.fallbackColor = ImVec4(0.98f, 0.98f, 1.0f, 0.88f); + theme.menu.enabled = true; + + // Tooltips + theme.tooltip.tintColor = ImVec4(0.95f, 0.95f, 0.97f, 1.0f); + theme.tooltip.tintOpacity = 0.80f; + theme.tooltip.luminosityOpacity = 0.7f; + theme.tooltip.blurRadius = 12.0f; + theme.tooltip.noiseOpacity = 0.01f; + theme.tooltip.fallbackColor = ImVec4(0.95f, 0.95f, 0.97f, 0.95f); + theme.tooltip.enabled = true; + + return theme; +} + +const AcrylicTheme& GetCurrentAcrylicTheme() +{ + if (!s_acrylicThemeInitialized) { + s_currentAcrylicTheme = GetDragonXAcrylicTheme(); + s_acrylicThemeInitialized = true; + } + return s_currentAcrylicTheme; +} + +void SetCurrentAcrylicTheme(const AcrylicTheme& theme) +{ + s_currentAcrylicTheme = theme; + s_acrylicThemeInitialized = true; +} + +// ============================================================================ +// ImGui Theme Functions +// ============================================================================ + +void SetDragonXTheme() +{ + ImGuiStyle& style = ImGui::GetStyle(); + ImVec4* colors = style.Colors; + const auto& S = schema::UI(); + + // DragonX brand colors: + // Primary: Red (#F64740) + // Background: Navy (#121420 / #1B2432) + // Text: Blue-gray (#BFD1E5) + + // Main background colors — navy palette + colors[ImGuiCol_WindowBg] = ImVec4(0.07f, 0.08f, 0.13f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.11f, 0.14f, 0.20f, 1.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.18f, 0.25f, 0.98f); + + // Borders + colors[ImGuiCol_Border] = ImVec4(1.00f, 1.00f, 1.00f, 0.12f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + + // Frame backgrounds (inputs, checkboxes, etc.) — glass-card style + colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); + colors[ImGuiCol_FrameBgActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.15f); + + // Title bar — navy + colors[ImGuiCol_TitleBg] = ImVec4(0.11f, 0.14f, 0.20f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.07f, 0.08f, 0.13f, 0.75f); + + // Menu bar — navy + colors[ImGuiCol_MenuBarBg] = ImVec4(0.11f, 0.14f, 0.20f, 1.00f); + + // Scrollbar — minimal glass style + colors[ImGuiCol_ScrollbarBg] = ImVec4(0, 0, 0, 0); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(1.0f, 1.0f, 1.0f, 15.0f / 255.0f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(1.0f, 1.0f, 1.0f, 30.0f / 255.0f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(1.0f, 1.0f, 1.0f, 45.0f / 255.0f); + + // Checkmarks, sliders — DragonX red + colors[ImGuiCol_CheckMark] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.97f, 0.48f, 0.46f, 1.00f); + + // Buttons — red accent + colors[ImGuiCol_Button] = ImVec4(0.96f, 0.28f, 0.25f, 0.80f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.44f, 0.10f, 0.03f, 1.00f); + + // Headers (collapsing headers, tree nodes, selectable, menu items) + colors[ImGuiCol_Header] = ImVec4(0.96f, 0.28f, 0.25f, 0.50f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.96f, 0.28f, 0.25f, 0.70f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + + // Separator — blue-gray + colors[ImGuiCol_Separator] = ImVec4(0.75f, 0.82f, 0.90f, 0.25f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.96f, 0.28f, 0.25f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + + // Resize grip + colors[ImGuiCol_ResizeGrip] = ImVec4(0.96f, 0.28f, 0.25f, 0.25f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.96f, 0.28f, 0.25f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.96f, 0.28f, 0.25f, 0.95f); + + // Tabs — navy + red accent + colors[ImGuiCol_Tab] = ImVec4(0.14f, 0.18f, 0.27f, 0.86f); + colors[ImGuiCol_TabHovered] = ImVec4(0.96f, 0.28f, 0.25f, 0.90f); + colors[ImGuiCol_TabSelected] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_TabSelectedOverline] = ImVec4(0.75f, 0.82f, 0.90f, 1.00f); + colors[ImGuiCol_TabDimmed] = ImVec4(0.09f, 0.11f, 0.16f, 0.97f); + colors[ImGuiCol_TabDimmedSelected] = ImVec4(0.44f, 0.10f, 0.03f, 1.00f); + + // Plot colors — red accent, blue-gray secondary + colors[ImGuiCol_PlotLines] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.75f, 0.82f, 0.90f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.96f, 0.28f, 0.25f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.75f, 0.82f, 0.90f, 1.00f); + + // Tables — navy palette + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.14f, 0.18f, 0.27f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.75f, 0.82f, 0.90f, 0.30f); + colors[ImGuiCol_TableBorderLight] = ImVec4(0.75f, 0.82f, 0.90f, 0.15f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.75f, 0.82f, 0.90f, 0.03f); + + // Text — blue-gray + colors[ImGuiCol_Text] = ImVec4(0.75f, 0.82f, 0.90f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.55f, 0.64f, 0.74f, 0.60f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.96f, 0.28f, 0.25f, 0.43f); + + // Drag/drop — red accent + colors[ImGuiCol_DragDropTarget] = ImVec4(0.96f, 0.28f, 0.25f, 0.90f); + + // Navigation highlight + colors[ImGuiCol_NavCursor] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_NavWindowingHighlight]= ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + + // Modal window dim + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); + + // Style adjustments (from UISchema) + auto brElem = S.drawElement("style", "border-radius"); + style.WindowRounding = brElem.extraFloats.count("window") ? brElem.extraFloats.at("window") : 6.0f; + style.ChildRounding = brElem.extraFloats.count("child") ? brElem.extraFloats.at("child") : 4.0f; + style.FrameRounding = brElem.extraFloats.count("frame") ? brElem.extraFloats.at("frame") : 4.0f; + style.PopupRounding = brElem.extraFloats.count("popup") ? brElem.extraFloats.at("popup") : 4.0f; + style.ScrollbarRounding = brElem.extraFloats.count("scrollbar") ? brElem.extraFloats.at("scrollbar") : 4.0f; + style.GrabRounding = brElem.extraFloats.count("grab") ? brElem.extraFloats.at("grab") : 4.0f; + style.TabRounding = brElem.extraFloats.count("tab") ? brElem.extraFloats.at("tab") : 4.0f; + + style.WindowTitleAlign = ImVec2(0.5f, 0.5f); + auto sElem = [&](const char* key, float fb) { + float v = S.drawElement("style", key).size; + return v >= 0 ? v : fb; + }; + style.WindowPadding = ImVec2(sElem("window-padding-x", 10.0f), sElem("window-padding-y", 10.0f)); + style.FramePadding = ImVec2(sElem("frame-padding-x", 8.0f), sElem("frame-padding-y", 4.0f)); + style.ItemSpacing = ImVec2(sElem("item-spacing-x", 8.0f), sElem("item-spacing-y", 6.0f)); + style.ItemInnerSpacing = ImVec2(sElem("item-inner-spacing-x", 6.0f), sElem("item-inner-spacing-y", 4.0f)); + style.IndentSpacing = sElem("indent-spacing", 20.0f); + + style.ScrollbarSize = sElem("scrollbar-size", 6.0f); + style.GrabMinSize = sElem("grab-min-size", 8.0f); + + auto bwElem = S.drawElement("style", "border-width"); + style.WindowBorderSize = bwElem.extraFloats.count("window") ? bwElem.extraFloats.at("window") : 1.0f; + style.ChildBorderSize = bwElem.extraFloats.count("child") ? bwElem.extraFloats.at("child") : 1.0f; + style.PopupBorderSize = bwElem.extraFloats.count("popup") ? bwElem.extraFloats.at("popup") : 1.0f; + style.FrameBorderSize = bwElem.extraFloats.count("frame") ? bwElem.extraFloats.at("frame") : 0.0f; + style.TabBorderSize = 0.0f; + + style.AntiAliasedLines = true; + style.AntiAliasedFill = true; + + // Set matching acrylic theme + SetCurrentAcrylicTheme(GetDragonXAcrylicTheme()); +} + +// ============================================================================ +// Material Design Theme Functions +// ============================================================================ + +void SetDragonXMaterialTheme() +{ + material::ApplyColorThemeToImGui(material::GetDragonXColorTheme()); + SetCurrentAcrylicTheme(GetDragonXAcrylicTheme()); +} + +void SetDarkTheme() +{ + material::ApplyColorThemeToImGui(material::GetMaterialDarkTheme()); + SetCurrentAcrylicTheme(GetDarkAcrylicTheme()); +} + +void SetLightTheme() +{ + material::ApplyColorThemeToImGui(material::GetMaterialLightTheme()); + SetCurrentAcrylicTheme(GetLightAcrylicTheme()); +} + +bool SetThemeById(const std::string& themeId) +{ + if (themeId == "dragonx") { + material::ApplyColorThemeToImGui(material::GetDragonXColorTheme()); + SetCurrentAcrylicTheme(GetDragonXAcrylicTheme()); + return true; + } else if (themeId == "dark") { + material::ApplyColorThemeToImGui(material::GetMaterialDarkTheme()); + SetCurrentAcrylicTheme(GetDarkAcrylicTheme()); + return true; + } else if (themeId == "light") { + material::ApplyColorThemeToImGui(material::GetMaterialLightTheme()); + SetCurrentAcrylicTheme(GetLightAcrylicTheme()); + return true; + } + + // Theme not found - fall back to DragonX + material::ApplyColorThemeToImGui(material::GetDragonXColorTheme()); + SetCurrentAcrylicTheme(GetDragonXAcrylicTheme()); + return false; +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/theme.h b/src/ui/theme.h new file mode 100644 index 0000000..86e60cd --- /dev/null +++ b/src/ui/theme.h @@ -0,0 +1,93 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "effects/acrylic.h" +#include "material/color_theme.h" +#include + +namespace dragonx { +namespace ui { + +// ============================================================================ +// Acrylic Theme Presets +// ============================================================================ + +/** + * @brief Collection of acrylic parameters for different UI elements + */ +struct AcrylicTheme { + effects::AcrylicParams sidebar; // Navigation sidebar + effects::AcrylicParams popup; // Dialogs, modals + effects::AcrylicParams card; // Cards, panels + effects::AcrylicParams menu; // Context menus + effects::AcrylicParams tooltip; // Tooltips +}; + +/** + * @brief Get the DragonX branded acrylic theme + */ +AcrylicTheme GetDragonXAcrylicTheme(); + +/** + * @brief Get the dark acrylic theme + */ +AcrylicTheme GetDarkAcrylicTheme(); + +/** + * @brief Get the light acrylic theme + */ +AcrylicTheme GetLightAcrylicTheme(); + +/** + * @brief Get acrylic theme matching current ImGui theme + */ +const AcrylicTheme& GetCurrentAcrylicTheme(); + +/** + * @brief Set the current acrylic theme + */ +void SetCurrentAcrylicTheme(const AcrylicTheme& theme); + +// ============================================================================ +// ImGui Theme Functions +// ============================================================================ + +/** + * @brief Apply the DragonX Material Design theme + * + * Uses Material Design 2 color system with DragonX red primary color. + * This is the recommended theme for DragonX wallet. + */ +void SetDragonXMaterialTheme(); + +/** + * @brief Apply the DragonX legacy theme (deprecated) + * + * Legacy green-based theme. Use SetDragonXMaterialTheme() instead. + */ +void SetDragonXTheme(); + +/** + * @brief Apply dark theme variant (Material Design) + */ +void SetDarkTheme(); + +/** + * @brief Apply light theme variant (Material Design) + */ +void SetLightTheme(); + +/** + * @brief Apply a theme by its ID (filename stem) + * + * Loads theme from res/themes/{id}.json. Falls back to dragonx theme if not found. + * @param themeId Theme identifier like "dragonx", "dark", "light", "ocean-blue" + * @return true if theme was loaded successfully + */ +bool SetThemeById(const std::string& themeId); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/theme_loader.cpp b/src/ui/theme_loader.cpp new file mode 100644 index 0000000..addf2a4 --- /dev/null +++ b/src/ui/theme_loader.cpp @@ -0,0 +1,353 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "theme_loader.h" +#include "schema/color_var_resolver.h" + +#include +#include + +namespace dragonx { +namespace ui { + +// ============================================================================ +// Color Parsing +// ============================================================================ + +bool ThemeLoader::parseHexColor(const std::string& hexStr, ImU32& outColor) +{ + if (hexStr.empty()) return false; + + std::string hex = hexStr; + + // Remove leading # or 0x + if (hex[0] == '#') { + hex = hex.substr(1); + } else if (hex.size() > 2 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) { + hex = hex.substr(2); + } + + // Validate length (6 for RGB, 8 for RGBA) + if (hex.size() != 6 && hex.size() != 8) { + return false; + } + + // Validate hex characters + for (char c : hex) { + if (!std::isxdigit(static_cast(c))) { + return false; + } + } + + // Parse hex value + unsigned long value = std::strtoul(hex.c_str(), nullptr, 16); + + if (hex.size() == 6) { + // RGB format: 0xRRGGBB -> IM_COL32(R, G, B, 255) + uint8_t r = (value >> 16) & 0xFF; + uint8_t g = (value >> 8) & 0xFF; + uint8_t b = value & 0xFF; + outColor = IM_COL32(r, g, b, 255); + } else { + // RGBA format: 0xRRGGBBAA -> IM_COL32(R, G, B, A) + uint8_t r = (value >> 24) & 0xFF; + uint8_t g = (value >> 16) & 0xFF; + uint8_t b = (value >> 8) & 0xFF; + uint8_t a = value & 0xFF; + outColor = IM_COL32(r, g, b, a); + } + + return true; +} + +std::string ThemeLoader::colorToHexString(ImU32 color, bool includeAlpha) +{ + uint8_t r = (color >> IM_COL32_R_SHIFT) & 0xFF; + uint8_t g = (color >> IM_COL32_G_SHIFT) & 0xFF; + uint8_t b = (color >> IM_COL32_B_SHIFT) & 0xFF; + uint8_t a = (color >> IM_COL32_A_SHIFT) & 0xFF; + + char buf[16]; + if (includeAlpha || a != 255) { + snprintf(buf, sizeof(buf), "0x%02X%02X%02X%02X", r, g, b, a); + } else { + snprintf(buf, sizeof(buf), "0x%02X%02X%02X", r, g, b); + } + return std::string(buf); +} + +// ============================================================================ +// Multi-format Color Parsing +// ============================================================================ + +bool ThemeLoader::parseColorString(const std::string& str, ImU32& outColor) +{ + if (str.empty()) return false; + + // Try #hex / 0xhex first (handles both formats) + if (parseHexColor(str, outColor)) return true; + + // Try rgba(r,g,b,a) + if (schema::ColorVarResolver::parseRgba(str, outColor)) return true; + + // "transparent" + if (str == "transparent") { + outColor = IM_COL32(0, 0, 0, 0); + return true; + } + + return false; +} + +// ============================================================================ +// Luminance Calculation +// ============================================================================ + +float ThemeLoader::getLuminance(ImU32 color) +{ + // Extract RGB components (0-255) + float r = ((color >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float g = ((color >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float b = ((color >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + + // Convert to linear RGB (sRGB gamma correction) + auto linearize = [](float c) { + return c <= 0.03928f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); + }; + + r = linearize(r); + g = linearize(g); + b = linearize(b); + + // Calculate relative luminance (ITU-R BT.709) + return 0.2126f * r + 0.7152f * g + 0.0722f * b; +} + +// ============================================================================ +// Default Color Computation +// ============================================================================ + +void ThemeLoader::computeDefaults(material::ColorTheme& theme, bool isDark) +{ + using namespace material; + + // Helper to check if a color is "unset" (black with no alpha) + auto isUnset = [](ImU32 c) { return c == 0; }; + + if (isDark) { + // Dark theme defaults + if (isUnset(theme.primaryVariant)) theme.primaryVariant = Darken(theme.primary, 0.2f); + if (isUnset(theme.primaryLight)) theme.primaryLight = Lighten(theme.primary, 0.3f); + + if (isUnset(theme.secondary)) theme.secondary = Hex(0x03DAC6); + if (isUnset(theme.secondaryVariant)) theme.secondaryVariant = Darken(theme.secondary, 0.2f); + if (isUnset(theme.secondaryLight)) theme.secondaryLight = Lighten(theme.secondary, 0.3f); + + if (isUnset(theme.surface)) theme.surface = Lighten(theme.background, 0.05f); + if (isUnset(theme.surfaceVariant)) theme.surfaceVariant = Lighten(theme.background, 0.10f); + + if (isUnset(theme.onPrimary)) theme.onPrimary = Hex(0xFFFFFF); + if (isUnset(theme.onSecondary)) theme.onSecondary = Hex(0x000000); + if (isUnset(theme.onBackground)) theme.onBackground = Hex(0xFFFFFF); + if (isUnset(theme.onSurface)) theme.onSurface = Hex(0xFFFFFF); + if (isUnset(theme.onSurfaceMedium)) theme.onSurfaceMedium = HexA(0xFFFFFF, 179); + if (isUnset(theme.onSurfaceDisabled)) theme.onSurfaceDisabled = HexA(0xFFFFFF, 97); + + if (isUnset(theme.error)) theme.error = Hex(0xCF6679); + if (isUnset(theme.onError)) theme.onError = Hex(0x000000); + + if (isUnset(theme.success)) theme.success = Hex(0x81C784); + if (isUnset(theme.onSuccess)) theme.onSuccess = Hex(0x000000); + if (isUnset(theme.warning)) theme.warning = Hex(0xFFB74D); + if (isUnset(theme.onWarning)) theme.onWarning = Hex(0x000000); + + if (isUnset(theme.stateHover)) theme.stateHover = HexA(0xFFFFFF, 10); + if (isUnset(theme.stateFocus)) theme.stateFocus = HexA(0xFFFFFF, 31); + if (isUnset(theme.statePressed)) theme.statePressed = HexA(0xFFFFFF, 25); + if (isUnset(theme.stateSelected)) theme.stateSelected = HexA(0xFFFFFF, 20); + if (isUnset(theme.stateDragged)) theme.stateDragged = HexA(0xFFFFFF, 20); + + if (isUnset(theme.divider)) theme.divider = HexA(0xFFFFFF, 31); + if (isUnset(theme.outline)) theme.outline = HexA(0xFFFFFF, 31); + if (isUnset(theme.scrim)) theme.scrim = HexA(0x000000, 128); + } else { + // Light theme defaults + if (isUnset(theme.primaryVariant)) theme.primaryVariant = Darken(theme.primary, 0.15f); + if (isUnset(theme.primaryLight)) theme.primaryLight = Lighten(theme.primary, 0.4f); + + if (isUnset(theme.secondary)) theme.secondary = Hex(0x03DAC6); + if (isUnset(theme.secondaryVariant)) theme.secondaryVariant = Darken(theme.secondary, 0.15f); + if (isUnset(theme.secondaryLight)) theme.secondaryLight = Lighten(theme.secondary, 0.4f); + + if (isUnset(theme.surface)) theme.surface = Hex(0xFFFFFF); + if (isUnset(theme.surfaceVariant)) theme.surfaceVariant = Darken(theme.background, 0.02f); + + if (isUnset(theme.onPrimary)) theme.onPrimary = Hex(0xFFFFFF); + if (isUnset(theme.onSecondary)) theme.onSecondary = Hex(0x000000); + if (isUnset(theme.onBackground)) theme.onBackground = Hex(0x000000); + if (isUnset(theme.onSurface)) theme.onSurface = Hex(0x000000); + if (isUnset(theme.onSurfaceMedium)) theme.onSurfaceMedium = HexA(0x000000, 179); + if (isUnset(theme.onSurfaceDisabled)) theme.onSurfaceDisabled = HexA(0x000000, 97); + + if (isUnset(theme.error)) theme.error = Hex(0xB00020); + if (isUnset(theme.onError)) theme.onError = Hex(0xFFFFFF); + + if (isUnset(theme.success)) theme.success = Hex(0x4CAF50); + if (isUnset(theme.onSuccess)) theme.onSuccess = Hex(0xFFFFFF); + if (isUnset(theme.warning)) theme.warning = Hex(0xFF9800); + if (isUnset(theme.onWarning)) theme.onWarning = Hex(0x000000); + + if (isUnset(theme.stateHover)) theme.stateHover = HexA(0x000000, 10); + if (isUnset(theme.stateFocus)) theme.stateFocus = HexA(0x000000, 31); + if (isUnset(theme.statePressed)) theme.statePressed = HexA(0x000000, 25); + if (isUnset(theme.stateSelected)) theme.stateSelected = HexA(0x000000, 20); + if (isUnset(theme.stateDragged)) theme.stateDragged = HexA(0x000000, 20); + + if (isUnset(theme.divider)) theme.divider = HexA(0x000000, 31); + if (isUnset(theme.outline)) theme.outline = HexA(0x000000, 31); + if (isUnset(theme.scrim)) theme.scrim = HexA(0x000000, 128); + } +} + +// ============================================================================ +// Acrylic Theme Derivation +// ============================================================================ + +AcrylicTheme ThemeLoader::deriveAcrylicTheme(const material::ColorTheme& theme) +{ + AcrylicTheme acrylic; + + // Extract primary color components for tinting + float primaryR = ((theme.primary >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float primaryG = ((theme.primary >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float primaryB = ((theme.primary >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + + // Extract background color components + float bgR = ((theme.background >> IM_COL32_R_SHIFT) & 0xFF) / 255.0f; + float bgG = ((theme.background >> IM_COL32_G_SHIFT) & 0xFF) / 255.0f; + float bgB = ((theme.background >> IM_COL32_B_SHIFT) & 0xFF) / 255.0f; + + bool isDark = getLuminance(theme.background) < 0.5f; + + if (isDark) { + // Dark theme: tint towards primary color + + // Sidebar: Strong primary tint + acrylic.sidebar.tintColor = ImVec4( + bgR * 0.5f + primaryR * 0.5f, + bgG * 0.5f + primaryG * 0.5f, + bgB * 0.5f + primaryB * 0.5f, + 1.0f + ); + acrylic.sidebar.tintOpacity = 0.85f; + acrylic.sidebar.luminosityOpacity = 0.4f; + acrylic.sidebar.blurRadius = 40.0f; + acrylic.sidebar.noiseOpacity = 0.02f; + acrylic.sidebar.fallbackColor = ImVec4(bgR * 0.7f, bgG * 0.7f, bgB * 0.7f, 1.0f); + acrylic.sidebar.enabled = true; + + // Popups: Subtle dark with slight primary tint + acrylic.popup.tintColor = ImVec4( + bgR * 0.8f + primaryR * 0.2f, + bgG * 0.8f + primaryG * 0.2f, + bgB * 0.8f + primaryB * 0.2f, + 1.0f + ); + acrylic.popup.tintOpacity = 0.80f; + acrylic.popup.luminosityOpacity = 0.5f; + acrylic.popup.blurRadius = 30.0f; + acrylic.popup.noiseOpacity = 0.02f; + acrylic.popup.fallbackColor = ImVec4(bgR, bgG, bgB, 0.98f); + acrylic.popup.enabled = true; + + // Cards: Very subtle primary tint + acrylic.card.tintColor = ImVec4( + bgR * 0.9f + primaryR * 0.1f, + bgG * 0.9f + primaryG * 0.1f, + bgB * 0.9f + primaryB * 0.1f, + 1.0f + ); + acrylic.card.tintOpacity = 0.65f; + acrylic.card.luminosityOpacity = 0.6f; + acrylic.card.blurRadius = 20.0f; + acrylic.card.noiseOpacity = 0.015f; + acrylic.card.fallbackColor = ImVec4(bgR + 0.05f, bgG + 0.05f, bgB + 0.05f, 1.0f); + acrylic.card.enabled = true; + + // Context menus: Dark and crisp + acrylic.menu.tintColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.menu.tintOpacity = 0.88f; + acrylic.menu.luminosityOpacity = 0.45f; + acrylic.menu.blurRadius = 25.0f; + acrylic.menu.noiseOpacity = 0.02f; + acrylic.menu.fallbackColor = ImVec4(bgR, bgG, bgB, 0.98f); + acrylic.menu.enabled = true; + + // Tooltips: Very transparent + acrylic.tooltip.tintColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.tooltip.tintOpacity = 0.75f; + acrylic.tooltip.luminosityOpacity = 0.5f; + acrylic.tooltip.blurRadius = 15.0f; + acrylic.tooltip.noiseOpacity = 0.01f; + acrylic.tooltip.fallbackColor = ImVec4(bgR + 0.02f, bgG + 0.02f, bgB + 0.02f, 0.95f); + acrylic.tooltip.enabled = true; + } else { + // Light theme + + // Sidebar: Light with slight primary tint + acrylic.sidebar.tintColor = ImVec4( + bgR * 0.9f + primaryR * 0.1f, + bgG * 0.9f + primaryG * 0.1f, + bgB * 0.9f + primaryB * 0.1f, + 1.0f + ); + acrylic.sidebar.tintOpacity = 0.82f; + acrylic.sidebar.luminosityOpacity = 0.7f; + acrylic.sidebar.blurRadius = 30.0f; + acrylic.sidebar.noiseOpacity = 0.015f; + acrylic.sidebar.fallbackColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.sidebar.enabled = true; + + // Popups + acrylic.popup.tintColor = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + acrylic.popup.tintOpacity = 0.85f; + acrylic.popup.luminosityOpacity = 0.75f; + acrylic.popup.blurRadius = 25.0f; + acrylic.popup.noiseOpacity = 0.015f; + acrylic.popup.fallbackColor = ImVec4(bgR, bgG, bgB, 0.98f); + acrylic.popup.enabled = true; + + // Cards + acrylic.card.tintColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.card.tintOpacity = 0.70f; + acrylic.card.luminosityOpacity = 0.75f; + acrylic.card.blurRadius = 18.0f; + acrylic.card.noiseOpacity = 0.01f; + acrylic.card.fallbackColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.card.enabled = true; + + // Menus + acrylic.menu.tintColor = ImVec4(bgR, bgG, bgB, 1.0f); + acrylic.menu.tintOpacity = 0.88f; + acrylic.menu.luminosityOpacity = 0.7f; + acrylic.menu.blurRadius = 22.0f; + acrylic.menu.noiseOpacity = 0.015f; + acrylic.menu.fallbackColor = ImVec4(bgR, bgG, bgB, 0.98f); + acrylic.menu.enabled = true; + + // Tooltips + acrylic.tooltip.tintColor = ImVec4(bgR - 0.02f, bgG - 0.02f, bgB - 0.02f, 1.0f); + acrylic.tooltip.tintOpacity = 0.80f; + acrylic.tooltip.luminosityOpacity = 0.7f; + acrylic.tooltip.blurRadius = 12.0f; + acrylic.tooltip.noiseOpacity = 0.01f; + acrylic.tooltip.fallbackColor = ImVec4(bgR - 0.02f, bgG - 0.02f, bgB - 0.02f, 0.95f); + acrylic.tooltip.enabled = true; + } + + return acrylic; +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/theme_loader.h b/src/ui/theme_loader.h new file mode 100644 index 0000000..2f873bf --- /dev/null +++ b/src/ui/theme_loader.h @@ -0,0 +1,69 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "material/color_theme.h" +#include "theme.h" +#include + +namespace dragonx { +namespace ui { + +/** + * @brief Color utility and theme derivation helpers + * + * Provides color parsing, luminance calculation, default color computation, + * and acrylic theme derivation from Material Design color themes. + * + * Theme loading is handled by the UISchema overlay system (ui.toml + + * dark.toml / light.toml). This class retains the utility methods + * that UISchema and other subsystems depend on. + */ +class ThemeLoader { +public: + /** + * @brief Parse any supported color string to ImU32 + * + * Supports all formats: + * - "0xRRGGBB" / "0xRRGGBBAA" (hex) + * - "#RRGGBB" / "#RRGGBBAA" (web hex) + * - "rgba(r,g,b,a)" (CSS-style, a is 0.0-1.0) + * - "transparent" (fully transparent) + */ + static bool parseColorString(const std::string& str, ImU32& outColor); + + /** + * @brief Parse hex color string to ImU32 + * + * Supports formats: + * - "0xRRGGBB" (6 hex digits, alpha = 255) + * - "0xRRGGBBAA" (8 hex digits, includes alpha) + * - "#RRGGBB" / "#RRGGBBAA" (web format) + */ + static bool parseHexColor(const std::string& hexStr, ImU32& outColor); + + /** + * @brief Convert ImU32 color to hex string + */ + static std::string colorToHexString(ImU32 color, bool includeAlpha = false); + + /** + * @brief Calculate relative luminance of a color (0.0 - 1.0) + */ + static float getLuminance(ImU32 color); + + /** + * @brief Compute default colors for missing fields + */ + static void computeDefaults(material::ColorTheme& theme, bool isDark); + + /** + * @brief Auto-generate AcrylicTheme from a ColorTheme + */ + static AcrylicTheme deriveAcrylicTheme(const material::ColorTheme& theme); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/widgets/qr_code.cpp b/src/ui/widgets/qr_code.cpp new file mode 100644 index 0000000..1016396 --- /dev/null +++ b/src/ui/widgets/qr_code.cpp @@ -0,0 +1,179 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "qr_code.h" +#include "../schema/ui_schema.h" +#include "imgui.h" +#include "../../../libs/qrcode/QrCode.hpp" + +#ifdef DRAGONX_USE_DX11 +#include +#else +#include +#endif +#include +#include +#include "../../util/logger.h" + +#ifdef DRAGONX_USE_DX11 +// Forward-declared helper to get D3D11 device from ImGui backend state +static ID3D11Device* GetImGuiD3D11Device() +{ + // ImGui_ImplDX11 stores the device in its backend data + // Access through the render state stored during init + ImGuiIO& io = ImGui::GetIO(); + if (!io.BackendRendererUserData) return nullptr; + // The first field in ImGui_ImplDX11_Data is the device pointer + return *reinterpret_cast(io.BackendRendererUserData); +} +#endif + +namespace dragonx { +namespace ui { + +uintptr_t GenerateQRTexture(const char* data, int* out_width, int* out_height) +{ + if (!data || !data[0]) { + return 0; + } + + try { + // Generate QR code + qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText( + data, qrcodegen::QrCode::Ecc::MEDIUM); + + const auto& S = schema::UI(); + int qr_size = qr.getSize(); + auto qrE = S.drawElement("components.qr-code", "module-scale"); + int scale = qrE.size >= 0 ? (int)qrE.size : 4; + auto qrB = S.drawElement("components.qr-code", "border-modules"); + int border = qrB.size >= 0 ? (int)qrB.size : 2; + + int img_size = (qr_size + border * 2) * scale; + + // Create pixel data (RGBA) + std::vector pixels(img_size * img_size * 4); + + for (int y = 0; y < img_size; y++) { + for (int x = 0; x < img_size; x++) { + int qx = x / scale - border; + int qy = y / scale - border; + + bool is_black = false; + if (qx >= 0 && qx < qr_size && qy >= 0 && qy < qr_size) { + is_black = qr.getModule(qx, qy); + } + + int idx = (y * img_size + x) * 4; + unsigned char color = is_black ? 0 : 255; + pixels[idx + 0] = color; // R + pixels[idx + 1] = color; // G + pixels[idx + 2] = color; // B + pixels[idx + 3] = 255; // A + } + } + +#ifdef DRAGONX_USE_DX11 + // Create D3D11 texture + shader resource view + ID3D11Device* device = GetImGuiD3D11Device(); + if (!device) return 0; + + D3D11_TEXTURE2D_DESC desc = {}; + desc.Width = img_size; + desc.Height = img_size; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + D3D11_SUBRESOURCE_DATA initData = {}; + initData.pSysMem = pixels.data(); + initData.SysMemPitch = img_size * 4; + + ID3D11Texture2D* texture = nullptr; + HRESULT hr = device->CreateTexture2D(&desc, &initData, &texture); + if (FAILED(hr) || !texture) return 0; + + ID3D11ShaderResourceView* srv = nullptr; + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = desc.Format; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = 1; + + hr = device->CreateShaderResourceView(texture, &srvDesc, &srv); + texture->Release(); + if (FAILED(hr) || !srv) return 0; + + if (out_width) *out_width = img_size; + if (out_height) *out_height = img_size; + + // Return SRV pointer as uintptr_t (cast to ImTextureID when rendering) + return (uintptr_t)srv; +#else + // Create OpenGL texture + GLuint texture; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_size, img_size, 0, + GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); + + if (out_width) *out_width = img_size; + if (out_height) *out_height = img_size; + + return texture; +#endif + + } catch (const std::exception& e) { + DEBUG_LOGF("QR generation failed: %s\n", e.what()); + return 0; + } +} + +void FreeQRTexture(uintptr_t texture_id) +{ + if (texture_id) { +#ifdef DRAGONX_USE_DX11 + ID3D11ShaderResourceView* srv = (ID3D11ShaderResourceView*)texture_id; + srv->Release(); +#else + GLuint tex = texture_id; + glDeleteTextures(1, &tex); +#endif + } +} + +void RenderQRCode(uintptr_t texture_id, float size) +{ + if (texture_id) { + ImGui::Image((ImTextureID)texture_id, ImVec2(size, size)); + } else { + // Draw placeholder + ImVec2 cursor = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + draw_list->AddRectFilled( + cursor, + ImVec2(cursor.x + size, cursor.y + size), + IM_COL32(200, 200, 200, 255) + ); + draw_list->AddRect( + cursor, + ImVec2(cursor.x + size, cursor.y + size), + IM_COL32(100, 100, 100, 255) + ); + + ImGui::Dummy(ImVec2(size, size)); + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/widgets/qr_code.h b/src/ui/widgets/qr_code.h new file mode 100644 index 0000000..b347a04 --- /dev/null +++ b/src/ui/widgets/qr_code.h @@ -0,0 +1,39 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +namespace ui { + +/** + * @brief QR Code rendering utilities + */ + +/** + * @brief Generate a texture containing a QR code + * @param data The data to encode in the QR code + * @param out_width Output: width of the texture + * @param out_height Output: height of the texture + * @return Texture handle (OpenGL texture ID or DX11 SRV pointer), or 0 on failure + */ +uintptr_t GenerateQRTexture(const char* data, int* out_width, int* out_height); + +/** + * @brief Free a QR texture + * @param texture_id Texture handle returned by GenerateQRTexture + */ +void FreeQRTexture(uintptr_t texture_id); + +/** + * @brief Render a QR code using ImGui + * @param texture_id Texture handle from GenerateQRTexture + * @param size Display size (width and height) + */ +void RenderQRCode(uintptr_t texture_id, float size); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/about_dialog.cpp b/src/ui/windows/about_dialog.cpp new file mode 100644 index 0000000..4919391 --- /dev/null +++ b/src/ui/windows/about_dialog.cpp @@ -0,0 +1,180 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "about_dialog.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +void RenderAboutDialog(App* app, bool* p_open) +{ + (void)app; + auto& S = schema::UI(); + auto win = S.window("dialogs.about"); + auto linkBtn = S.button("dialogs.about", "link-button"); + auto closeBtn = S.button("dialogs.about", "close-button"); + auto versionLbl = S.label("dialogs.about", "version-label"); + auto editionLbl = S.label("dialogs.about", "edition-label"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + // Use acrylic modal popup from current theme + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("About ObsidianDragon"); + if (!effects::ImGuiAcrylic::BeginAcrylicPopupModal("About ObsidianDragon", p_open, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + effects::ImGuiAcrylic::EndAcrylicPopup(); + return; + } + + // Use Body2 font for all dialog text + ImGui::PushFont(Type().body2()); + + // Logo/Title area + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.3f, 0.69f, 0.31f, 1.0f)); // Green + ImGui::PushFont(Type().h4()); + ImGui::Text("ObsidianDragon"); + ImGui::PopFont(); + ImGui::PopStyleColor(); + + ImGui::SameLine(ImGui::GetWindowWidth() - editionLbl.position); + ImGui::TextDisabled("ImGui Edition"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Version info + ImGui::Text("Version:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("%s", DRAGONX_VERSION); + + ImGui::Text("ImGui:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("%s", IMGUI_VERSION); + + ImGui::Text("Build Date:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("%s %s", __DATE__, __TIME__); + +#ifdef DRAGONX_DEBUG + ImGui::Text("Build Type:"); + ImGui::SameLine(versionLbl.position); + ImGui::TextColored(ImVec4(1.0f, 0.6f, 0.0f, 1.0f), "Debug"); +#else + ImGui::Text("Build Type:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("Release"); +#endif + + // Daemon info + if (app && app->isConnected()) { + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Daemon:"); + ImGui::SameLine(versionLbl.position); + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "Connected"); + + const auto& state = app->getWalletState(); + ImGui::Text("Chain:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("ObsidianDragon"); + + ImGui::Text("Block Height:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("%d", state.sync.blocks); + + ImGui::Text("Connections:"); + ImGui::SameLine(versionLbl.position); + ImGui::Text("%zu peers", state.peers.size()); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Credits + ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), "Credits"); + ImGui::Spacing(); + + ImGui::BulletText("The Hush Developers"); + ImGui::BulletText("ObsidianDragon Community"); + ImGui::BulletText("Dear ImGui by Omar Cornut"); + ImGui::BulletText("ImPlot by Evan Pezent"); + ImGui::BulletText("SDL3 by Sam Lantinga"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // License + ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), "License"); + ImGui::Spacing(); + ImGui::TextWrapped( + "This software is released under the GNU General Public License v3 (GPLv3). " + "You are free to use, modify, and distribute this software under the terms of the license." + ); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Links + if (material::StyledButton("Website", ImVec2(linkBtn.width, 0), S.resolveFont(linkBtn.font))) { + #ifdef _WIN32 + system("start https://dragonx.is"); + #elif __APPLE__ + system("open https://dragonx.is"); + #else + system("xdg-open https://dragonx.is &"); + #endif + } + ImGui::SameLine(); + if (material::StyledButton("GitHub", ImVec2(linkBtn.width, 0), S.resolveFont(linkBtn.font))) { + #ifdef _WIN32 + system("start https://git.hush.is/dragonx/ObsidianDragon"); + #elif __APPLE__ + system("open https://git.hush.is/dragonx/ObsidianDragon"); + #else + system("xdg-open https://git.hush.is/dragonx/ObsidianDragon &"); + #endif + } + ImGui::SameLine(); + if (material::StyledButton("Block Explorer", ImVec2(linkBtn.width, 0), S.resolveFont(linkBtn.font))) { + #ifdef _WIN32 + system("start https://explorer.dragonx.is"); + #elif __APPLE__ + system("open https://explorer.dragonx.is"); + #else + system("xdg-open https://explorer.dragonx.is &"); + #endif + } + + ImGui::Spacing(); + + // Close button + float button_width = closeBtn.width; + ImGui::SetCursorPosX((ImGui::GetWindowWidth() - button_width) * 0.5f); + if (material::StyledButton("Close", ImVec2(button_width, 0), S.resolveFont(closeBtn.font))) { + *p_open = false; + } + + ImGui::PopFont(); // Body2 + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/about_dialog.h b/src/ui/windows/about_dialog.h new file mode 100644 index 0000000..4b75370 --- /dev/null +++ b/src/ui/windows/about_dialog.h @@ -0,0 +1,16 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { + +class App; + +namespace ui { + +void RenderAboutDialog(App* app, bool* p_open); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/address_book_dialog.cpp b/src/ui/windows/address_book_dialog.cpp new file mode 100644 index 0000000..48cd7d1 --- /dev/null +++ b/src/ui/windows/address_book_dialog.cpp @@ -0,0 +1,316 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "address_book_dialog.h" +#include "../../app.h" +#include "../../data/address_book.h" +#include "../notifications.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "imgui.h" +#include + +namespace dragonx { +namespace ui { + +// Static member initialization +bool AddressBookDialog::s_open = false; +int AddressBookDialog::s_selected_index = -1; +bool AddressBookDialog::s_show_add_dialog = false; +bool AddressBookDialog::s_show_edit_dialog = false; +char AddressBookDialog::s_edit_label[128] = ""; +char AddressBookDialog::s_edit_address[512] = ""; +char AddressBookDialog::s_edit_notes[512] = ""; + +// Shared address book instance +static std::unique_ptr s_address_book; + +static data::AddressBook& getAddressBook() { + if (!s_address_book) { + s_address_book = std::make_unique(); + s_address_book->load(); + } + return *s_address_book; +} + +void AddressBookDialog::show() +{ + s_open = true; + s_selected_index = -1; + s_show_add_dialog = false; + s_show_edit_dialog = false; + + // Reload address book + getAddressBook().load(); +} + +bool AddressBookDialog::isOpen() +{ + return s_open; +} + +void AddressBookDialog::render(App* app) +{ + (void)app; // May use for send-to feature later + + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.address-book"); + auto addrTable = S.table("dialogs.address-book", "address-table"); + auto addrFrontLbl = S.label("dialogs.address-book", "address-front-label"); + auto addrBackLbl = S.label("dialogs.address-book", "address-back-label"); + auto addrInput = S.input("dialogs.address-book", "address-input"); + auto notesInput = S.input("dialogs.address-book", "notes-input"); + auto actionBtn = S.button("dialogs.address-book", "action-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Address Book"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Address Book", &s_open, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + auto& book = getAddressBook(); + + // Toolbar + if (material::StyledButton("Add New", ImVec2(0,0), S.resolveFont(actionBtn.font))) { + s_show_add_dialog = true; + s_edit_label[0] = '\0'; + s_edit_address[0] = '\0'; + s_edit_notes[0] = '\0'; + } + + ImGui::SameLine(); + + bool has_selection = s_selected_index >= 0 && s_selected_index < static_cast(book.size()); + + if (!has_selection) ImGui::BeginDisabled(); + + if (material::StyledButton("Edit", ImVec2(0,0), S.resolveFont(actionBtn.font))) { + if (has_selection) { + const auto& entry = book.entries()[s_selected_index]; + strncpy(s_edit_label, entry.label.c_str(), sizeof(s_edit_label) - 1); + strncpy(s_edit_address, entry.address.c_str(), sizeof(s_edit_address) - 1); + strncpy(s_edit_notes, entry.notes.c_str(), sizeof(s_edit_notes) - 1); + s_show_edit_dialog = true; + } + } + + ImGui::SameLine(); + + if (material::StyledButton("Delete", ImVec2(0,0), S.resolveFont(actionBtn.font))) { + if (has_selection) { + book.removeEntry(s_selected_index); + s_selected_index = -1; + Notifications::instance().success("Entry deleted"); + } + } + + ImGui::SameLine(); + + if (material::StyledButton("Copy Address", ImVec2(0,0), S.resolveFont(actionBtn.font))) { + if (has_selection) { + ImGui::SetClipboardText(book.entries()[s_selected_index].address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + } + + if (!has_selection) ImGui::EndDisabled(); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Address list + if (ImGui::BeginTable("AddressBookTable", 3, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | + ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY, + ImVec2(0, addrTable.bottomReserve > 0 ? -addrTable.bottomReserve : -35))) + { + float labelColW = (addrTable.columns.count("label") && addrTable.columns.at("label").width > 0) ? addrTable.columns.at("label").width : 150; + float notesColW = (addrTable.columns.count("notes") && addrTable.columns.at("notes").width > 0) ? addrTable.columns.at("notes").width : 150; + ImGui::TableSetupColumn("Label", ImGuiTableColumnFlags_WidthFixed, labelColW); + ImGui::TableSetupColumn("Address", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Notes", ImGuiTableColumnFlags_WidthFixed, notesColW); + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableHeadersRow(); + + if (book.empty()) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextDisabled("No saved addresses. Click 'Add New' to add one."); + } else { + for (size_t i = 0; i < book.size(); i++) { + const auto& entry = book.entries()[i]; + + ImGui::TableNextRow(); + ImGui::PushID(static_cast(i)); + + ImGui::TableNextColumn(); + bool is_selected = (s_selected_index == static_cast(i)); + if (ImGui::Selectable(entry.label.c_str(), is_selected, + ImGuiSelectableFlags_SpanAllColumns)) { + s_selected_index = static_cast(i); + } + + // Double-click to edit + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) { + s_selected_index = static_cast(i); + strncpy(s_edit_label, entry.label.c_str(), sizeof(s_edit_label) - 1); + strncpy(s_edit_address, entry.address.c_str(), sizeof(s_edit_address) - 1); + strncpy(s_edit_notes, entry.notes.c_str(), sizeof(s_edit_notes) - 1); + s_show_edit_dialog = true; + } + + ImGui::TableNextColumn(); + // Truncate long addresses + std::string addr_display = entry.address; + int addrTruncLen = (addrTable.columns.count("address") && addrTable.columns.at("address").truncate > 0) ? addrTable.columns.at("address").truncate : 40; + if (addr_display.length() > static_cast(addrTruncLen)) { + addr_display = addr_display.substr(0, addrFrontLbl.truncate) + "..." + + addr_display.substr(addr_display.length() - addrBackLbl.truncate); + } + ImGui::TextDisabled("%s", addr_display.c_str()); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("%s", entry.address.c_str()); + } + + ImGui::TableNextColumn(); + ImGui::TextDisabled("%s", entry.notes.c_str()); + + ImGui::PopID(); + } + } + + ImGui::EndTable(); + } + + // Status line + ImGui::TextDisabled("%zu addresses saved", book.size()); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + + // Add dialog + if (s_show_add_dialog) { + ImGui::OpenPopup("Add Address"); + } + + // Re-use center from above (already defined at start of render) + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + if (ImGui::BeginPopupModal("Add Address", &s_show_add_dialog, ImGuiWindowFlags_AlwaysAutoResize)) { + material::Type().text(material::TypeStyle::H6, "Add Address"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::Text("Label:"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputText("##AddLabel", s_edit_label, sizeof(s_edit_label)); + + ImGui::Spacing(); + + ImGui::Text("Address:"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputText("##AddAddress", s_edit_address, sizeof(s_edit_address)); + ImGui::SameLine(); + if (material::StyledButton("Paste##Add", ImVec2(0,0), S.resolveFont(actionBtn.font))) { + const char* clipboard = ImGui::GetClipboardText(); + if (clipboard) { + strncpy(s_edit_address, clipboard, sizeof(s_edit_address) - 1); + } + } + + ImGui::Spacing(); + + ImGui::Text("Notes (optional):"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputTextMultiline("##AddNotes", s_edit_notes, sizeof(s_edit_notes), ImVec2(addrInput.width, notesInput.height > 0 ? notesInput.height : 60)); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + bool can_add = strlen(s_edit_label) > 0 && strlen(s_edit_address) > 0; + if (!can_add) ImGui::BeginDisabled(); + + if (material::StyledButton("Add", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + data::AddressBookEntry entry(s_edit_label, s_edit_address, s_edit_notes); + if (getAddressBook().addEntry(entry)) { + Notifications::instance().success("Address added to book"); + s_show_add_dialog = false; + } else { + Notifications::instance().error("Address already exists in book"); + } + } + + if (!can_add) ImGui::EndDisabled(); + + ImGui::SameLine(); + if (material::StyledButton("Cancel", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + s_show_add_dialog = false; + } + + ImGui::EndPopup(); + } + + // Edit dialog + if (s_show_edit_dialog) { + ImGui::OpenPopup("Edit Address"); + } + + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + if (ImGui::BeginPopupModal("Edit Address", &s_show_edit_dialog, ImGuiWindowFlags_AlwaysAutoResize)) { + material::Type().text(material::TypeStyle::H6, "Edit Address"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + ImGui::Text("Label:"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputText("##EditLabel", s_edit_label, sizeof(s_edit_label)); + + ImGui::Spacing(); + + ImGui::Text("Address:"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputText("##EditAddress", s_edit_address, sizeof(s_edit_address)); + + ImGui::Spacing(); + + ImGui::Text("Notes (optional):"); + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputTextMultiline("##EditNotes", s_edit_notes, sizeof(s_edit_notes), ImVec2(addrInput.width, notesInput.height > 0 ? notesInput.height : 60)); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + bool can_save = strlen(s_edit_label) > 0 && strlen(s_edit_address) > 0; + if (!can_save) ImGui::BeginDisabled(); + + if (material::StyledButton("Save", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + data::AddressBookEntry entry(s_edit_label, s_edit_address, s_edit_notes); + if (getAddressBook().updateEntry(s_selected_index, entry)) { + Notifications::instance().success("Address updated"); + s_show_edit_dialog = false; + } else { + Notifications::instance().error("Failed to update - address may be duplicate"); + } + } + + if (!can_save) ImGui::EndDisabled(); + + ImGui::SameLine(); + if (material::StyledButton("Cancel", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + s_show_edit_dialog = false; + } + + ImGui::EndPopup(); + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/address_book_dialog.h b/src/ui/windows/address_book_dialog.h new file mode 100644 index 0000000..120cd55 --- /dev/null +++ b/src/ui/windows/address_book_dialog.h @@ -0,0 +1,45 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Address book dialog for managing saved addresses + */ +class AddressBookDialog { +public: + /** + * @brief Show the address book dialog + */ + static void show(); + + /** + * @brief Render the dialog (call every frame) + * @param app Pointer to app instance + */ + static void render(App* app); + + /** + * @brief Check if dialog is currently open + */ + static bool isOpen(); + +private: + static bool s_open; + static int s_selected_index; + static bool s_show_add_dialog; + static bool s_show_edit_dialog; + static char s_edit_label[128]; + static char s_edit_address[512]; + static char s_edit_notes[512]; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/backup_wallet_dialog.cpp b/src/ui/windows/backup_wallet_dialog.cpp new file mode 100644 index 0000000..add4fc2 --- /dev/null +++ b/src/ui/windows/backup_wallet_dialog.cpp @@ -0,0 +1,199 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "backup_wallet_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +namespace fs = std::filesystem; +using json = nlohmann::json; + +// Static state +static bool s_open = false; +static char s_destination[512] = ""; +static std::string s_status; +static bool s_backing_up = false; + +void BackupWalletDialog::show() +{ + s_open = true; + s_status.clear(); + s_backing_up = false; + + // Generate default destination with timestamp + std::time_t now = std::time(nullptr); + char timebuf[32]; + std::strftime(timebuf, sizeof(timebuf), "%Y%m%d_%H%M%S", std::localtime(&now)); + + // Default to home directory + std::string home = util::Platform::getHomeDir(); + snprintf(s_destination, sizeof(s_destination), "%s/wallet_backup_%s.dat", home.c_str(), timebuf); +} + +bool BackupWalletDialog::isOpen() +{ + return s_open; +} + +void BackupWalletDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.backup-wallet"); + auto backupBtn = S.button("dialogs.backup-wallet", "backup-button"); + auto closeBtn = S.button("dialogs.backup-wallet", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Backup Wallet"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Backup Wallet", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ImGui::TextWrapped( + "Create a backup of your wallet.dat file. This file contains all your " + "private keys and transaction history. Store the backup in a secure location." + ); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + if (s_backing_up) { + ImGui::BeginDisabled(); + } + + // Destination path + ImGui::Text("Backup destination:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##Destination", s_destination, sizeof(s_destination)); + + ImGui::Spacing(); + + // Show wallet.dat location + std::string walletPath = util::Platform::getDataDir() + "/wallet.dat"; + ImGui::TextDisabled("Source: %s", walletPath.c_str()); + + // Check if source exists + bool sourceExists = fs::exists(walletPath); + if (!sourceExists) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); + ImGui::Text("Warning: wallet.dat not found at expected location"); + ImGui::PopStyleColor(); + } + + if (s_backing_up) { + ImGui::EndDisabled(); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Backup button - use RPC backupwallet + if (s_backing_up) { + ImGui::BeginDisabled(); + } + + if (material::StyledButton("Create Backup", ImVec2(backupBtn.width, 0), S.resolveFont(backupBtn.font))) { + if (strlen(s_destination) == 0) { + Notifications::instance().warning("Please enter a destination path"); + } else if (!app->rpc() || !app->rpc()->isConnected()) { + Notifications::instance().error("Not connected to daemon"); + } else { + s_backing_up = true; + s_status = "Creating backup..."; + + // Run backup on worker thread to avoid freezing UI + std::string dest(s_destination); + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), dest]() -> rpc::RPCWorker::MainCb { + bool success = false; + std::string statusMsg; + try { + rpc->call("backupwallet", json::array({dest})); + // Check if file was created + if (fs::exists(dest)) { + auto size = fs::file_size(dest); + char sizebuf[32]; + if (size > 1024 * 1024) { + snprintf(sizebuf, sizeof(sizebuf), "%.2f MB", size / (1024.0 * 1024.0)); + } else if (size > 1024) { + snprintf(sizebuf, sizeof(sizebuf), "%.2f KB", size / 1024.0); + } else { + snprintf(sizebuf, sizeof(sizebuf), "%zu bytes", size); + } + statusMsg = std::string("Backup created successfully (") + sizebuf + ")"; + success = true; + } else { + statusMsg = "Backup may have failed - file not found"; + } + } catch (const std::exception& e) { + statusMsg = std::string("Backup failed: ") + e.what(); + } + return [success, statusMsg]() { + s_status = statusMsg; + s_backing_up = false; + if (success) { + Notifications::instance().success("Wallet backup created"); + } else { + Notifications::instance().warning(statusMsg); + } + }; + }); + } + } + } + + if (s_backing_up) { + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::TextDisabled("Backing up..."); + } + + ImGui::SameLine(); + if (material::StyledButton("Close", ImVec2(closeBtn.width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + + // Status + if (!s_status.empty()) { + ImGui::Spacing(); + ImGui::TextWrapped("%s", s_status.c_str()); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Tips + ImGui::TextDisabled("Tips:"); + ImGui::BulletText("Store backups on external drives or cloud storage"); + ImGui::BulletText("Create multiple backups in different locations"); + ImGui::BulletText("Test restoring from backup periodically"); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/backup_wallet_dialog.h b/src/ui/windows/backup_wallet_dialog.h new file mode 100644 index 0000000..8f5d96e --- /dev/null +++ b/src/ui/windows/backup_wallet_dialog.h @@ -0,0 +1,31 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for backing up wallet.dat + */ +class BackupWalletDialog { +public: + // Show the dialog + static void show(); + + // Render the dialog (call each frame) + static void render(App* app); + + // Check if dialog is open + static bool isOpen(); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/balance_tab.cpp b/src/ui/windows/balance_tab.cpp new file mode 100644 index 0000000..26428d8 --- /dev/null +++ b/src/ui/windows/balance_tab.cpp @@ -0,0 +1,3273 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "balance_tab.h" +#include "key_export_dialog.h" +#include "qr_popup_dialog.h" +#include "send_tab.h" +#include "../../app.h" +#include "../../config/settings.h" +#include "../../config/version.h" +#include "../../util/i18n.h" +#include "../theme.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../effects/imgui_acrylic.h" +#include "../sidebar.h" +#include "../notifications.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include +#include +#include +#include "../../util/logger.h" + +namespace dragonx { +namespace ui { + +// Case-insensitive substring search +static bool containsIgnoreCase(const std::string& str, const std::string& search) { + if (search.empty()) return true; + std::string s = str, q = search; + std::transform(s.begin(), s.end(), s.begin(), ::tolower); + std::transform(q.begin(), q.end(), q.begin(), ::tolower); + return s.find(q) != std::string::npos; +} + +// Relative time string ("2m ago", "3h ago", etc.) +static std::string timeAgo(int64_t timestamp) { + if (timestamp <= 0) return ""; + int64_t now = (int64_t)std::time(nullptr); + int64_t diff = now - timestamp; + if (diff < 0) diff = 0; + if (diff < 60) return std::to_string(diff) + "s ago"; + if (diff < 3600) return std::to_string(diff / 60) + "m ago"; + if (diff < 86400) return std::to_string(diff / 3600) + "h ago"; + return std::to_string(diff / 86400) + "d ago"; +} + +// Draw a small transaction-type icon (send=up, receive=down, mined=construction) +static void DrawTxIcon(ImDrawList* dl, const std::string& type, + float cx, float cy, float /*s*/, ImU32 col) +{ + using namespace material; + ImFont* iconFont = Type().iconSmall(); + const char* icon; + if (type == "send") { + icon = ICON_MD_CALL_MADE; + } else if (type == "receive") { + icon = ICON_MD_CALL_RECEIVED; + } else { + icon = ICON_MD_CONSTRUCTION; + } + ImVec2 sz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - sz.x * 0.5f, cy - sz.y * 0.5f), col, icon); +} + +// Animated balance state — lerps smoothly toward target +static double s_dispTotal = 0.0; +static double s_dispShielded = 0.0; +static double s_dispTransparent = 0.0; +static double s_dispUnconfirmed = 0.0; + +// Helper to truncate address for display +static std::string truncateAddress(const std::string& addr, int maxLen = 32) { + if (addr.length() <= static_cast(maxLen)) return addr; + int half = (maxLen - 3) / 2; + return addr.substr(0, half) + "..." + addr.substr(addr.length() - half); +} + +// Helper to draw a sparkline polyline within a bounding box +static void DrawSparkline(ImDrawList* dl, const ImVec2& pMin, const ImVec2& pMax, + const std::vector& data, ImU32 color, + float thickness = 1.5f) +{ + if (data.size() < 2) return; + double lo = *std::min_element(data.begin(), data.end()); + double hi = *std::max_element(data.begin(), data.end()); + double range = hi - lo; + if (range < 1e-12) range = 1.0; + + float w = pMax.x - pMin.x; + float h = pMax.y - pMin.y; + int n = (int)data.size(); + + std::vector pts; + pts.reserve(n); + for (int i = 0; i < n; i++) { + float x = pMin.x + (float)i / (float)(n - 1) * w; + float y = pMax.y - (float)((data[i] - lo) / range) * h; + pts.push_back(ImVec2(x, y)); + } + dl->AddPolyline(pts.data(), n, color, ImDrawFlags_None, thickness); +} + +// Forward declarations for all layout functions +static void RenderBalanceClassic(App* app); +static void RenderBalanceDonut(App* app); +static void RenderBalanceConsolidated(App* app); +static void RenderBalanceDashboard(App* app); +static void RenderBalanceVerticalStack(App* app); +static void RenderBalanceVertical2x2(App* app); +static void RenderBalanceShield(App* app); +static void RenderBalanceTimeline(App* app); +static void RenderBalanceTwoRow(App* app); +static void RenderBalanceMinimal(App* app); + +// ============================================================================ +// Layout config — parsed from ui.toml [tabs.balance.layouts] +// ============================================================================ + +// Legacy int→string ID mapping for old settings.json migration +static const char* s_legacyLayoutIds[] = { + "classic", "donut", "consolidated", "dashboard", + "vertical-stack", "vertical-2x2", "shield", "timeline", "two-row", "minimal" +}; +static constexpr int s_legacyLayoutCount = 10; + +static std::vector s_balanceLayouts; +static std::string s_defaultLayoutId = "classic"; +static bool s_layoutConfigLoaded = false; + +static void LoadBalanceLayoutConfig() +{ + s_balanceLayouts.clear(); + + const void* elem = schema::UI().findElement("tabs.balance", "layouts"); + if (elem) { + const auto& t = *static_cast(elem); + + if (auto selected = t["selected"].value()) + s_defaultLayoutId = *selected; + else if (auto def = t["default"].value()) + s_defaultLayoutId = *def; + + if (auto* options = t["options"].as_array()) { + for (auto& item : *options) { + auto* opt = item.as_table(); + if (!opt) continue; + auto id = (*opt)["id"].value(); + auto name = (*opt)["name"].value(); + if (!id || !name) continue; + + BalanceLayoutEntry entry; + entry.id = *id; + entry.name = *name; + entry.enabled = (*opt)["enabled"].value_or(true); + s_balanceLayouts.push_back(std::move(entry)); + } + } + } + + // Fallback if ui.toml had no layouts defined + if (s_balanceLayouts.empty()) { + for (int i = 0; i < s_legacyLayoutCount; i++) { + BalanceLayoutEntry entry; + entry.id = s_legacyLayoutIds[i]; + // Capitalize first letter for display name + entry.name = entry.id; + if (!entry.name.empty()) + entry.name[0] = (char)toupper((unsigned char)entry.name[0]); + s_balanceLayouts.push_back(std::move(entry)); + } + } + s_layoutConfigLoaded = true; +} + +const std::vector& GetBalanceLayouts() +{ + if (!s_layoutConfigLoaded) LoadBalanceLayoutConfig(); + return s_balanceLayouts; +} + +const std::string& GetDefaultBalanceLayout() +{ + if (!s_layoutConfigLoaded) LoadBalanceLayoutConfig(); + return s_defaultLayoutId; +} + +void RefreshBalanceLayoutConfig() +{ + s_layoutConfigLoaded = false; +} + +std::string MigrateBalanceLayoutIndex(int index) +{ + if (index >= 0 && index < s_legacyLayoutCount) + return s_legacyLayoutIds[index]; + return "classic"; +} + +// Layout ID → render function dispatch +using LayoutRenderFn = void(*)(App*); +struct LayoutDispatchEntry { const char* id; LayoutRenderFn fn; }; +static const LayoutDispatchEntry s_layoutDispatch[] = { + { "classic", RenderBalanceClassic }, + { "donut", RenderBalanceDonut }, + { "consolidated", RenderBalanceConsolidated }, + { "dashboard", RenderBalanceDashboard }, + { "vertical-stack", RenderBalanceVerticalStack }, + { "vertical-2x2", RenderBalanceVertical2x2 }, + { "shield", RenderBalanceShield }, + { "timeline", RenderBalanceTimeline }, + { "two-row", RenderBalanceTwoRow }, + { "minimal", RenderBalanceMinimal }, +}; + +void RenderBalanceTab(App* app) +{ + std::string layoutId = GetDefaultBalanceLayout(); + if (app->settings()) { + std::string saved = app->settings()->getBalanceLayout(); + if (!saved.empty()) layoutId = saved; + } + + // Left/Right arrows: cycle through enabled balance layouts + // (skip when Ctrl is held — Ctrl+Arrow cycles themes instead) + if (app->settings() && !ImGui::GetIO().WantTextInput && !ImGui::GetIO().KeyCtrl) { + bool cycleUp = ImGui::IsKeyPressed(ImGuiKey_LeftArrow); + bool cycleDown = ImGui::IsKeyPressed(ImGuiKey_RightArrow); + if (cycleUp || cycleDown) { + const auto& layouts = GetBalanceLayouts(); + // Build list of enabled layout IDs + std::vector enabled; + for (const auto& l : layouts) + if (l.enabled) enabled.push_back(l.id); + if (!enabled.empty()) { + int cur = 0; + for (int i = 0; i < (int)enabled.size(); i++) { + if (enabled[i] == layoutId) { cur = i; break; } + } + if (cycleUp) + cur = (cur - 1 + (int)enabled.size()) % (int)enabled.size(); + else + cur = (cur + 1) % (int)enabled.size(); + layoutId = enabled[cur]; + app->settings()->setBalanceLayout(layoutId); + + // Show toast with layout name + const auto& allLayouts = GetBalanceLayouts(); + std::string displayName = layoutId; + for (const auto& l : allLayouts) { + if (l.id == layoutId) { displayName = l.name; break; } + } + Notifications::instance().info("Layout: " + displayName); + } + } + } + + // Dispatch by string ID + for (const auto& entry : s_layoutDispatch) { + if (layoutId == entry.id) { + entry.fn(app); + return; + } + } + // Fallback to Classic + RenderBalanceClassic(app); +} + +// ============================================================================ +// Layout 0: Classic (original 3-card layout) +// ============================================================================ +static void RenderBalanceClassic(App* app) +{ + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto addrBtn = S.button("tabs.balance", "address-button"); + const auto actionBtn = S.button("tabs.balance", "action-button"); + const auto searchIn = S.input("tabs.balance", "search-input"); + const auto addrTable = S.table("tabs.balance", "address-table"); + const auto syncBar = S.drawElement("tabs.balance", "sync-bar"); + + // Read layout properties from schema + const float kBalanceLerpSpeed = S.drawElement("tabs.balance", "balance-lerp-speed").sizeOr(8.0f); + const float kHeroPadTop = S.drawElement("tabs.balance", "hero-pad-top").sizeOr(12.0f); + const float kRecentTxRowHeight = S.drawElement("tabs.balance", "recent-tx-row-height").sizeOr(22.0f); + const float kButtonRowRightMargin = S.drawElement("tabs.balance", "button-row-right-margin").sizeOr(16.0f); + + const auto& state = app->state(); + + // Responsive scale factors (recomputed every frame) + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + const float hs = Layout::hScale(contentAvail.x); + const float vs = Layout::vScale(contentAvail.y); + const auto tier = Layout::currentTier(contentAvail.x, contentAvail.y); + const float glassRound = Layout::glassRounding(); + const float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + + // Responsive constants (scale with window size) + const float kSparklineHeight = std::max(S.drawElement("tabs.balance", "sparkline-min-height").size, S.drawElement("tabs.balance", "sparkline-height").size * vs); + const float kMinButtonsPosition = std::max(S.drawElement("tabs.balance", "min-buttons-position").size, S.drawElement("tabs.balance", "buttons-position").size * hs); + + // Dynamic recent tx count — fit as many as space allows + const float scaledRowH = std::max(S.drawElement("tabs.balance", "recent-tx-row-min-height").size, kRecentTxRowHeight * vs); + // At minimum size ~601px avail, reserve ~300px for hero+cards+addr header, + // rest for address list + recent txs. Show 3-5 rows depending on space. + const int kRecentTxCount = std::clamp( + (int)((contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f)) / scaledRowH), 2, 5); + + // Lerp displayed balances toward actual values + { + float dt = ImGui::GetIO().DeltaTime; + float speed = kBalanceLerpSpeed; + auto lerp = [](double& disp, double target, float dt, float spd) { + double diff = target - disp; + if (std::abs(diff) < 1e-9) { disp = target; return; } + disp += diff * (double)(dt * spd); + // Snap when very close + if (std::abs(target - disp) < 1e-9) disp = target; + }; + lerp(s_dispTotal, app->getTotalBalance(), dt, speed); + lerp(s_dispShielded, app->getShieldedBalance(), dt, speed); + lerp(s_dispTransparent, app->getTransparentBalance(), dt, speed); + lerp(s_dispUnconfirmed, state.unconfirmed_balance, dt, speed); + } + + // ================================================================ + // Card row — Total Balance | Shielded | Transparent | Market + // ================================================================ + { + float topMargin = S.drawElement("tabs.balance.classic", "top-margin").size; + if (topMargin > 0.0f) + ImGui::Dummy(ImVec2(0, topMargin)); + else if (topMargin < 0.0f) { + // auto: use hero-pad-top scaled by vertical factor + float autoPad = kHeroPadTop * vs; + if (autoPad > 0.0f) + ImGui::Dummy(ImVec2(0, autoPad)); + } + // topMargin == 0 → no spacing at all + + const float cardGap = cGap; + float availWidth = ImGui::GetContentRegionAvail().x; + + // Responsive card columns: 4 normally, 2 in compact, 1 if very narrow + int numCols = (int)S.drawElement("tabs.balance.classic", "card-num-cols").sizeOr(4.0f); + if (tier == Layout::LayoutTier::Compact) { + if (availWidth < S.drawElement("tabs.balance.classic", "card-narrow-width").sizeOr(400.0f) * Layout::dpiScale()) + numCols = (int)S.drawElement("tabs.balance.classic", "card-narrow-cols").sizeOr(1.0f); + else + numCols = (int)S.drawElement("tabs.balance.classic", "card-compact-cols").sizeOr(2.0f); + } + float cardWidth = (availWidth - (float)(numCols - 1) * cardGap) / (float)numCols; + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 origin = ImGui::GetCursorScreenPos(); + GlassPanelSpec cardSpec; + cardSpec.rounding = glassRound; + + char buf[64]; + ImU32 greenCol = Success(); + ImU32 goldCol = Warning(); + ImU32 amberCol = Warning(); + + ImFont* ovFont = Type().overline(); + ImFont* sub1 = Type().subtitle1(); + ImFont* capFont = Type().caption(); + + float classicPadOverride = S.drawElement("tabs.balance.classic", "card-padding").size; + float cardPadLg = (classicPadOverride >= 0.0f) ? classicPadOverride : Layout::spacingLg(); + + // Card height: must fit the Market card's content (overline + price + 24h) + const float ovGap = S.drawElement("tabs.balance", "overline-value-gap").sizeOr(6.0f); + const float valGap = S.drawElement("tabs.balance", "value-caption-gap").sizeOr(4.0f); + const float tickGap = S.drawElement("tabs.balance.classic", "ticker-gap").sizeOr(4.0f); + float marketContentH = cardPadLg + + ovFont->LegacySize + ovGap + + sub1->LegacySize + 2.0f * dp + + capFont->LegacySize + + cardPadLg; + float classicCardH = S.drawElement("tabs.balance.classic", "card-height").size; + float cardH; + if (classicCardH >= 0.0f) { + cardH = classicCardH; // explicit override from ui.toml + } else { + float minH = S.drawElement("tabs.balance.classic", "card-min-height").sizeOr(70.0f); + cardH = std::max(StatCardHeight(vs, minH), marketContentH); + } + + // Helper: draw accent stripe on left edge, clipped to card rounded corners. + // We draw a full-size rounded rect (left corners only) and clip it to the + // stripe width so the shape itself follows the card rounding. + const float accentW = S.drawElement("tabs.balance", "accent-width").sizeOr(4.0f); + auto drawAccent = [&](const ImVec2& cMin, const ImVec2& cMax, ImU32 col) { + dl->PushClipRect(cMin, ImVec2(cMin.x + accentW, cMax.y), true); + dl->AddRectFilled(cMin, cMax, col, cardSpec.rounding, + ImDrawFlags_RoundCornersLeft); + dl->PopClipRect(); + }; + + // Helper: compute card position given card index (0-3) + auto cardPos = [&](int idx) -> ImVec2 { + int col = idx % numCols; + int row = idx / numCols; + return ImVec2(origin.x + col * (cardWidth + cardGap), + origin.y + row * (cardH + cardGap)); + }; + + // ---- Total Balance card ---- + { + ImVec2 cMin = cardPos(0); + ImVec2 cMax(cMin.x + cardWidth, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, cardSpec); + drawAccent(cMin, cMax, S.resolveColor("var(--accent-total)", OnSurface())); + + float cx = cMin.x + cardPadLg; + float cy = cMin.y + cardPadLg; + + // Coin logo (small, top-right corner) + ImTextureID logoTex = app->getCoinLogoTexture(); + if (logoTex != 0) { + float logoSz = ovFont->LegacySize + sub1->LegacySize + 4.0f * dp; + float logoX = cMax.x - cardPadLg - logoSz; + float logoY = cMin.y + cardPadLg; + dl->AddImage(logoTex, + ImVec2(logoX, logoY), + ImVec2(logoX + logoSz, logoY + logoSz), + ImVec2(0, 0), ImVec2(1, 1), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance.classic", "logo-opacity").sizeOr(180.0f))); + } + + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cx, cy), + OnSurfaceMedium(), "TOTAL BALANCE"); + cy += ovFont->LegacySize + ovGap; + + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), OnSurface(), buf); + ImVec2 balSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + balSz.x + tickGap, + cy + sub1->LegacySize - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + cy += sub1->LegacySize + valGap; + + // USD value + { + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) + snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else + snprintf(buf, sizeof(buf), "$-.-- USD"); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), + OnSurfaceDisabled(), buf); + } + cy += capFont->LegacySize + 2 * dp; + + // Sync progress or mining indicator (whichever fits) + if (state.sync.syncing && state.sync.headers > 0) { + float pct = static_cast(state.sync.verification_progress) * 100.0f; + snprintf(buf, sizeof(buf), "Syncing %.1f%%", pct); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), + Warning(), buf); + + // Thin sync bar at card bottom — clipped to card rounded corners + float barH = (syncBar.height >= 0) ? syncBar.height : 3.0f; + float prog = static_cast(state.sync.verification_progress); + if (prog > 1.0f) prog = 1.0f; + float barTop = cMax.y - barH; + // Clip to the bottom strip so the full-card rounded rect + // curves exactly match the card's own rounded corners + dl->PushClipRect(ImVec2(cMin.x, barTop), cMax, true); + // Background track + dl->AddRectFilled(cMin, cMax, + IM_COL32(255, 255, 255, 15), cardSpec.rounding); + // Progress fill — additional horizontal clip + float progRight = cMin.x + (cMax.x - cMin.x) * prog; + dl->PushClipRect(ImVec2(cMin.x, barTop), ImVec2(progRight, cMax.y), true); + dl->AddRectFilled(cMin, cMax, + WithAlpha(Warning(), 200), cardSpec.rounding); + dl->PopClipRect(); + dl->PopClipRect(); + } else if (state.mining.generate) { + float pulse = schema::UI().drawElement("animations", "pulse-base-normal").size + + schema::UI().drawElement("animations", "pulse-amp-normal").size + * (float)std::sin((double)ImGui::GetTime() + * schema::UI().drawElement("animations", "pulse-speed-normal").size); + ImU32 mineCol = WithAlpha(Success(), (int)(255.0f * pulse)); + dl->AddCircleFilled(ImVec2(cx + 4 * dp, cy + capFont->LegacySize * 0.5f), + S.drawElement("tabs.balance.classic", "mining-dot-radius").sizeOr(3.0f), mineCol); + double hr = state.mining.localHashrate; + if (hr >= 1000.0) + snprintf(buf, sizeof(buf), " Mining %.1f KH/s", hr / 1000.0); + else + snprintf(buf, sizeof(buf), " Mining %.0f H/s", hr); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + 12 * dp, cy), + WithAlpha(Success(), 200), buf); + } + + // Hover glow + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance", "hover-glow-alpha").sizeOr(40.0f)), + cardSpec.rounding, 0, S.drawElement("tabs.balance", "hover-glow-thickness").sizeOr(1.5f)); + } + } + + // ---- Shielded card ---- + { + ImVec2 cMin = cardPos(1); + ImVec2 cMax(cMin.x + cardWidth, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, cardSpec); + drawAccent(cMin, cMax, WithAlpha(S.resolveColor("var(--accent-shielded)", Success()), 200)); + + float cx = cMin.x + cardPadLg; + float cy = cMin.y + cardPadLg; + + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cx, cy), + OnSurfaceMedium(), TR("shielded")); + cy += ovFont->LegacySize + ovGap; + + snprintf(buf, sizeof(buf), "%.8f", s_dispShielded); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), greenCol, buf); + ImVec2 balSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + balSz.x + tickGap, + cy + sub1->LegacySize - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + cy += sub1->LegacySize + valGap; + + // Privacy ratio + address count + { + float privPct = (s_dispTotal > 1e-9) + ? (float)(s_dispShielded / s_dispTotal * 100.0) : 0.0f; + snprintf(buf, sizeof(buf), "%.0f%% of total · %d Z-addr", + privPct, (int)state.z_addresses.size()); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), + WithAlpha(Success(), 160), buf); + } + + // Unconfirmed badge (top-right corner) + if (state.unconfirmed_balance > 0.0) { + snprintf(buf, sizeof(buf), "+%.4f", state.unconfirmed_balance); + ImVec2 ts = capFont->CalcTextSizeA( + capFont->LegacySize, 10000, 0, buf); + float bp = S.drawElement("tabs.balance.classic", "unconfirmed-badge-padding").sizeOr(4.0f); + float br = S.drawElement("tabs.balance.classic", "unconfirmed-badge-rounding").sizeOr(4.0f); + ImVec2 bMin(cMax.x - ts.x - bp * 3, + cMin.y + cardPadLg); + ImVec2 bMax(cMax.x - bp, bMin.y + ts.y + bp); + dl->AddRectFilled(bMin, bMax, + WithAlpha(Warning(), 40), br); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(bMin.x + bp, bMin.y + bp * 0.5f), + amberCol, buf); + } + + // Hover glow + click to Receive + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance", "hover-glow-alpha").sizeOr(40.0f)), + cardSpec.rounding, 0, S.drawElement("tabs.balance", "hover-glow-thickness").sizeOr(1.5f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(NavPage::Receive); + } + } + + // ---- Transparent card ---- + { + ImVec2 cMin = cardPos(2); + ImVec2 cMax(cMin.x + cardWidth, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, cardSpec); + drawAccent(cMin, cMax, WithAlpha(S.resolveColor("var(--accent-transparent)", Warning()), 200)); + + float cx = cMin.x + cardPadLg; + float cy = cMin.y + cardPadLg; + + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cx, cy), + OnSurfaceMedium(), TR("transparent")); + cy += ovFont->LegacySize + ovGap; + + snprintf(buf, sizeof(buf), "%.8f", s_dispTransparent); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), goldCol, buf); + ImVec2 balSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + balSz.x + tickGap, + cy + sub1->LegacySize - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + cy += sub1->LegacySize + valGap; + + snprintf(buf, sizeof(buf), "%d T-addresses", + (int)state.t_addresses.size()); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), + OnSurfaceDisabled(), buf); + + // Hover glow + click to Receive + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance", "hover-glow-alpha").sizeOr(40.0f)), + cardSpec.rounding, 0, S.drawElement("tabs.balance", "hover-glow-thickness").sizeOr(1.5f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(NavPage::Receive); + } + } + + // ---- Market card ---- + { + ImVec2 cMin = cardPos(3); + ImVec2 cMax(cMin.x + cardWidth, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, cardSpec); + drawAccent(cMin, cMax, S.resolveColor("var(--accent-action)", Primary())); + + float cx = cMin.x + cardPadLg; + float cy = cMin.y + cardPadLg; + + // Price string (compute early to measure text width) + const auto& market = state.market; + if (market.price_usd > 0) { + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", market.price_usd); + else if (market.price_usd >= 0.0001) + snprintf(buf, sizeof(buf), "$%.6f", market.price_usd); + else + snprintf(buf, sizeof(buf), "$%.8f", market.price_usd); + } else { + snprintf(buf, sizeof(buf), "$--.--"); + } + ImVec2 pSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, buf); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, "USD"); + + // Measure widest text line to determine sparkline left edge + float textW = std::max(pSz.x + tickGap + usdSz.x, + ovFont->CalcTextSizeA(ovFont->LegacySize, 10000, 0, "MARKET").x); + float sparkGap = S.drawElement("tabs.balance.classic", "sparkline-gap").sizeOr(12.0f); + float sparkLeft = cx + textW + sparkGap; + float sparkRight = cMax.x - cardPadLg; + + // Left side: label + price + 24h change + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cx, cy), + OnSurfaceMedium(), "MARKET"); + cy += ovFont->LegacySize + ovGap; + + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), + OnSurface(), buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + pSz.x + tickGap, + cy + sub1->LegacySize - capFont->LegacySize), + OnSurfaceMedium(), "USD"); + cy += sub1->LegacySize + valGap; + + // 24h change + if (market.price_usd > 0) { + bool pos = market.change_24h >= 0; + ImU32 chgCol = pos ? Success() + : Error(); + snprintf(buf, sizeof(buf), "%s%.1f%% 24h", + pos ? "+" : "", market.change_24h); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx, cy), chgCol, buf); + } + + // Right side: sparkline fills remaining card space + if (market.price_history.size() >= 2 && sparkLeft < sparkRight) { + float spTop = cMin.y + cardPadLg; + float spBot = cMax.y - cardPadLg; + ImVec2 spMin(sparkLeft, spTop); + ImVec2 spMax(sparkRight, spBot); + ImU32 lineCol = market.change_24h >= 0 + ? WithAlpha(Success(), 200) + : WithAlpha(Error(), 200); + DrawSparkline(dl, spMin, spMax, + market.price_history, lineCol); + } + + // Hover glow + click to Market + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance", "hover-glow-alpha").sizeOr(40.0f)), + cardSpec.rounding, 0, S.drawElement("tabs.balance", "hover-glow-thickness").sizeOr(1.5f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(NavPage::Market); + } + } + + // Advance cursor past the card row(s) + { + int totalCards = 4; + int numRows = (totalCards + numCols - 1) / numCols; + ImGui::Dummy(ImVec2(availWidth, cardH * numRows + cardGap * (numRows - 1))); + } + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + } + + // ================================================================ + // Address list — DrawList-based rows (matches recent tx style) + // ================================================================ + { + // Header row: title only + Type().text(TypeStyle::H6, TR("your_addresses")); + + ImGui::Spacing(); + + // Static filter state (declared here, UI rendered below with ADDRESSES overline) + static char addr_search[128] = ""; + static bool s_hideZeroBalances = true; + static bool s_showHidden = false; + + // Build a merged + sorted list of all addresses + struct AddrRow { + const AddressInfo* info; + bool isZ; + bool hidden; + bool favorite; + }; + std::vector rows; + rows.reserve(state.z_addresses.size() + state.t_addresses.size()); + for (const auto& a : state.z_addresses) { + std::string filter(addr_search); + if (!containsIgnoreCase(a.address, filter) && + !containsIgnoreCase(a.label, filter)) + continue; + bool isHidden = app->isAddressHidden(a.address); + if (isHidden && !s_showHidden) continue; + bool isFav = app->isAddressFavorite(a.address); + if (s_hideZeroBalances && a.balance < 1e-9 && !isHidden && !isFav) + continue; + rows.push_back({&a, true, isHidden, isFav}); + } + for (const auto& a : state.t_addresses) { + std::string filter(addr_search); + if (!containsIgnoreCase(a.address, filter) && + !containsIgnoreCase(a.label, filter)) + continue; + bool isHidden = app->isAddressHidden(a.address); + if (isHidden && !s_showHidden) continue; + bool isFav = app->isAddressFavorite(a.address); + if (s_hideZeroBalances && a.balance < 1e-9 && !isHidden && !isFav) + continue; + rows.push_back({&a, false, isHidden, isFav}); + } + + // Sort: favorites first, then Z addresses, then by balance descending + static int s_sortCol = 3; // default sort by balance + static bool s_sortAsc = false; + std::sort(rows.begin(), rows.end(), + [](const AddrRow& a, const AddrRow& b) -> bool { + if (a.favorite != b.favorite) return a.favorite > b.favorite; + if (a.isZ != b.isZ) return a.isZ > b.isZ; // Z first + if (s_sortAsc) + return a.info->balance < b.info->balance; + else + return a.info->balance > b.info->balance; + }); + + // Recent TX gets sizing priority — compute its reserve first, + // then the address list gets whatever remains. + float scaledTxRowH = std::max(S.drawElement("tabs.balance", "recent-tx-row-min-height").size, kRecentTxRowHeight * vs); + // Recent TX section: header + kRecentTxCount rows + status label + gaps + float recentTxReserve = S.drawElement("tabs.balance", "recent-tx-header-height").size * vs + kRecentTxCount * scaledTxRowH + Layout::spacingXl(); + + // Search + create buttons row + float avail = ImGui::GetContentRegionAvail().x; + float schemaMaxW = (searchIn.maxWidth >= 0) ? searchIn.maxWidth : 250.0f; + float schemaRatio = (searchIn.widthRatio >= 0) ? searchIn.widthRatio : 0.30f; + float searchW = std::min(schemaMaxW * hs, avail * schemaRatio); + ImGui::SetNextItemWidth(searchW); + ImGui::InputTextWithHint("##AddrSearch", "Filter...", addr_search, sizeof(addr_search)); + + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::Checkbox("Hide 0 Balances", &s_hideZeroBalances); + { + int hc = app->getHiddenAddressCount(); + if (hc > 0) { + ImGui::SameLine(0, Layout::spacingLg()); + char hlbl[64]; + snprintf(hlbl, sizeof(hlbl), "Show Hidden (%d)", hc); + ImGui::Checkbox(hlbl, &s_showHidden); + } else { + s_showHidden = false; + } + } + + float buttonWidth = (addrBtn.width > 0) ? addrBtn.width : 140.0f; + float spacing = (addrBtn.gap > 0) ? addrBtn.gap : 8.0f; + float totalButtonsWidth = buttonWidth * 2 + spacing; + ImGui::SameLine(std::max(kMinButtonsPosition, + ImGui::GetWindowWidth() - totalButtonsWidth - kButtonRowRightMargin)); + + bool addrSyncing = state.sync.syncing && !state.sync.isSynced(); + ImGui::BeginDisabled(addrSyncing); + if (TactileButton(TR("new_z_address"), ImVec2(buttonWidth, 0), S.resolveFont(addrBtn.font.empty() ? "button" : addrBtn.font))) { + app->createNewZAddress([](const std::string& addr) { + DEBUG_LOGF("Created new z-address: %s\n", addr.c_str()); + }); + } + ImGui::SameLine(); + if (TactileButton(TR("new_t_address"), ImVec2(buttonWidth, 0), S.resolveFont(addrBtn.font.empty() ? "button" : addrBtn.font))) { + app->createNewTAddress([](const std::string& addr) { + DEBUG_LOGF("Created new t-address: %s\n", addr.c_str()); + }); + } + ImGui::EndDisabled(); + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + float availWidth = ImGui::GetContentRegionAvail().x; + // Address list gets whatever height remains after recent TX reserve + float classicAddrH = S.drawElement("tabs.balance.classic", "address-table-height").size; + float addrListH; + if (classicAddrH >= 0.0f) { + addrListH = classicAddrH; // explicit override from ui.toml + } else { + addrListH = ImGui::GetContentRegionAvail().y - recentTxReserve; + } + // Keep address list at a reasonable minimum; if too tight, + // shrink recent-tx reserve instead so both remain visible. + float addrListMin = S.drawElement("tabs.balance", "addr-list-min-height").sizeOr(40.0f); + if (addrListH < addrListMin) { + addrListH = addrListMin; + } + + // Glass panel wrapping the list area (matching tx list) + ImDrawList* dlPanel = ImGui::GetWindowDrawList(); + ImVec2 listPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 listPanelMax(listPanelMin.x + availWidth, listPanelMin.y + addrListH); + GlassPanelSpec addrGlassSpec; + addrGlassSpec.rounding = glassRound; + DrawGlassPanel(dlPanel, listPanelMin, listPanelMax, addrGlassSpec); + + // Scroll-edge mask state + float addrScrollY = 0.0f, addrScrollMaxY = 0.0f; + int addrParentVtx = dlPanel->VtxBuffer.Size; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(Layout::spacingLg(), Layout::spacingSm())); + ImGui::BeginChild("AddressList", ImVec2(availWidth, addrListH), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + ImDrawList* addrChildDL = ImGui::GetWindowDrawList(); + int addrChildVtx = addrChildDL->VtxBuffer.Size; + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (!app->isConnected()) { + ImGui::Dummy(ImVec2(0, 16 * dp)); + float cw = ImGui::GetContentRegionAvail().x; + ImVec2 ts = ImGui::CalcTextSize(TR("not_connected")); + ImGui::SetCursorPosX((cw - ts.x) * 0.5f); + ImGui::TextDisabled("%s", TR("not_connected")); + } else if (rows.empty()) { + // Empty state + float cw = ImGui::GetContentRegionAvail().x; + float ch = ImGui::GetContentRegionAvail().y; + if (ch < 60) ch = 60; + + if (addr_search[0]) { + ImVec2 textSz = ImGui::CalcTextSize("No matching addresses"); + ImGui::SetCursorPosX((cw - textSz.x) * 0.5f); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ch * 0.25f); + ImGui::TextDisabled("No matching addresses"); + } else { + const char* msg = "No addresses yet"; + ImVec2 msgSz = ImGui::CalcTextSize(msg); + ImGui::SetCursorPosX((cw - msgSz.x) * 0.5f); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ch * 0.25f); + ImGui::TextDisabled("%s", msg); + } + } else { + // DrawList-based address rows (matching transaction list style) + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd(); + static int selected_row = -1; + addrScrollY = ImGui::GetScrollY(); + addrScrollMaxY = ImGui::GetScrollMaxY(); + + ImU32 greenCol = S.resolveColor("var(--accent-shielded)", Success()); + ImU32 goldCol = S.resolveColor("var(--accent-transparent)", Warning()); + float rowPadLeft = Layout::spacingLg(); + float rowIconSz = std::max(S.drawElement("tabs.balance", "address-icon-min-size").size, S.drawElement("tabs.balance", "address-icon-size").size * hs); + float innerW = ImGui::GetContentRegionAvail().x; + + for (int row_idx = 0; row_idx < (int)rows.size(); row_idx++) { + const auto& row = rows[row_idx]; + const auto& addr = *row.info; + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + + ImU32 typeCol = row.isZ ? greenCol : goldCol; + if (row.hidden) typeCol = OnSurfaceDisabled(); + + // Golden border for favorites + if (row.favorite) { + ImU32 favBorder = IM_COL32(255, 200, 50, 120); + dl->AddRect(rowPos, rowEnd, favBorder, 4.0f * dp, 0, 1.5f * dp); + } + + // Selected indicator (left accent bar) + if (selected_row == row_idx) { + ImDrawFlags accentFlags = 0; + float accentRound = 2.0f * dp; + if (row_idx == 0) { + accentFlags = ImDrawFlags_RoundCornersTopLeft; + accentRound = glassRound; + } + if (row_idx == (int)rows.size() - 1) { + accentFlags |= ImDrawFlags_RoundCornersBottomLeft; + accentRound = glassRound; + } + dl->AddRectFilled(rowPos, ImVec2(rowPos.x + 3 * dp, rowEnd.y), typeCol, accentRound, accentFlags); + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 20), 4.0f * dp); + } + + // Hover glow + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered && selected_row != row_idx) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), 4.0f * dp); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + float cx = rowPos.x + rowPadLeft; + float cy = rowPos.y + Layout::spacingMd(); + + // --- Button zone (right edge): [eye] [star] --- + float btnH = rowH - Layout::spacingSm() * 2.0f; + float btnW = btnH; + float btnGap = Layout::spacingXs(); + float btnY = rowPos.y + (rowH - btnH) * 0.5f; + float rightEdge = rowPos.x + innerW; + float starX = rightEdge - btnW - Layout::spacingSm(); + float eyeX = starX - btnGap - btnW; + float btnRound = 6.0f * dp; + bool btnClicked = false; + + // Star button (always shown, rightmost) + { + ImVec2 bMin(starX, btnY), bMax(starX + btnW, btnY + btnH); + bool bHov = ImGui::IsMouseHoveringRect(bMin, bMax); + ImU32 starFill = row.favorite ? IM_COL32(255, 200, 50, 40) : IM_COL32(255, 255, 255, bHov ? 25 : 12); + ImU32 starBorder = row.favorite ? IM_COL32(255, 200, 50, 100) : IM_COL32(255, 255, 255, bHov ? 50 : 25); + dl->AddRectFilled(bMin, bMax, starFill, btnRound); + dl->AddRect(bMin, bMax, starBorder, btnRound, 0, 1.0f * dp); + ImFont* iconFont = material::Type().iconSmall(); + const char* starIcon = row.favorite ? ICON_MD_STAR : ICON_MD_STAR_BORDER; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, starIcon); + ImU32 starCol = row.favorite ? IM_COL32(255, 200, 50, 255) : (bHov ? OnSurface() : OnSurfaceDisabled()); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(starX + (btnW - iSz.x) * 0.5f, btnY + (btnH - iSz.y) * 0.5f), starCol, starIcon); + if (bHov && ImGui::IsMouseClicked(0)) { + if (row.favorite) app->unfavoriteAddress(addr.address); + else app->favoriteAddress(addr.address); + btnClicked = true; + } + if (bHov) ImGui::SetTooltip("%s", row.favorite ? "Remove favorite" : "Favorite address"); + } + + // Eye button (zero balance or hidden) + if (addr.balance < 1e-9 || row.hidden) { + ImVec2 bMin(eyeX, btnY), bMax(eyeX + btnW, btnY + btnH); + bool bHov = ImGui::IsMouseHoveringRect(bMin, bMax); + ImU32 eyeFill = IM_COL32(255, 255, 255, bHov ? 25 : 12); + ImU32 eyeBorder = IM_COL32(255, 255, 255, bHov ? 50 : 25); + dl->AddRectFilled(bMin, bMax, eyeFill, btnRound); + dl->AddRect(bMin, bMax, eyeBorder, btnRound, 0, 1.0f * dp); + ImFont* iconFont = material::Type().iconSmall(); + const char* hideIcon = row.hidden ? ICON_MD_VISIBILITY : ICON_MD_VISIBILITY_OFF; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, hideIcon); + ImU32 iconCol = bHov ? OnSurface() : OnSurfaceDisabled(); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(eyeX + (btnW - iSz.x) * 0.5f, btnY + (btnH - iSz.y) * 0.5f), iconCol, hideIcon); + if (bHov && ImGui::IsMouseClicked(0)) { + if (row.hidden) app->unhideAddress(addr.address); + else app->hideAddress(addr.address); + btnClicked = true; + } + if (bHov) ImGui::SetTooltip("%s", row.hidden ? "Restore address" : "Hide address"); + } + + // Content zone ends before buttons + float contentRight = eyeX - Layout::spacingSm(); + + // Type icon (shield for Z, circle for T) + float iconCx = cx + rowIconSz; + float iconCy = cy + body2->LegacySize * 0.5f; + if (row.isZ) { + ImFont* iconFont = material::Type().iconSmall(); + const char* shieldIcon = ICON_MD_SHIELD; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, shieldIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(iconCx - iSz.x * 0.5f, iconCy - iSz.y * 0.5f), typeCol, shieldIcon); + } else { + ImFont* iconFont = material::Type().iconSmall(); + const char* circIcon = ICON_MD_CIRCLE; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, circIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(iconCx - iSz.x * 0.5f, iconCy - iSz.y * 0.5f), typeCol, circIcon); + } + + // Type label (first line, next to icon) + float labelX = cx + rowIconSz * 2.0f + Layout::spacingSm(); + const char* typeLabel = row.isZ ? "Shielded" : "Transparent"; + const char* hiddenTag = row.hidden ? " (hidden)" : ""; + char typeBuf[64]; + snprintf(typeBuf, sizeof(typeBuf), "%s%s", typeLabel, hiddenTag); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy), typeCol, typeBuf); + + // Label (if present, next to type) + if (!addr.label.empty()) { + float typeLabelW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, typeBuf).x; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(labelX + typeLabelW + Layout::spacingLg(), cy), + OnSurfaceMedium(), addr.label.c_str()); + } + + // Address (second line) — show full if it fits, otherwise truncate + float addrAvailW = contentRight - labelX; + ImVec2 fullAddrSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, addr.address.c_str()); + std::string display_addr; + if (fullAddrSz.x <= addrAvailW) { + display_addr = addr.address; + } else { + int addrTruncLen = (addrTable.columns.count("address") && addrTable.columns.at("address").truncate > 0) + ? addrTable.columns.at("address").truncate : 32; + display_addr = truncateAddress(addr.address, addrTruncLen); + } + dl->AddText(capFont, capFont->LegacySize, + ImVec2(labelX, cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceMedium(), display_addr.c_str()); + + // Balance (right-aligned within content zone) + char balBuf[32]; + snprintf(balBuf, sizeof(balBuf), "%.8f", addr.balance); + ImVec2 balSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, balBuf); + float balX = contentRight - balSz.x; + ImU32 balCol = addr.balance > 0.0 + ? (row.isZ ? greenCol : OnSurface()) + : OnSurfaceDisabled(); + if (row.hidden) balCol = OnSurfaceDisabled(); + DrawTextShadow(dl, body2, body2->LegacySize, ImVec2(balX, cy), balCol, balBuf); + + // USD equivalent (right-aligned, second line) + double priceUsd = state.market.price_usd; + if (priceUsd > 0.0 && addr.balance > 0.0) { + char usdBuf[32]; + double usdVal = addr.balance * priceUsd; + if (usdVal >= 1.0) + snprintf(usdBuf, sizeof(usdBuf), "$%.2f", usdVal); + else if (usdVal >= 0.01) + snprintf(usdBuf, sizeof(usdBuf), "$%.4f", usdVal); + else + snprintf(usdBuf, sizeof(usdBuf), "$%.6f", usdVal); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, usdBuf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(contentRight - usdSz.x, + cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceDisabled(), usdBuf); + } + + // Click to copy + select + if (hovered && ImGui::IsMouseClicked(0) && !btnClicked) { + ImGui::SetClipboardText(addr.address.c_str()); + selected_row = row_idx; + } + + // Invisible button for context menu + tooltip + ImGui::PushID(row_idx); + ImGui::InvisibleButton("##addr", ImVec2(innerW, rowH)); + + // Tooltip with full address + if (ImGui::IsItemHovered() && !btnClicked) { + ImGui::SetTooltip("%s", addr.address.c_str()); + } + + // Right-click context menu + const auto& acrTheme = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicContextItem("AddressContext", 0, acrTheme.menu)) { + if (ImGui::MenuItem(TR("copy_address"))) { + ImGui::SetClipboardText(addr.address.c_str()); + } + if (ImGui::MenuItem(TR("send_from_this_address"))) { + SetSendFromAddress(addr.address); + app->setCurrentPage(NavPage::Send); + } + ImGui::Separator(); + if (ImGui::MenuItem(TR("export_private_key"))) { + KeyExportDialog::show(addr.address, KeyExportDialog::KeyType::Private); + } + if (row.isZ) { + if (ImGui::MenuItem(TR("export_viewing_key"))) { + KeyExportDialog::show(addr.address, KeyExportDialog::KeyType::Viewing); + } + } + if (ImGui::MenuItem(TR("show_qr_code"))) { + QRPopupDialog::show(addr.address, + row.isZ ? "Z-Address" : "T-Address"); + } + ImGui::Separator(); + if (row.hidden) { + if (ImGui::MenuItem("Restore Address")) + app->unhideAddress(addr.address); + } else if (addr.balance < 1e-9) { + if (ImGui::MenuItem("Hide Address")) + app->hideAddress(addr.address); + } + if (row.favorite) { + if (ImGui::MenuItem("Remove Favorite")) + app->unfavoriteAddress(addr.address); + } else { + if (ImGui::MenuItem("Favorite Address")) + app->favoriteAddress(addr.address); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopID(); + + // Subtle divider between rows (matching tx list) + if (row_idx < (int)rows.size() - 1 && selected_row != row_idx) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine( + ImVec2(divStart.x + rowPadLeft + rowIconSz * 2.0f, divStart.y), + ImVec2(divStart.x + innerW - Layout::spacingLg(), divStart.y), + IM_COL32(255, 255, 255, 15)); + } + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImGui::EndChild(); + ImGui::PopStyleVar(); // WindowPadding for address list + + // CSS-style clipping mask (same as history list) + { + float fadeZone = std::min( + (Type().body2()->LegacySize + Type().caption()->LegacySize + Layout::spacingLg() + Layout::spacingMd()) * 1.2f, + addrListH * 0.18f); + ApplyScrollEdgeMask(dlPanel, addrParentVtx, addrChildDL, addrChildVtx, + listPanelMin.y, listPanelMax.y, fadeZone, addrScrollY, addrScrollMaxY); + } + + // Status line (matching tx list) + { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + char countBuf[128]; + int totalAddrs = (int)(state.z_addresses.size() + state.t_addresses.size()); + snprintf(countBuf, sizeof(countBuf), "Showing %d of %d addresses", + (int)rows.size(), totalAddrs); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), countBuf); + } + } + + // ================================================================ + // Recent Transactions + // ================================================================ + { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT TRANSACTIONS"); + ImGui::SameLine(); + if (TactileSmallButton("View All", S.resolveFont(actionBtn.font.empty() ? "button" : actionBtn.font))) { + app->setCurrentPage(NavPage::History); + } + ImGui::Spacing(); + + const auto& txs = state.transactions; + int maxTx = kRecentTxCount; + int count = (int)txs.size(); + if (count > maxTx) count = maxTx; + + if (count == 0) { + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), + "No transactions yet"); + } else { + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + float rowH = std::max(18.0f * dp, kRecentTxRowHeight * vs); + float iconSz = std::max(S.drawElement("tabs.balance", "recent-tx-icon-min-size").size, S.drawElement("tabs.balance", "recent-tx-icon-size").size * hs); + + for (int i = 0; i < count; i++) { + const auto& tx = txs[i]; + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + float rowY = rowPos.y + rowH * 0.5f; + + // Icon + ImU32 iconCol; + if (tx.type == "send") + iconCol = Error(); + else if (tx.type == "receive") + iconCol = Success(); + else + iconCol = Warning(); + DrawTxIcon(dl, tx.type, rowPos.x + Layout::spacingMd(), rowY, iconSz, iconCol); + + // Type label + float tx_x = rowPos.x + Layout::spacingMd() + iconSz * 2.0f + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(tx_x, rowPos.y + 2 * dp), + OnSurfaceMedium(), tx.getTypeDisplay().c_str()); + + // Address (truncated) + float addrX = tx_x + S.drawElement("tabs.balance", "recent-tx-addr-offset").sizeOr(65.0f); + std::string trAddr = truncateAddress(tx.address, (int)S.drawElement("tabs.balance", "recent-tx-addr-trunc").sizeOr(20.0f)); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(addrX, rowPos.y + 2 * dp), + OnSurfaceDisabled(), trAddr.c_str()); + + // Amount (right-aligned area) + char amtBuf[32]; + snprintf(amtBuf, sizeof(amtBuf), "%s%.4f %s", + tx.type == "send" ? "-" : "+", + std::abs(tx.amount), DRAGONX_TICKER); + ImVec2 amtSz = capFont->CalcTextSizeA( + capFont->LegacySize, 10000, 0, amtBuf); + float rightEdge = rowPos.x + ImGui::GetContentRegionAvail().x; + float amtX = rightEdge - amtSz.x - std::max(S.drawElement("tabs.balance", "amount-right-min-margin").size, S.drawElement("tabs.balance", "amount-right-margin").size * hs); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(amtX, rowPos.y + 2 * dp), + tx.type == "send" ? Error() + : Success(), + amtBuf); + + // Time ago + std::string ago = timeAgo(tx.timestamp); + ImVec2 agoSz = capFont->CalcTextSizeA( + capFont->LegacySize, 10000, 0, ago.c_str()); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rightEdge - agoSz.x - S.drawElement("tabs.balance", "recent-tx-time-margin").sizeOr(4.0f), rowPos.y + 2 * dp), + OnSurfaceDisabled(), ago.c_str()); + + // Clickable row — hover highlight + navigate to History + float rowW = ImGui::GetContentRegionAvail().x; + ImVec2 rowEnd(rowPos.x + rowW, rowPos.y + rowH); + if (material::IsRectHovered(rowPos, rowEnd)) { + dl->AddRectFilled(rowPos, rowEnd, + IM_COL32(255, 255, 255, 15), S.drawElement("tabs.balance", "row-hover-rounding").sizeOr(4.0f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(NavPage::History); + } + + ImGui::Dummy(ImVec2(0, rowH)); + } + } + } +} + +// ============================================================================ +// Shared helpers used by multiple layouts +// ============================================================================ + +// Update animated lerp balances — called at the top of every layout +static void UpdateBalanceLerp(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const float kBalanceLerpSpeed = S.drawElement("tabs.balance", "balance-lerp-speed").sizeOr(8.0f); + const auto& state = app->state(); + float dt = ImGui::GetIO().DeltaTime; + float speed = kBalanceLerpSpeed; + auto lerp = [](double& disp, double target, float dt, float spd) { + double diff = target - disp; + if (std::abs(diff) < 1e-9) { disp = target; return; } + disp += diff * (double)(dt * spd); + if (std::abs(target - disp) < 1e-9) disp = target; + }; + lerp(s_dispTotal, app->getTotalBalance(), dt, speed); + lerp(s_dispShielded, app->getShieldedBalance(), dt, speed); + lerp(s_dispTransparent, app->getTransparentBalance(), dt, speed); + lerp(s_dispUnconfirmed, state.unconfirmed_balance, dt, speed); +} + +// Render compact hero line: logo + balance + USD + mining on one line +static void RenderCompactHero(App* app, ImDrawList* dl, float availW, float hs, float vs, float heroHeightOverride = -1.0f) { + using namespace material; + char buf[64]; + const float dp = Layout::dpiScale(); + + // Coin logo + ImTextureID logoTex = app->getCoinLogoTexture(); + ImFont* sub1 = Type().subtitle1(); + float logoSz = sub1->LegacySize + 4.0f * dp; + float lineH = (heroHeightOverride >= 0.0f) ? heroHeightOverride : logoSz; + if (logoTex != 0) { + ImVec2 pos = ImGui::GetCursorScreenPos(); + dl->AddImage(logoTex, + ImVec2(pos.x, pos.y), + ImVec2(pos.x + lineH, pos.y + lineH), + ImVec2(0, 0), ImVec2(1, 1), IM_COL32(255, 255, 255, 255)); + ImGui::Dummy(ImVec2(lineH + Layout::spacingSm(), lineH)); + ImGui::SameLine(); + } + + // Total balance + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + ImVec2 pos = ImGui::GetCursorScreenPos(); + float fontSize = (heroHeightOverride >= 0.0f) ? heroHeightOverride : sub1->LegacySize; + DrawTextShadow(dl, sub1, fontSize, pos, OnSurface(), buf); + ImVec2 sz = sub1->CalcTextSizeA(fontSize, 10000.0f, 0.0f, buf); + ImGui::Dummy(ImVec2(sz.x, lineH)); + ImGui::SameLine(); + + // Ticker + ImFont* capFont = Type().caption(); + float tickerFontSize = (heroHeightOverride >= 0.0f) ? heroHeightOverride * 0.6f : capFont->LegacySize; + float tickerY = pos.y + lineH - tickerFontSize; + dl->AddText(capFont, tickerFontSize, + ImVec2(ImGui::GetCursorScreenPos().x, tickerY), + OnSurfaceMedium(), DRAGONX_TICKER); + ImGui::Dummy(ImVec2(capFont->CalcTextSizeA(tickerFontSize, 10000, 0, DRAGONX_TICKER).x + Layout::spacingLg(), lineH)); + ImGui::SameLine(); + + // USD value + const auto& state = app->state(); + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) + snprintf(buf, sizeof(buf), "$%.2f", usd_value); + else + snprintf(buf, sizeof(buf), "$--.--"); + dl->AddText(capFont, tickerFontSize, + ImVec2(ImGui::GetCursorScreenPos().x, tickerY), + OnSurfaceDisabled(), buf); + + ImGui::NewLine(); +} + +// Render the shared address list section (used by all layouts) +static void RenderSharedAddressList(App* app, float listH, float availW, + float glassRound, float hs, float vs) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const float dp = Layout::dpiScale(); + const auto addrBtn = S.button("tabs.balance", "address-button"); + const auto actionBtn = S.button("tabs.balance", "action-button"); + const auto searchIn = S.input("tabs.balance", "search-input"); + const auto addrTable = S.table("tabs.balance", "address-table"); + const auto& state = app->state(); + + Type().text(TypeStyle::H6, TR("your_addresses")); + ImGui::Spacing(); + + static char addr_search[128] = ""; + static bool s_hideZeroBalances = true; + static bool s_showHidden = false; + + struct AddrRow { const AddressInfo* info; bool isZ; bool hidden; bool favorite; }; + std::vector rows; + rows.reserve(state.z_addresses.size() + state.t_addresses.size()); + for (const auto& a : state.z_addresses) { + std::string filter(addr_search); + if (!containsIgnoreCase(a.address, filter) && + !containsIgnoreCase(a.label, filter)) continue; + bool isHidden = app->isAddressHidden(a.address); + if (isHidden && !s_showHidden) continue; + bool isFav = app->isAddressFavorite(a.address); + if (s_hideZeroBalances && a.balance < 1e-9 && !isHidden && !isFav) continue; + rows.push_back({&a, true, isHidden, isFav}); + } + for (const auto& a : state.t_addresses) { + std::string filter(addr_search); + if (!containsIgnoreCase(a.address, filter) && + !containsIgnoreCase(a.label, filter)) continue; + bool isHidden = app->isAddressHidden(a.address); + if (isHidden && !s_showHidden) continue; + bool isFav = app->isAddressFavorite(a.address); + if (s_hideZeroBalances && a.balance < 1e-9 && !isHidden && !isFav) continue; + rows.push_back({&a, false, isHidden, isFav}); + } + static int s_sortCol = 3; + static bool s_sortAsc = false; + std::sort(rows.begin(), rows.end(), + [](const AddrRow& a, const AddrRow& b) -> bool { + if (a.favorite != b.favorite) return a.favorite > b.favorite; + if (a.isZ != b.isZ) return a.isZ > b.isZ; + if (s_sortAsc) return a.info->balance < b.info->balance; + else return a.info->balance > b.info->balance; + }); + + // Search + create buttons row + float avail = ImGui::GetContentRegionAvail().x; + float schemaMaxW = (searchIn.maxWidth >= 0) ? searchIn.maxWidth : 250.0f; + float schemaRatio = (searchIn.widthRatio >= 0) ? searchIn.widthRatio : 0.30f; + float searchW = std::min(schemaMaxW * hs, avail * schemaRatio); + ImGui::SetNextItemWidth(searchW); + ImGui::InputTextWithHint("##AddrSearch", "Filter...", addr_search, sizeof(addr_search)); + ImGui::SameLine(0, Layout::spacingLg()); + ImGui::Checkbox("Hide 0 Balances", &s_hideZeroBalances); + { + int hc = app->getHiddenAddressCount(); + if (hc > 0) { + ImGui::SameLine(0, Layout::spacingLg()); + char hlbl[64]; + snprintf(hlbl, sizeof(hlbl), "Show Hidden (%d)", hc); + ImGui::Checkbox(hlbl, &s_showHidden); + } else { + s_showHidden = false; + } + } + + float buttonWidth = (addrBtn.width > 0) ? addrBtn.width : 140.0f; + float spacing = (addrBtn.gap > 0) ? addrBtn.gap : 8.0f; + float totalButtonsWidth = buttonWidth * 2 + spacing; + float kMinButtonsPosition = std::max(S.drawElement("tabs.balance", "min-buttons-position").size, + S.drawElement("tabs.balance", "buttons-position").size * hs); + ImGui::SameLine(std::max(kMinButtonsPosition, + ImGui::GetWindowWidth() - totalButtonsWidth - + S.drawElement("tabs.balance", "button-row-right-margin").sizeOr(16.0f))); + + bool sharedAddrSyncing = state.sync.syncing && !state.sync.isSynced(); + ImGui::BeginDisabled(sharedAddrSyncing); + if (TactileButton(TR("new_z_address"), ImVec2(buttonWidth, 0), + S.resolveFont(addrBtn.font.empty() ? "button" : addrBtn.font))) { + app->createNewZAddress([](const std::string& addr) { + DEBUG_LOGF("Created new z-address: %s\n", addr.c_str()); + }); + } + ImGui::SameLine(); + if (TactileButton(TR("new_t_address"), ImVec2(buttonWidth, 0), + S.resolveFont(addrBtn.font.empty() ? "button" : addrBtn.font))) { + app->createNewTAddress([](const std::string& addr) { + DEBUG_LOGF("Created new t-address: %s\n", addr.c_str()); + }); + } + ImGui::EndDisabled(); + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + float addrListH = listH; + if (addrListH < 40.0f * dp) addrListH = 40.0f * dp; + + ImDrawList* dlPanel = ImGui::GetWindowDrawList(); + ImVec2 listPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 listPanelMax(listPanelMin.x + availW, listPanelMin.y + addrListH); + GlassPanelSpec addrGlassSpec; + addrGlassSpec.rounding = glassRound; + DrawGlassPanel(dlPanel, listPanelMin, listPanelMax, addrGlassSpec); + + float addrScrollY = 0.0f, addrScrollMaxY = 0.0f; + int addrParentVtx = dlPanel->VtxBuffer.Size; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(Layout::spacingLg(), Layout::spacingSm())); + ImGui::BeginChild("AddressList", ImVec2(availW, addrListH), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + ImDrawList* addrChildDL = ImGui::GetWindowDrawList(); + int addrChildVtx = addrChildDL->VtxBuffer.Size; + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (!app->isConnected()) { + ImGui::Dummy(ImVec2(0, 16 * dp)); + float cw = ImGui::GetContentRegionAvail().x; + ImVec2 ts = ImGui::CalcTextSize(TR("not_connected")); + ImGui::SetCursorPosX((cw - ts.x) * 0.5f); + ImGui::TextDisabled("%s", TR("not_connected")); + } else if (rows.empty()) { + float cw = ImGui::GetContentRegionAvail().x; + float ch = ImGui::GetContentRegionAvail().y; + if (ch < 60) ch = 60; + if (addr_search[0]) { + ImVec2 textSz = ImGui::CalcTextSize("No matching addresses"); + ImGui::SetCursorPosX((cw - textSz.x) * 0.5f); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ch * 0.25f); + ImGui::TextDisabled("No matching addresses"); + } else { + const char* msg = "No addresses yet"; + ImVec2 msgSz = ImGui::CalcTextSize(msg); + ImGui::SetCursorPosX((cw - msgSz.x) * 0.5f); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ch * 0.25f); + ImGui::TextDisabled("%s", msg); + } + } else { + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd(); + static int selected_row = -1; + addrScrollY = ImGui::GetScrollY(); + addrScrollMaxY = ImGui::GetScrollMaxY(); + ImU32 greenCol = S.resolveColor("var(--accent-shielded)", Success()); + ImU32 goldCol = S.resolveColor("var(--accent-transparent)", Warning()); + float rowPadLeft = Layout::spacingLg(); + float rowIconSz = std::max(S.drawElement("tabs.balance", "address-icon-min-size").size, + S.drawElement("tabs.balance", "address-icon-size").size * hs); + float innerW = ImGui::GetContentRegionAvail().x; + + for (int row_idx = 0; row_idx < (int)rows.size(); row_idx++) { + const auto& row = rows[row_idx]; + const auto& addr = *row.info; + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + ImU32 typeCol = row.isZ ? greenCol : goldCol; + if (row.hidden) typeCol = OnSurfaceDisabled(); + + // Golden border for favorites + if (row.favorite) { + ImU32 favBorder = IM_COL32(255, 200, 50, 120); + dl->AddRect(rowPos, rowEnd, favBorder, 4.0f * dp, 0, 1.5f * dp); + } + + if (selected_row == row_idx) { + ImDrawFlags accentFlags = 0; + float accentRound = 2.0f * dp; + if (row_idx == 0) { accentFlags = ImDrawFlags_RoundCornersTopLeft; accentRound = glassRound; } + if (row_idx == (int)rows.size() - 1) { accentFlags |= ImDrawFlags_RoundCornersBottomLeft; accentRound = glassRound; } + dl->AddRectFilled(rowPos, ImVec2(rowPos.x + 3 * dp, rowEnd.y), typeCol, accentRound, accentFlags); + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 20), 4.0f * dp); + } + + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered && selected_row != row_idx) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), 4.0f * dp); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + float cx = rowPos.x + rowPadLeft; + float cy = rowPos.y + Layout::spacingMd(); + + // --- Button zone (right edge): [eye] [star] --- + float btnH = rowH - Layout::spacingSm() * 2.0f; + float btnW = btnH; + float btnGap = Layout::spacingXs(); + float btnY = rowPos.y + (rowH - btnH) * 0.5f; + float rightEdge = rowPos.x + innerW; + float starX = rightEdge - btnW - Layout::spacingSm(); + float eyeX = starX - btnGap - btnW; + float btnRound = 6.0f * dp; + bool btnClicked = false; + + // Star button (always shown, rightmost) + { + ImVec2 bMin(starX, btnY), bMax(starX + btnW, btnY + btnH); + bool bHov = ImGui::IsMouseHoveringRect(bMin, bMax); + ImU32 starFill = row.favorite ? IM_COL32(255, 200, 50, 40) : IM_COL32(255, 255, 255, bHov ? 25 : 12); + ImU32 starBorder = row.favorite ? IM_COL32(255, 200, 50, 100) : IM_COL32(255, 255, 255, bHov ? 50 : 25); + dl->AddRectFilled(bMin, bMax, starFill, btnRound); + dl->AddRect(bMin, bMax, starBorder, btnRound, 0, 1.0f * dp); + ImFont* iconFont = material::Type().iconSmall(); + const char* starIcon = row.favorite ? ICON_MD_STAR : ICON_MD_STAR_BORDER; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, starIcon); + ImU32 starCol = row.favorite ? IM_COL32(255, 200, 50, 255) : (bHov ? OnSurface() : OnSurfaceDisabled()); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(starX + (btnW - iSz.x) * 0.5f, btnY + (btnH - iSz.y) * 0.5f), starCol, starIcon); + if (bHov && ImGui::IsMouseClicked(0)) { + if (row.favorite) app->unfavoriteAddress(addr.address); + else app->favoriteAddress(addr.address); + btnClicked = true; + } + if (bHov) ImGui::SetTooltip("%s", row.favorite ? "Remove favorite" : "Favorite address"); + } + + // Eye button (zero balance or hidden) + if (addr.balance < 1e-9 || row.hidden) { + ImVec2 bMin(eyeX, btnY), bMax(eyeX + btnW, btnY + btnH); + bool bHov = ImGui::IsMouseHoveringRect(bMin, bMax); + ImU32 eyeFill = IM_COL32(255, 255, 255, bHov ? 25 : 12); + ImU32 eyeBorder = IM_COL32(255, 255, 255, bHov ? 50 : 25); + dl->AddRectFilled(bMin, bMax, eyeFill, btnRound); + dl->AddRect(bMin, bMax, eyeBorder, btnRound, 0, 1.0f * dp); + ImFont* iconFont = material::Type().iconSmall(); + const char* hideIcon = row.hidden ? ICON_MD_VISIBILITY : ICON_MD_VISIBILITY_OFF; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, hideIcon); + ImU32 iconCol = bHov ? OnSurface() : OnSurfaceDisabled(); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(eyeX + (btnW - iSz.x) * 0.5f, btnY + (btnH - iSz.y) * 0.5f), iconCol, hideIcon); + if (bHov && ImGui::IsMouseClicked(0)) { + if (row.hidden) app->unhideAddress(addr.address); + else app->hideAddress(addr.address); + btnClicked = true; + } + if (bHov) ImGui::SetTooltip("%s", row.hidden ? "Restore address" : "Hide address"); + } + + // Content zone ends before buttons + float contentRight = eyeX - Layout::spacingSm(); + + float iconCx = cx + rowIconSz; + float iconCy = cy + body2->LegacySize * 0.5f; + if (row.isZ) { + ImFont* iconFont = material::Type().iconSmall(); + const char* shieldIcon = ICON_MD_SHIELD; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, shieldIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(iconCx - iSz.x * 0.5f, iconCy - iSz.y * 0.5f), typeCol, shieldIcon); + } else { + ImFont* iconFont = material::Type().iconSmall(); + const char* circIcon = ICON_MD_CIRCLE; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, circIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(iconCx - iSz.x * 0.5f, iconCy - iSz.y * 0.5f), typeCol, circIcon); + } + + float labelX = cx + rowIconSz * 2.0f + Layout::spacingSm(); + const char* typeLabel = row.isZ ? "Shielded" : "Transparent"; + const char* hiddenTag = row.hidden ? " (hidden)" : ""; + char typeBuf[64]; + snprintf(typeBuf, sizeof(typeBuf), "%s%s", typeLabel, hiddenTag); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy), typeCol, typeBuf); + if (!addr.label.empty()) { + float typeLabelW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, typeBuf).x; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(labelX + typeLabelW + Layout::spacingLg(), cy), + OnSurfaceMedium(), addr.label.c_str()); + } + + // Address (second line) — show full if it fits, otherwise truncate + float addrAvailW = contentRight - labelX; + ImVec2 fullAddrSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0.0f, addr.address.c_str()); + std::string display_addr; + if (fullAddrSz.x <= addrAvailW) { + display_addr = addr.address; + } else { + int addrTruncLen = (addrTable.columns.count("address") && addrTable.columns.at("address").truncate > 0) + ? addrTable.columns.at("address").truncate : 32; + display_addr = truncateAddress(addr.address, addrTruncLen); + } + dl->AddText(capFont, capFont->LegacySize, + ImVec2(labelX, cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceMedium(), display_addr.c_str()); + + // Balance (right-aligned within content zone) + char balBuf[32]; + snprintf(balBuf, sizeof(balBuf), "%.8f", addr.balance); + ImVec2 balSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, balBuf); + float balX = contentRight - balSz.x; + ImU32 balCol = addr.balance > 0.0 + ? (row.isZ ? greenCol : OnSurface()) + : OnSurfaceDisabled(); + if (row.hidden) balCol = OnSurfaceDisabled(); + DrawTextShadow(dl, body2, body2->LegacySize, ImVec2(balX, cy), balCol, balBuf); + + double priceUsd = state.market.price_usd; + if (priceUsd > 0.0 && addr.balance > 0.0) { + char usdBuf[32]; + double usdVal = addr.balance * priceUsd; + if (usdVal >= 1.0) snprintf(usdBuf, sizeof(usdBuf), "$%.2f", usdVal); + else if (usdVal >= 0.01) snprintf(usdBuf, sizeof(usdBuf), "$%.4f", usdVal); + else snprintf(usdBuf, sizeof(usdBuf), "$%.6f", usdVal); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, usdBuf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(contentRight - usdSz.x, + cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceDisabled(), usdBuf); + } + + if (hovered && ImGui::IsMouseClicked(0) && !btnClicked) { + ImGui::SetClipboardText(addr.address.c_str()); + selected_row = row_idx; + } + + ImGui::PushID(row_idx); + ImGui::InvisibleButton("##addr", ImVec2(innerW, rowH)); + if (ImGui::IsItemHovered() && !btnClicked) ImGui::SetTooltip("%s", addr.address.c_str()); + const auto& acrTheme = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicContextItem("AddressContext", 0, acrTheme.menu)) { + if (ImGui::MenuItem(TR("copy_address"))) ImGui::SetClipboardText(addr.address.c_str()); + if (ImGui::MenuItem(TR("send_from_this_address"))) { + SetSendFromAddress(addr.address); + app->setCurrentPage(NavPage::Send); + } + ImGui::Separator(); + if (ImGui::MenuItem(TR("export_private_key"))) + KeyExportDialog::show(addr.address, KeyExportDialog::KeyType::Private); + if (row.isZ) { + if (ImGui::MenuItem(TR("export_viewing_key"))) + KeyExportDialog::show(addr.address, KeyExportDialog::KeyType::Viewing); + } + if (ImGui::MenuItem(TR("show_qr_code"))) + QRPopupDialog::show(addr.address, row.isZ ? "Z-Address" : "T-Address"); + ImGui::Separator(); + if (row.hidden) { + if (ImGui::MenuItem("Restore Address")) + app->unhideAddress(addr.address); + } else if (addr.balance < 1e-9) { + if (ImGui::MenuItem("Hide Address")) + app->hideAddress(addr.address); + } + if (row.favorite) { + if (ImGui::MenuItem("Remove Favorite")) + app->unfavoriteAddress(addr.address); + } else { + if (ImGui::MenuItem("Favorite Address")) + app->favoriteAddress(addr.address); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + } + ImGui::PopID(); + + if (row_idx < (int)rows.size() - 1 && selected_row != row_idx) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine( + ImVec2(divStart.x + rowPadLeft + rowIconSz * 2.0f, divStart.y), + ImVec2(divStart.x + innerW - Layout::spacingLg(), divStart.y), + IM_COL32(255, 255, 255, 15)); + } + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImGui::EndChild(); + ImGui::PopStyleVar(); + + { + float fadeZone = std::min( + (Type().body2()->LegacySize + Type().caption()->LegacySize + + Layout::spacingLg() + Layout::spacingMd()) * 1.2f, + addrListH * 0.18f); + ApplyScrollEdgeMask(dlPanel, addrParentVtx, addrChildDL, addrChildVtx, + listPanelMin.y, listPanelMax.y, fadeZone, addrScrollY, addrScrollMaxY); + } + + { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + char countBuf[128]; + int totalAddrs = (int)(state.z_addresses.size() + state.t_addresses.size()); + snprintf(countBuf, sizeof(countBuf), "Showing %d of %d addresses", + (int)rows.size(), totalAddrs); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), countBuf); + } +} + +// Render the shared recent transactions section (used by all layouts) +static void RenderSharedRecentTx(App* app, float recentH, float availW, float hs, float vs) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const float dp = Layout::dpiScale(); + const auto actionBtn = S.button("tabs.balance", "action-button"); + const float kRecentTxRowHeight = S.drawElement("tabs.balance", "recent-tx-row-height").sizeOr(22.0f); + const auto& state = app->state(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT TRANSACTIONS"); + ImGui::SameLine(); + if (TactileSmallButton("View All", S.resolveFont(actionBtn.font.empty() ? "button" : actionBtn.font))) { + app->setCurrentPage(NavPage::History); + } + ImGui::Spacing(); + + float scaledRowH = std::max(S.drawElement("tabs.balance", "recent-tx-row-min-height").size, kRecentTxRowHeight * vs); + int maxTx = std::clamp((int)(recentH / scaledRowH), 2, 5); + const auto& txs = state.transactions; + int count = (int)txs.size(); + if (count > maxTx) count = maxTx; + + if (count == 0) { + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), "No transactions yet"); + } else { + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + float rowH = std::max(18.0f * dp, kRecentTxRowHeight * vs); + float iconSz = std::max(S.drawElement("tabs.balance", "recent-tx-icon-min-size").size, + S.drawElement("tabs.balance", "recent-tx-icon-size").size * hs); + + for (int i = 0; i < count; i++) { + const auto& tx = txs[i]; + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + float rowY = rowPos.y + rowH * 0.5f; + ImU32 iconCol; + if (tx.type == "send") iconCol = Error(); + else if (tx.type == "receive") iconCol = Success(); + else iconCol = Warning(); + DrawTxIcon(dl, tx.type, rowPos.x + Layout::spacingMd(), rowY, iconSz, iconCol); + + float tx_x = rowPos.x + Layout::spacingMd() + iconSz * 2.0f + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(tx_x, rowPos.y + 2 * dp), OnSurfaceMedium(), tx.getTypeDisplay().c_str()); + + float addrX = tx_x + S.drawElement("tabs.balance", "recent-tx-addr-offset").sizeOr(65.0f); + std::string trAddr = truncateAddress(tx.address, (int)S.drawElement("tabs.balance", "recent-tx-addr-trunc").sizeOr(20.0f)); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(addrX, rowPos.y + 2 * dp), OnSurfaceDisabled(), trAddr.c_str()); + + char amtBuf[32]; + snprintf(amtBuf, sizeof(amtBuf), "%s%.4f %s", + tx.type == "send" ? "-" : "+", + std::abs(tx.amount), DRAGONX_TICKER); + ImVec2 amtSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, amtBuf); + float rightEdge = rowPos.x + ImGui::GetContentRegionAvail().x; + float amtX = rightEdge - amtSz.x - std::max( + S.drawElement("tabs.balance", "amount-right-min-margin").size, + S.drawElement("tabs.balance", "amount-right-margin").size * hs); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(amtX, rowPos.y + 2 * dp), + tx.type == "send" ? Error() : Success(), amtBuf); + + std::string ago = timeAgo(tx.timestamp); + ImVec2 agoSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, ago.c_str()); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rightEdge - agoSz.x - S.drawElement("tabs.balance", "recent-tx-time-margin").sizeOr(4.0f), rowPos.y + 2 * dp), + OnSurfaceDisabled(), ago.c_str()); + + float rowW = ImGui::GetContentRegionAvail().x; + ImVec2 rowEnd(rowPos.x + rowW, rowPos.y + rowH); + if (material::IsRectHovered(rowPos, rowEnd)) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), S.drawElement("tabs.balance", "row-hover-rounding").sizeOr(4.0f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(NavPage::History); + } + ImGui::Dummy(ImVec2(0, rowH)); + } + } +} + +// Render sync progress bar (used by multiple layouts) +static void RenderSyncBar(App* app, ImDrawList* dl, float vs) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto syncBar = S.drawElement("tabs.balance", "sync-bar"); + const auto& state = app->state(); + const float dp = Layout::dpiScale(); + + if (state.sync.syncing && state.sync.headers > 0) { + float prog = static_cast(state.sync.verification_progress); + if (prog > 1.0f) prog = 1.0f; + float barH = (syncBar.height >= 0) ? syncBar.height : 3.0f; + float barW = ImGui::GetContentRegionAvail().x; + ImVec2 barPos = ImGui::GetCursorScreenPos(); + dl->AddRectFilled(barPos, + ImVec2(barPos.x + barW, barPos.y + barH), + IM_COL32(255, 255, 255, 15), 1.0f * dp); + dl->AddRectFilled(barPos, + ImVec2(barPos.x + barW * prog, barPos.y + barH), + WithAlpha(Warning(), 200), 1.0f * dp); + ImGui::Dummy(ImVec2(barW, barH)); + } +} + +// ============================================================================ +// Layout 1: Donut Chart +// ============================================================================ +static void RenderBalanceDonut(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // --- Hero: total balance --- + float donutTopMargin = S.drawElement("tabs.balance.donut", "top-margin").size; + if (donutTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, donutTopMargin)); + else + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.balance.donut", "hero-pad-ratio").sizeOr(8.0f) * vs)); + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL BALANCE"); + ImGui::Dummy(ImVec2(0, 2 * dp)); + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + ImFont* heroFont = Type().h2(); + ImVec2 pos = ImGui::GetCursorScreenPos(); + DrawTextShadow(dl, heroFont, heroFont->LegacySize, pos, OnSurface(), buf); + ImVec2 heroSize = heroFont->CalcTextSizeA(heroFont->LegacySize, 10000.0f, 0.0f, buf); + ImGui::Dummy(heroSize); + ImGui::SameLine(); + ImFont* capFont = Type().caption(); + float tickerY = pos.y + heroSize.y - capFont->LegacySize; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, tickerY), + OnSurfaceMedium(), DRAGONX_TICKER); + ImGui::NewLine(); + + // USD value + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else snprintf(buf, sizeof(buf), "$-.-- USD"); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + // --- Donut + legend panel --- + { + float donutCardH = S.drawElement("tabs.balance.donut", "card-height").size; + float panelH; + if (donutCardH >= 0.0f) { + panelH = donutCardH; // explicit override from ui.toml + } else { + panelH = std::max( + S.drawElement("tabs.balance.donut", "panel-min-height").sizeOr(80.0f), + contentAvail.y * S.drawElement("tabs.balance.donut", "panel-height-ratio").sizeOr(0.20f)); + } + ImVec2 panelMin = ImGui::GetCursorScreenPos(); + ImVec2 panelMax(panelMin.x + availW, panelMin.y + panelH); + GlassPanelSpec spec; + spec.rounding = glassRound; + DrawGlassPanel(dl, panelMin, panelMax, spec); + + float donutPadOverride = S.drawElement("tabs.balance.donut", "card-padding").size; + float donutPad = (donutPadOverride >= 0.0f) ? donutPadOverride : Layout::spacingLg(); + + // Donut ring + float cx = panelMin.x + panelH * 0.5f + donutPad; + float cy = panelMin.y + panelH * 0.5f; + float radius = std::min( + panelH * S.drawElement("tabs.balance.donut", "outer-radius-ratio").sizeOr(0.40f), + availW * S.drawElement("tabs.balance.donut", "max-radius-ratio").sizeOr(0.12f)); + float innerRadius = radius * S.drawElement("tabs.balance.donut", "inner-radius-ratio").sizeOr(0.6f); + + float total = (float)s_dispTotal; + float shielded = (float)s_dispShielded; + float ratio = (total > 1e-9f) ? shielded / total : 0.5f; + + // Shielded arc (green) + float startAngle = -IM_PI * 0.5f; // top + float shieldEnd = startAngle + 2.0f * IM_PI * ratio; + if (ratio > 0.01f) { + dl->PathClear(); + dl->PathArcTo(ImVec2(cx, cy), radius, startAngle, shieldEnd, 32); + dl->PathArcTo(ImVec2(cx, cy), innerRadius, shieldEnd, startAngle, 32); + dl->PathFillConvex(WithAlpha(Success(), 180)); + } + // Transparent arc (gold) + if (ratio < 0.99f) { + dl->PathClear(); + dl->PathArcTo(ImVec2(cx, cy), radius, shieldEnd, startAngle + 2.0f * IM_PI, 32); + dl->PathArcTo(ImVec2(cx, cy), innerRadius, startAngle + 2.0f * IM_PI, shieldEnd, 32); + dl->PathFillConvex(WithAlpha(Warning(), 180)); + } + + // Center text: privacy % + float privPct = ratio * 100.0f; + snprintf(buf, sizeof(buf), "%.0f%%", privPct); + ImFont* sub1 = Type().subtitle1(); + ImVec2 pctSz = sub1->CalcTextSizeA(sub1->LegacySize, 1000, 0, buf); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(cx - pctSz.x * 0.5f, cy - pctSz.y * 0.5f), + OnSurface(), buf); + + // Legend (right side) + float legendX = panelMin.x + panelH + donutPad * 2; + float legendY = panelMin.y + donutPad; + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + + float legendDotR = S.drawElement("tabs.balance.donut", "legend-dot-radius").sizeOr(4.0f); + float legendXOff = S.drawElement("tabs.balance.donut", "legend-x-offset").sizeOr(14.0f); + float legendLineGap = S.drawElement("tabs.balance.donut", "legend-line-gap").sizeOr(6.0f); + float legendSectionGap = S.drawElement("tabs.balance.donut", "legend-section-gap").sizeOr(10.0f); + + // Shielded legend + dl->AddCircleFilled(ImVec2(legendX + 5 * dp, legendY + capFont->LegacySize * 0.5f), legendDotR, Success()); + snprintf(buf, sizeof(buf), "Shielded %.8f", s_dispShielded); + dl->AddText(capFont, capFont->LegacySize, ImVec2(legendX + legendXOff, legendY), Success(), buf); + legendY += capFont->LegacySize + legendLineGap; + + // Transparent legend + dl->AddCircleFilled(ImVec2(legendX + 5 * dp, legendY + capFont->LegacySize * 0.5f), legendDotR, Warning()); + snprintf(buf, sizeof(buf), "Transparent %.8f", s_dispTransparent); + dl->AddText(capFont, capFont->LegacySize, ImVec2(legendX + legendXOff, legendY), Warning(), buf); + legendY += capFont->LegacySize + legendSectionGap; + + // Market price + const auto& market = state.market; + if (market.price_usd > 0) { + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "Market: $%.4f", market.price_usd); + else + snprintf(buf, sizeof(buf), "Market: $%.8f", market.price_usd); + dl->AddText(capFont, capFont->LegacySize, ImVec2(legendX + legendXOff, legendY), + OnSurfaceMedium(), buf); + legendY += capFont->LegacySize + 4 * dp; + + bool pos = market.change_24h >= 0; + snprintf(buf, sizeof(buf), "%s%.1f%% 24h", pos ? "+" : "", market.change_24h); + dl->AddText(capFont, capFont->LegacySize, ImVec2(legendX + legendXOff, legendY), + pos ? Success() : Error(), buf); + } + + ImGui::Dummy(ImVec2(availW, panelH)); + } + + ImGui::Dummy(ImVec2(0, cGap)); + + // --- Shared address list + recent tx --- + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float donutAddrOverride = S.drawElement("tabs.balance.donut", "address-table-height").size; + float addrH = (donutAddrOverride >= 0.0f) ? donutAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 2: Consolidated Card +// ============================================================================ +static void RenderBalanceConsolidated(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Single consolidated card + float consTopMargin = S.drawElement("tabs.balance.consolidated", "top-margin").size; + if (consTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, consTopMargin)); + + float consCardH = S.drawElement("tabs.balance.consolidated", "card-height").size; + float cardH; + if (consCardH >= 0.0f) { + cardH = consCardH; // explicit override from ui.toml + } else { + cardH = std::max( + S.drawElement("tabs.balance.consolidated", "card-min-height").sizeOr(90.0f), + contentAvail.y * S.drawElement("tabs.balance.consolidated", "card-height-ratio").sizeOr(0.22f)); + } + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + ImVec2 cardMax(cardMin.x + availW, cardMin.y + cardH); + GlassPanelSpec spec; + spec.rounding = glassRound; + DrawGlassPanel(dl, cardMin, cardMax, spec); + + float consPadOverride = S.drawElement("tabs.balance.consolidated", "card-padding").size; + float pad = (consPadOverride >= 0.0f) ? consPadOverride : Layout::spacingLg(); + float cx = cardMin.x + pad; + float cy = cardMin.y + pad; + + // Coin logo + ImTextureID logoTex = app->getCoinLogoTexture(); + ImFont* heroFont = Type().h2(); + ImFont* sub1 = Type().subtitle1(); + ImFont* capFont = Type().caption(); + ImFont* ovFont = Type().overline(); + + float logoSz = heroFont->LegacySize + capFont->LegacySize + 4.0f * dp; + if (logoTex != 0) { + dl->AddImage(logoTex, + ImVec2(cx, cy), ImVec2(cx + logoSz, cy + logoSz), + ImVec2(0, 0), ImVec2(1, 1), IM_COL32(255, 255, 255, 255)); + cx += logoSz + Layout::spacingMd(); + } + + // Total balance + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + DrawTextShadow(dl, heroFont, heroFont->LegacySize, ImVec2(cx, cy), OnSurface(), buf); + ImVec2 heroSz = heroFont->CalcTextSizeA(heroFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + heroSz.x + 4 * dp, cy + heroSz.y - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + cy += heroSz.y + 2 * dp; + + // USD value + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else snprintf(buf, sizeof(buf), "$-.-- USD"); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceDisabled(), buf); + + // Market badge (top-right) + { + const auto& market = state.market; + if (market.price_usd > 0) { + float badgeX = cardMax.x - pad; + float badgeY = cardMin.y + pad; + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", market.price_usd); + else + snprintf(buf, sizeof(buf), "$%.8f", market.price_usd); + ImVec2 pSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(badgeX - pSz.x, badgeY), OnSurfaceMedium(), buf); + badgeY += capFont->LegacySize + 2 * dp; + + bool pos = market.change_24h >= 0; + snprintf(buf, sizeof(buf), "%s%.1f%%", pos ? "+" : "", market.change_24h); + ImVec2 chgSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(badgeX - chgSz.x, badgeY), + pos ? Success() : Error(), buf); + } + } + + // Divider + float divY = cardMin.y + cardH * S.drawElement("tabs.balance.consolidated", "divider-y-ratio").sizeOr(0.55f); + dl->AddLine(ImVec2(cardMin.x + pad, divY), ImVec2(cardMax.x - pad, divY), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance.consolidated", "divider-alpha").sizeOr(20.0f)), + S.drawElement("tabs.balance.consolidated", "divider-thickness").sizeOr(1.0f)); + + // Bottom half: proportion bars + float barY = divY + Layout::spacingSm(); + float barH = std::max( + S.drawElement("tabs.balance.consolidated", "bar-min-height").sizeOr(6.0f), + S.drawElement("tabs.balance.consolidated", "bar-base-height").sizeOr(10.0f) * vs); + float halfW = (availW - pad * 3) * 0.5f; + float total = (float)s_dispTotal; + float shieldRatio = (total > 1e-9f) ? (float)(s_dispShielded / total) : 0.5f; + float transRatio = 1.0f - shieldRatio; + + // Shielded bar + float shieldX = cardMin.x + pad; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(shieldX, barY), Success(), "SHIELDED"); + barY += ovFont->LegacySize + 4 * dp; + dl->AddRectFilled(ImVec2(shieldX, barY), ImVec2(shieldX + halfW, barY + barH), + IM_COL32(255, 255, 255, 15), barH * 0.5f); + dl->AddRectFilled(ImVec2(shieldX, barY), ImVec2(shieldX + halfW * shieldRatio, barY + barH), + WithAlpha(Success(), 180), barH * 0.5f); + barY += barH + 2 * dp; + snprintf(buf, sizeof(buf), "%.8f (%.0f%%)", s_dispShielded, shieldRatio * 100.0f); + dl->AddText(capFont, capFont->LegacySize, ImVec2(shieldX, barY), OnSurfaceMedium(), buf); + + // Transparent bar + float transX = cardMin.x + pad * 2 + halfW; + barY = divY + Layout::spacingSm(); + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(transX, barY), Warning(), "TRANSPARENT"); + barY += ovFont->LegacySize + 4 * dp; + dl->AddRectFilled(ImVec2(transX, barY), ImVec2(transX + halfW, barY + barH), + IM_COL32(255, 255, 255, 15), barH * 0.5f); + dl->AddRectFilled(ImVec2(transX, barY), ImVec2(transX + halfW * transRatio, barY + barH), + WithAlpha(Warning(), 180), barH * 0.5f); + barY += barH + 2 * dp; + snprintf(buf, sizeof(buf), "%.8f (%.0f%%)", s_dispTransparent, transRatio * 100.0f); + dl->AddText(capFont, capFont->LegacySize, ImVec2(transX, barY), OnSurfaceMedium(), buf); + + // Sync bar at card bottom — clipped to rounded corners + if (state.sync.syncing && state.sync.headers > 0) { + const auto syncBar = S.drawElement("tabs.balance", "sync-bar"); + float syncBarH = (syncBar.height >= 0) ? syncBar.height : 3.0f; + float prog = static_cast(state.sync.verification_progress); + if (prog > 1.0f) prog = 1.0f; + float syncBarTop = cardMax.y - syncBarH; + // Clip to the bottom strip so the full-card rounded rect + // curves exactly match the card's own rounded corners + dl->PushClipRect(ImVec2(cardMin.x, syncBarTop), cardMax, true); + // Background track + dl->AddRectFilled(cardMin, cardMax, + IM_COL32(255, 255, 255, 15), glassRound); + // Progress fill — additional horizontal clip + float progRight = cardMin.x + (cardMax.x - cardMin.x) * prog; + dl->PushClipRect(ImVec2(cardMin.x, syncBarTop), ImVec2(progRight, cardMax.y), true); + dl->AddRectFilled(cardMin, cardMax, + WithAlpha(Warning(), 200), glassRound); + dl->PopClipRect(); + dl->PopClipRect(); + } + ImGui::Dummy(ImVec2(availW, cardH)); + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float consAddrOverride = S.drawElement("tabs.balance.consolidated", "address-table-height").size; + float addrH = (consAddrOverride >= 0.0f) ? consAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 3: Dashboard Tiles +// ============================================================================ +static void RenderBalanceDashboard(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + auto tier = Layout::currentTier(availW, contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Compact hero line + float dashTopMargin = S.drawElement("tabs.balance.dashboard", "top-margin").size; + if (dashTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, dashTopMargin)); + float dashHeroH = S.drawElement("tabs.balance.dashboard", "hero-height").size; + RenderCompactHero(app, dl, availW, hs, vs, dashHeroH); + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + // 4-tile grid + int numCols = (tier == Layout::LayoutTier::Compact && availW < S.drawElement("tabs.balance.dashboard", "compact-cutoff").sizeOr(500.0f) * Layout::dpiScale()) + ? (int)S.drawElement("tabs.balance.dashboard", "tile-compact-cols").sizeOr(2.0f) + : (int)S.drawElement("tabs.balance.dashboard", "tile-num-cols").sizeOr(4.0f); + int numRows = (numCols == 2) ? 2 : 1; + float tileW = (availW - (numCols - 1) * cGap) / numCols; + float dashCardH = S.drawElement("tabs.balance.dashboard", "card-height").size; + float tileH; + if (dashCardH >= 0.0f) { + tileH = dashCardH; // explicit override from ui.toml + } else { + tileH = std::max( + S.drawElement("tabs.balance.dashboard", "tile-min-height").sizeOr(70.0f), + contentAvail.y * S.drawElement("tabs.balance.dashboard", "tile-height-ratio").sizeOr(0.16f) / numRows); + } + ImVec2 origin = ImGui::GetCursorScreenPos(); + + GlassPanelSpec tileSpec; + tileSpec.rounding = glassRound; + ImFont* ovFont = Type().overline(); + ImFont* sub1 = Type().subtitle1(); + ImFont* capFont = Type().caption(); + + struct TileInfo { + const char* label; + const char* value; + ImU32 accent; + const char* icon; + NavPage nav; + bool isAction; + }; + + snprintf(buf, sizeof(buf), "%.8f", s_dispShielded); + static char shBuf[64], trBuf[64]; + snprintf(shBuf, sizeof(shBuf), "%.8f", s_dispShielded); + snprintf(trBuf, sizeof(trBuf), "%.8f", s_dispTransparent); + + TileInfo tiles[4] = { + {"SHIELDED", shBuf, S.resolveColor("var(--accent-shielded)", Success()), ICON_MD_SHIELD, NavPage::Receive, false}, + {"TRANSPARENT", trBuf, S.resolveColor("var(--accent-transparent)", Warning()), ICON_MD_CIRCLE, NavPage::Receive, false}, + {"QUICK SEND", "Send", S.resolveColor("var(--accent-action)", Primary()), ICON_MD_CALL_MADE, NavPage::Send, true}, + {"QUICK RECEIVE", "Receive", S.resolveColor("var(--accent-action)", Primary()), ICON_MD_CALL_RECEIVED, NavPage::Receive, true}, + }; + + for (int i = 0; i < 4; i++) { + int col = (numCols == 4) ? i : (i % 2); + int row = (numCols == 4) ? 0 : (i / 2); + float xOff = col * (tileW + cGap); + float yOff = row * (tileH + cGap); + + ImVec2 tMin(origin.x + xOff, origin.y + yOff); + ImVec2 tMax(tMin.x + tileW, tMin.y + tileH); + DrawGlassPanel(dl, tMin, tMax, tileSpec); + + // Accent stripe — clipped to tile rounded corners + { + float aw = S.drawElement("tabs.balance", "accent-width").sizeOr(4.0f); + dl->PushClipRect(tMin, ImVec2(tMin.x + aw, tMax.y), true); + dl->AddRectFilled(tMin, tMax, tiles[i].accent, tileSpec.rounding, + ImDrawFlags_RoundCornersLeft); + dl->PopClipRect(); + } + + float dashPadOverride = S.drawElement("tabs.balance.dashboard", "card-padding").size; + float tilePad = (dashPadOverride >= 0.0f) ? dashPadOverride : Layout::spacingLg(); + float tilePadV = (dashPadOverride >= 0.0f) ? dashPadOverride : Layout::spacingSm(); + + float px = tMin.x + tilePad; + float py = tMin.y + tilePadV; + + // Icon + ImFont* iconFont = Type().iconSmall(); + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, tiles[i].icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(px, py), tiles[i].accent, tiles[i].icon); + px += iSz.x + Layout::spacingSm(); + + // Label + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(px, py), OnSurfaceMedium(), tiles[i].label); + py += ovFont->LegacySize + 4 * dp; + + // Value + if (!tiles[i].isAction) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(tMin.x + tilePad, py), + tiles[i].accent, tiles[i].value); + } else { + dl->AddText(capFont, capFont->LegacySize, ImVec2(tMin.x + tilePad, py), + OnSurfaceMedium(), "Click to open"); + } + + // Click + if (material::IsRectHovered(tMin, tMax)) { + dl->AddRect(tMin, tMax, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance", "hover-glow-alpha").sizeOr(40.0f)), + tileSpec.rounding, 0, S.drawElement("tabs.balance", "hover-glow-thickness").sizeOr(1.5f)); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) + app->setCurrentPage(tiles[i].nav); + } + } + + float totalTileH = numRows * tileH + (numRows - 1) * cGap; + ImGui::Dummy(ImVec2(availW, totalTileH)); + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float dashAddrOverride = S.drawElement("tabs.balance.dashboard", "address-table-height").size; + float addrH = (dashAddrOverride >= 0.0f) ? dashAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 4: Vertical Stack +// ============================================================================ +static void RenderBalanceVerticalStack(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + float vstackTopMargin = S.drawElement("tabs.balance.vertical-stack", "top-margin").size; + if (vstackTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, vstackTopMargin)); + + float vstackCardH = S.drawElement("tabs.balance.vertical-stack", "card-height").size; + float stackH; + if (vstackCardH >= 0.0f) { + stackH = vstackCardH; // explicit override from ui.toml + } else { + stackH = std::max( + S.drawElement("tabs.balance.vertical-stack", "stack-min-height").sizeOr(80.0f), + contentAvail.y * S.drawElement("tabs.balance.vertical-stack", "stack-height-ratio").sizeOr(0.16f)); + } + float rowGap = S.drawElement("tabs.balance.vertical-stack", "row-gap").sizeOr(2.0f); + float rowH = (stackH - 3 * rowGap) / 4.0f; + float rowMinH = S.drawElement("tabs.balance.vertical-stack", "row-min-height").sizeOr(20.0f); + if (rowH < rowMinH) rowH = rowMinH; + + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + ImFont* sub1 = Type().subtitle1(); + + float total = (float)s_dispTotal; + float shieldRatio = (total > 1e-9f) ? (float)(s_dispShielded / total) : 0.5f; + float transRatio = 1.0f - shieldRatio; + + struct RowInfo { + const char* label; + const char* icon; + ImU32 accent; + double amount; + float ratio; + }; + + RowInfo rowInfos[4] = { + {"Total Balance", ICON_MD_ACCOUNT_BALANCE_WALLET, S.resolveColor("var(--accent-total)", OnSurface()), s_dispTotal, 1.0f}, + {"Shielded", ICON_MD_SHIELD, S.resolveColor("var(--accent-shielded)", Success()), s_dispShielded, shieldRatio}, + {"Transparent", ICON_MD_CIRCLE, S.resolveColor("var(--accent-transparent)", Warning()), s_dispTransparent, transRatio}, + {"Market", ICON_MD_TRENDING_UP, S.resolveColor("var(--accent-action)", Primary()), state.market.price_usd, 0.0f}, + }; + + for (int i = 0; i < 4; i++) { + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowEnd(rowPos.x + availW, rowPos.y + rowH); + + float vstackPadOverride = S.drawElement("tabs.balance.vertical-stack", "card-padding").size; + float rowPad = (vstackPadOverride >= 0.0f) ? vstackPadOverride : Layout::spacingLg(); + + // Subtle background + float rowBgAlpha = S.drawElement("tabs.balance.vertical-stack", "row-bg-alpha").sizeOr(8.0f); + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, (int)rowBgAlpha), 4.0f * dp); + + // Left accent — clipped to row rounding + dl->PushClipRect(rowPos, rowEnd, true); + dl->AddRectFilled(ImVec2(rowPos.x, rowPos.y), + ImVec2(rowPos.x + 3 * dp, rowEnd.y), + rowInfos[i].accent); + dl->PopClipRect(); + + float px = rowPos.x + rowPad; + float cy = rowPos.y + (rowH - capFont->LegacySize) * 0.5f; + + // Icon + ImFont* iconFont = Type().iconSmall(); + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, rowInfos[i].icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(px, rowPos.y + (rowH - iSz.y) * 0.5f), + rowInfos[i].accent, rowInfos[i].icon); + px += iSz.x + Layout::spacingSm(); + + // Label + dl->AddText(capFont, capFont->LegacySize, ImVec2(px, cy), + OnSurfaceMedium(), rowInfos[i].label); + + // Amount (right side) + if (i < 3) { + snprintf(buf, sizeof(buf), "%.8f %s", rowInfos[i].amount, DRAGONX_TICKER); + } else { + if (state.market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", state.market.price_usd); + else if (state.market.price_usd > 0) + snprintf(buf, sizeof(buf), "$%.8f", state.market.price_usd); + else + snprintf(buf, sizeof(buf), "$--.--"); + } + ImVec2 amtSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowEnd.x - amtSz.x - rowPad, cy), + i == 0 ? OnSurface() : rowInfos[i].accent, buf); + + // Proportion bar (for shielded/transparent rows — fills gap between label and amount) + if (i == 1 || i == 2) { + ImVec2 labelSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, rowInfos[i].label); + float barGap = S.drawElement("tabs.balance.vertical-stack", "sparkline-gap").sizeOr(12.0f); + float barPad = S.drawElement("tabs.balance.vertical-stack", "sparkline-pad").sizeOr(4.0f); + float barH = std::max( + S.drawElement("tabs.balance.vertical-stack", "bar-min-height").sizeOr(3.0f), + rowH * S.drawElement("tabs.balance.vertical-stack", "bar-height-ratio").sizeOr(0.15f)); + float barLeft = px + labelSz.x + barGap; + float barRight = rowEnd.x - amtSz.x - rowPad - barGap; + if (barLeft < barRight) { + float barW = barRight - barLeft; + float barY = rowPos.y + (rowH - barH) * 0.5f; + dl->AddRectFilled(ImVec2(barLeft, barY), ImVec2(barRight, barY + barH), + IM_COL32(255, 255, 255, 15), barH * 0.5f); + dl->AddRectFilled(ImVec2(barLeft, barY), + ImVec2(barLeft + barW * rowInfos[i].ratio, barY + barH), + WithAlpha(rowInfos[i].accent, 180), barH * 0.5f); + } + } + + // Market: 24h change + sparkline + if (i == 3 && state.market.price_usd > 0) { + bool pos = state.market.change_24h >= 0; + snprintf(buf, sizeof(buf), "%s%.1f%%", pos ? "+" : "", state.market.change_24h); + ImVec2 chgSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float chgX = rowEnd.x - amtSz.x - Layout::spacingLg() - chgSz.x - Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(chgX, cy), + pos ? Success() : Error(), buf); + + // Sparkline in the gap between label and 24h change + if (state.market.price_history.size() >= 2) { + ImVec2 labelSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, rowInfos[i].label); + float sparkGap = S.drawElement("tabs.balance.vertical-stack", "sparkline-gap").sizeOr(12.0f); + float sparkPad = S.drawElement("tabs.balance.vertical-stack", "sparkline-pad").sizeOr(4.0f); + float sparkLeft = px + labelSz.x + sparkGap; + float sparkRight = chgX - sparkGap; + if (sparkLeft < sparkRight) { + ImVec2 spMin(sparkLeft, rowPos.y + sparkPad); + ImVec2 spMax(sparkRight, rowEnd.y - sparkPad); + ImU32 lineCol = pos + ? WithAlpha(Success(), 200) + : WithAlpha(Error(), 200); + DrawSparkline(dl, spMin, spMax, + state.market.price_history, lineCol); + } + } + } + + ImGui::Dummy(ImVec2(availW, rowH)); + if (i < 3) ImGui::Dummy(ImVec2(0, rowGap)); + } + + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float vstackAddrOverride = S.drawElement("tabs.balance.vertical-stack", "address-table-height").size; + float addrH = (vstackAddrOverride >= 0.0f) ? vstackAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 5b: Vertical 2×2 (Total+Market left, Shielded+Transparent right) +// ============================================================================ +static void RenderBalanceVertical2x2(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + const char* cfgSec = "tabs.balance.vertical-2x2"; + + float topMargin = S.drawElement(cfgSec, "top-margin").size; + if (topMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, topMargin)); + + float cardHOverride = S.drawElement(cfgSec, "card-height").size; + float stackH; + if (cardHOverride >= 0.0f) { + stackH = cardHOverride; + } else { + stackH = std::max( + S.drawElement(cfgSec, "stack-min-height").sizeOr(60.0f), + contentAvail.y * S.drawElement(cfgSec, "stack-height-ratio").sizeOr(0.12f)); + } + float rowGap = S.drawElement(cfgSec, "row-gap").sizeOr(2.0f); + float colGap = S.drawElement(cfgSec, "col-gap").sizeOr(8.0f); + float rowH = (stackH - rowGap) / 2.0f; + float rowMinH = S.drawElement(cfgSec, "row-min-height").sizeOr(24.0f); + if (rowH < rowMinH) rowH = rowMinH; + + float colW = (availW - colGap) / 2.0f; + + ImFont* capFont = Type().caption(); + ImFont* iconFont = Type().iconSmall(); + + float padOverride = S.drawElement(cfgSec, "card-padding").size; + float rowPad = (padOverride >= 0.0f) ? padOverride : Layout::spacingLg(); + float rowBgAlpha = S.drawElement(cfgSec, "row-bg-alpha").sizeOr(8.0f); + + float total = (float)s_dispTotal; + float shieldRatio = (total > 1e-9f) ? (float)(s_dispShielded / total) : 0.5f; + float transRatio = 1.0f - shieldRatio; + + // Grid: [row][col] — row 0 top, row 1 bottom; col 0 left, col 1 right + // Left col: Total Balance (row 0), Market (row 1) + // Right col: Shielded (row 0), Transparent (row 1) + struct CellInfo { + const char* label; + const char* icon; + ImU32 accent; + double amount; + float ratio; + bool isMarket; + bool hasBar; + }; + + CellInfo cells[2][2] = { + // Row 0: Total Balance (left), Shielded (right) + { + {"Total Balance", ICON_MD_ACCOUNT_BALANCE_WALLET, S.resolveColor("var(--accent-total)", OnSurface()), s_dispTotal, 1.0f, false, false}, + {"Shielded", ICON_MD_SHIELD, S.resolveColor("var(--accent-shielded)", Success()), s_dispShielded, shieldRatio, false, true}, + }, + // Row 1: Market (left), Transparent (right) + { + {"Market", ICON_MD_TRENDING_UP, S.resolveColor("var(--accent-action)", Primary()), state.market.price_usd, 0.0f, true, false}, + {"Transparent", ICON_MD_CIRCLE, S.resolveColor("var(--accent-transparent)", Warning()), s_dispTransparent, transRatio, false, true}, + }, + }; + + ImVec2 gridOrigin = ImGui::GetCursorScreenPos(); + + for (int row = 0; row < 2; row++) { + for (int col = 0; col < 2; col++) { + const auto& cell = cells[row][col]; + + float cellX = gridOrigin.x + col * (colW + colGap); + float cellY = gridOrigin.y + row * (rowH + rowGap); + ImVec2 cellMin(cellX, cellY); + ImVec2 cellMax(cellX + colW, cellY + rowH); + + // Background + dl->AddRectFilled(cellMin, cellMax, IM_COL32(255, 255, 255, (int)rowBgAlpha), 4.0f * dp); + + // Left accent — clipped to cell rounding + dl->PushClipRect(cellMin, cellMax, true); + dl->AddRectFilled(ImVec2(cellMin.x, cellMin.y), + ImVec2(cellMin.x + 3 * dp, cellMax.y), + cell.accent); + dl->PopClipRect(); + + float px = cellMin.x + rowPad; + float cy = cellMin.y + (rowH - capFont->LegacySize) * 0.5f; + + // Icon + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, cell.icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(px, cellMin.y + (rowH - iSz.y) * 0.5f), + cell.accent, cell.icon); + px += iSz.x + Layout::spacingSm(); + + // Label + dl->AddText(capFont, capFont->LegacySize, ImVec2(px, cy), + OnSurfaceMedium(), cell.label); + + // Amount (right-aligned) + if (!cell.isMarket) { + snprintf(buf, sizeof(buf), "%.8f %s", cell.amount, DRAGONX_TICKER); + } else { + if (state.market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", state.market.price_usd); + else if (state.market.price_usd > 0) + snprintf(buf, sizeof(buf), "$%.8f", state.market.price_usd); + else + snprintf(buf, sizeof(buf), "$--.--"); + } + ImVec2 amtSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cellMax.x - amtSz.x - rowPad, cy), + cell.isMarket ? cell.accent : (row == 0 && col == 0 ? OnSurface() : cell.accent), buf); + + // Proportion bar (shielded/transparent) + if (cell.hasBar) { + float barW = colW * S.drawElement(cfgSec, "bar-width-ratio").sizeOr(0.12f); + float barH = std::max( + S.drawElement(cfgSec, "bar-min-height").sizeOr(3.0f), + rowH * S.drawElement(cfgSec, "bar-height-ratio").sizeOr(0.15f)); + float barX = cellMax.x - amtSz.x - rowPad - barW - Layout::spacingSm(); + float barY = cellMin.y + (rowH - barH) * 0.5f; + dl->AddRectFilled(ImVec2(barX, barY), ImVec2(barX + barW, barY + barH), + IM_COL32(255, 255, 255, 15), barH * 0.5f); + dl->AddRectFilled(ImVec2(barX, barY), + ImVec2(barX + barW * cell.ratio, barY + barH), + WithAlpha(cell.accent, 180), barH * 0.5f); + } + + // Market: 24h change + sparkline + if (cell.isMarket && state.market.price_usd > 0) { + bool pos = state.market.change_24h >= 0; + snprintf(buf, sizeof(buf), "%s%.1f%%", pos ? "+" : "", state.market.change_24h); + ImVec2 chgSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float chgX = cellMax.x - amtSz.x - Layout::spacingLg() - chgSz.x - Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(chgX, cy), + pos ? Success() : Error(), buf); + + // Sparkline between label and 24h change + if (state.market.price_history.size() >= 2) { + ImVec2 labelSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, cell.label); + float sparkGap = S.drawElement(cfgSec, "sparkline-gap").sizeOr(12.0f); + float sparkPad = S.drawElement(cfgSec, "sparkline-pad").sizeOr(4.0f); + float sparkLeft = px + labelSz.x + sparkGap; + float sparkRight = chgX - sparkGap; + if (sparkLeft < sparkRight) { + ImVec2 spMin(sparkLeft, cellMin.y + sparkPad); + ImVec2 spMax(sparkRight, cellMax.y - sparkPad); + ImU32 lineCol = pos + ? WithAlpha(Success(), 200) + : WithAlpha(Error(), 200); + DrawSparkline(dl, spMin, spMax, + state.market.price_history, lineCol); + } + } + } + } + } + + // Advance cursor past the 2×2 grid + float totalGridH = 2.0f * rowH + rowGap; + ImGui::Dummy(ImVec2(availW, totalGridH)); + + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float addrOverride = S.drawElement(cfgSec, "address-table-height").size; + float addrH = (addrOverride >= 0.0f) ? addrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 5: Privacy Shield Meter +// ============================================================================ +static void RenderBalanceShield(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Hero section + float shieldTopMargin = S.drawElement("tabs.balance.shield", "top-margin").size; + if (shieldTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, shieldTopMargin)); + else + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.balance", "compact-hero-pad").sizeOr(8.0f) * vs)); + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL BALANCE"); + ImGui::Dummy(ImVec2(0, 2 * dp)); + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + ImFont* heroFont = Type().h2(); + ImVec2 pos = ImGui::GetCursorScreenPos(); + DrawTextShadow(dl, heroFont, heroFont->LegacySize, pos, OnSurface(), buf); + ImVec2 heroSz = heroFont->CalcTextSizeA(heroFont->LegacySize, 10000.0f, 0.0f, buf); + ImGui::Dummy(heroSz); + ImGui::SameLine(); + ImFont* capFont = Type().caption(); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, pos.y + heroSz.y - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + ImGui::NewLine(); + + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else snprintf(buf, sizeof(buf), "$-.-- USD"); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + // Shield gauge panel + { + float shieldCardH = S.drawElement("tabs.balance.shield", "card-height").size; + float gaugeH; + if (shieldCardH >= 0.0f) { + gaugeH = shieldCardH; // explicit override from ui.toml + } else { + gaugeH = std::max( + S.drawElement("tabs.balance.shield", "gauge-min-height").sizeOr(80.0f), + contentAvail.y * S.drawElement("tabs.balance.shield", "gauge-height-ratio").sizeOr(0.18f)); + } + ImVec2 panelMin = ImGui::GetCursorScreenPos(); + ImVec2 panelMax(panelMin.x + availW, panelMin.y + gaugeH); + GlassPanelSpec spec; + spec.rounding = glassRound; + DrawGlassPanel(dl, panelMin, panelMax, spec); + + float total = (float)s_dispTotal; + float privacyRatio = (total > 1e-9f) ? (float)(s_dispShielded / total) : 0.0f; + float privPct = privacyRatio * 100.0f; + + // Semicircle gauge + float gaugeCx = panelMin.x + gaugeH; + float gaugeCy = panelMin.y + gaugeH * S.drawElement("tabs.balance.shield", "gauge-center-y-ratio").sizeOr(0.7f); + float gaugeR = std::min( + gaugeH * S.drawElement("tabs.balance.shield", "gauge-radius-ratio").sizeOr(0.55f), + availW * S.drawElement("tabs.balance.shield", "gauge-max-radius-ratio").sizeOr(0.15f)); + float gaugeInnerR = gaugeR * S.drawElement("tabs.balance.shield", "gauge-inner-ratio").sizeOr(0.7f); + + // Background arc (gray) + dl->PathClear(); + dl->PathArcTo(ImVec2(gaugeCx, gaugeCy), gaugeR, IM_PI, 2.0f * IM_PI, 32); + dl->PathArcTo(ImVec2(gaugeCx, gaugeCy), gaugeInnerR, 2.0f * IM_PI, IM_PI, 32); + dl->PathFillConvex(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.balance.shield", "gauge-bg-alpha").sizeOr(20.0f))); + + // Filled arc (colored by threshold) + ImU32 gaugeCol; + float goodThreshold = S.drawElement("tabs.balance.shield", "good-threshold").sizeOr(80.0f); + float medThreshold = S.drawElement("tabs.balance.shield", "medium-threshold").sizeOr(50.0f); + if (privPct >= goodThreshold) gaugeCol = WithAlpha(Success(), 200); + else if (privPct >= medThreshold) gaugeCol = WithAlpha(Warning(), 200); + else gaugeCol = WithAlpha(Error(), 200); + + float fillEnd = IM_PI + IM_PI * privacyRatio; + if (privacyRatio > 0.01f) { + dl->PathClear(); + dl->PathArcTo(ImVec2(gaugeCx, gaugeCy), gaugeR, IM_PI, fillEnd, 32); + dl->PathArcTo(ImVec2(gaugeCx, gaugeCy), gaugeInnerR, fillEnd, IM_PI, 32); + dl->PathFillConvex(gaugeCol); + } + + // Needle line + float needleAngle = IM_PI + IM_PI * privacyRatio; + float needleLen = gaugeR * 0.85f; + ImVec2 needleTip(gaugeCx + cosf(needleAngle) * needleLen, + gaugeCy + sinf(needleAngle) * needleLen); + dl->AddLine(ImVec2(gaugeCx, gaugeCy), needleTip, gaugeCol, + S.drawElement("tabs.balance.shield", "needle-thickness").sizeOr(2.0f)); + + // Center text: percentage + ImFont* sub1 = Type().subtitle1(); + snprintf(buf, sizeof(buf), "%.0f%%", privPct); + ImVec2 pctSz = sub1->CalcTextSizeA(sub1->LegacySize, 1000, 0, buf); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(gaugeCx - pctSz.x * 0.5f, gaugeCy - pctSz.y - 2 * dp), + gaugeCol, buf); + + // Label below gauge + ImFont* capFont = Type().caption(); + const char* statusMsg; + if (privPct >= 80.0f) statusMsg = "Great privacy!"; + else if (privPct >= 50.0f) statusMsg = "Consider shielding more"; + else statusMsg = "Low privacy — shield funds"; + ImVec2 msgSz = capFont->CalcTextSizeA(capFont->LegacySize, 1000, 0, statusMsg); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(gaugeCx - msgSz.x * 0.5f, gaugeCy + 4 * dp), + OnSurfaceMedium(), statusMsg); + + // Right side: balances + market + float shieldPadOverride = S.drawElement("tabs.balance.shield", "card-padding").size; + float shieldPad = (shieldPadOverride >= 0.0f) ? shieldPadOverride : Layout::spacingLg(); + float infoX = panelMin.x + gaugeH * 2 + shieldPad; + float infoY = panelMin.y + shieldPad; + ImFont* ovFont = Type().overline(); + + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(infoX, infoY), Success(), "SHIELDED"); + infoY += ovFont->LegacySize + 2 * dp; + snprintf(buf, sizeof(buf), "%.8f", s_dispShielded); + dl->AddText(capFont, capFont->LegacySize, ImVec2(infoX, infoY), Success(), buf); + infoY += capFont->LegacySize + 6 * dp; + + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(infoX, infoY), Warning(), "TRANSPARENT"); + infoY += ovFont->LegacySize + 2 * dp; + snprintf(buf, sizeof(buf), "%.8f", s_dispTransparent); + dl->AddText(capFont, capFont->LegacySize, ImVec2(infoX, infoY), Warning(), buf); + infoY += capFont->LegacySize + 6 * dp; + + const auto& market = state.market; + if (market.price_usd > 0) { + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", market.price_usd); + else + snprintf(buf, sizeof(buf), "$%.8f", market.price_usd); + dl->AddText(capFont, capFont->LegacySize, ImVec2(infoX, infoY), + OnSurfaceMedium(), buf); + } + + ImGui::Dummy(ImVec2(availW, gaugeH)); + } + + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float shieldAddrOverride = S.drawElement("tabs.balance.shield", "address-table-height").size; + float addrH = (shieldAddrOverride >= 0.0f) ? shieldAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 6: Balance Timeline (placeholder — requires history tracking) +// ============================================================================ +static void RenderBalanceTimeline(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Hero + float tlTopMargin = S.drawElement("tabs.balance.timeline", "top-margin").size; + if (tlTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, tlTopMargin)); + else + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.balance", "compact-hero-pad").sizeOr(8.0f) * vs)); + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TOTAL BALANCE"); + ImGui::Dummy(ImVec2(0, 2 * dp)); + snprintf(buf, sizeof(buf), "%.8f", s_dispTotal); + ImFont* heroFont = Type().h2(); + ImVec2 pos = ImGui::GetCursorScreenPos(); + DrawTextShadow(dl, heroFont, heroFont->LegacySize, pos, OnSurface(), buf); + ImVec2 heroSz = heroFont->CalcTextSizeA(heroFont->LegacySize, 10000.0f, 0.0f, buf); + ImGui::Dummy(heroSz); + ImGui::SameLine(); + ImFont* capFont = Type().caption(); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(ImGui::GetCursorScreenPos().x, pos.y + heroSz.y - capFont->LegacySize), + OnSurfaceMedium(), DRAGONX_TICKER); + ImGui::NewLine(); + + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else snprintf(buf, sizeof(buf), "$-.-- USD"); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, cGap)); + + // Chart area placeholder + { + float tlChartH = S.drawElement("tabs.balance.timeline", "chart-height").size; + float chartH; + if (tlChartH >= 0.0f) { + chartH = tlChartH; // explicit override from ui.toml + } else { + chartH = std::max( + S.drawElement("tabs.balance.timeline", "chart-min-height").sizeOr(80.0f), + contentAvail.y * S.drawElement("tabs.balance.timeline", "chart-height-ratio").sizeOr(0.20f)); + } + ImVec2 chartMin = ImGui::GetCursorScreenPos(); + ImVec2 chartMax(chartMin.x + availW, chartMin.y + chartH); + GlassPanelSpec spec; + spec.rounding = glassRound; + DrawGlassPanel(dl, chartMin, chartMax, spec); + + ImFont* capFont = Type().caption(); + const char* msg = "Balance history — collecting data..."; + ImVec2 msgSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, msg); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(chartMin.x + (availW - msgSz.x) * 0.5f, + chartMin.y + (chartH - msgSz.y) * 0.5f), + OnSurfaceDisabled(), msg); + + // If we have market sparkline data, use it as a preview + const auto& market = state.market; + if (market.price_history.size() >= 2) { + float sparkPad = Layout::spacingLg(); + ImVec2 spMin(chartMin.x + sparkPad, chartMin.y + capFont->LegacySize + sparkPad * 2); + ImVec2 spMax(chartMax.x - sparkPad, chartMax.y - sparkPad); + if (spMax.y > spMin.y && spMax.x > spMin.x) { + ImU32 lineCol = market.change_24h >= 0 + ? WithAlpha(Success(), (int)S.drawElement("tabs.balance.timeline", "sparkline-alpha").sizeOr(120.0f)) + : WithAlpha(Error(), (int)S.drawElement("tabs.balance.timeline", "sparkline-alpha").sizeOr(120.0f)); + DrawSparkline(dl, spMin, spMax, market.price_history, lineCol); + } + } + + ImGui::Dummy(ImVec2(availW, chartH)); + } + + // Compact 3 summary cards + ImGui::Dummy(ImVec2(0, cGap)); + { + float tlSummaryH = S.drawElement("tabs.balance.timeline", "summary-card-height").size; + float cardH; + if (tlSummaryH >= 0.0f) { + cardH = tlSummaryH; // explicit override from ui.toml + } else { + cardH = std::max( + S.drawElement("tabs.balance.timeline", "summary-min-height").sizeOr(44.0f), + contentAvail.y * S.drawElement("tabs.balance.timeline", "summary-height-ratio").sizeOr(0.08f)); + } + float cardW = (availW - 2 * cGap) / 3.0f; + ImVec2 origin = ImGui::GetCursorScreenPos(); + GlassPanelSpec spec; + spec.rounding = glassRound; + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + + struct SumCard { const char* label; ImU32 col; double val; bool isMoney; }; + SumCard cards[3] = { + {"SHIELDED", Success(), s_dispShielded, false}, + {"TRANSPARENT", Warning(), s_dispTransparent, false}, + {"MARKET", Primary(), state.market.price_usd, true}, + }; + for (int i = 0; i < 3; i++) { + ImVec2 cMin(origin.x + i * (cardW + cGap), origin.y); + ImVec2 cMax(cMin.x + cardW, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, spec); + + float tlPadOverride = S.drawElement("tabs.balance.timeline", "card-padding").size; + float cx = cMin.x + ((tlPadOverride >= 0.0f) ? tlPadOverride : Layout::spacingSm()); + float cy = cMin.y + ((tlPadOverride >= 0.0f) ? tlPadOverride : Layout::spacingXs()); + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), cards[i].label); + cy += ovFont->LegacySize + 2 * dp; + if (cards[i].isMoney) { + if (cards[i].val >= 0.01) snprintf(buf, sizeof(buf), "$%.4f", cards[i].val); + else if (cards[i].val > 0) snprintf(buf, sizeof(buf), "$%.8f", cards[i].val); + else snprintf(buf, sizeof(buf), "$--.--"); + } else { + snprintf(buf, sizeof(buf), "%.8f", cards[i].val); + } + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), cards[i].col, buf); + } + ImGui::Dummy(ImVec2(availW, cardH)); + } + + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float tlAddrOverride = S.drawElement("tabs.balance.timeline", "address-table-height").size; + float addrH = (tlAddrOverride >= 0.0f) ? tlAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 7: Two-Row Hero +// ============================================================================ +static void RenderBalanceTwoRow(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + float cGap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Top margin + float twoRowTopMargin = S.drawElement("tabs.balance.two-row", "top-margin").size; + if (twoRowTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, twoRowTopMargin)); + + // Row 1: logo + balance + USD + actions + RenderCompactHero(app, dl, availW, hs, vs); + + // Sync + mining on same line + { + const auto& state = app->state(); + ImFont* capFont = Type().caption(); + if (state.sync.syncing && state.sync.headers > 0) { + float pct = static_cast(state.sync.verification_progress) * 100.0f; + snprintf(buf, sizeof(buf), "Syncing %.1f%%", pct); + Type().textColored(TypeStyle::Caption, Warning(), buf); + ImGui::SameLine(); + } + if (state.mining.generate) { + double hr = state.mining.localHashrate; + if (hr >= 1000.0) + snprintf(buf, sizeof(buf), "Mining %.1f KH/s", hr / 1000.0); + else + snprintf(buf, sizeof(buf), "Mining %.0f H/s", hr); + Type().textColored(TypeStyle::Caption, WithAlpha(Success(), 200), buf); + ImGui::SameLine(); + } + + // Action buttons right-aligned + float btnW = S.drawElement("tabs.balance.two-row", "action-btn-width").sizeOr(80.0f); + float rightEdge = ImGui::GetWindowWidth() - Layout::spacingLg(); + ImGui::SameLine(rightEdge - btnW * 2 - Layout::spacingSm()); + if (TactileButton("Send", ImVec2(btnW, 0), S.resolveFont("button"))) { + app->setCurrentPage(NavPage::Send); + } + ImGui::SameLine(); + if (TactileButton("Receive", ImVec2(btnW, 0), S.resolveFont("button"))) { + app->setCurrentPage(NavPage::Receive); + } + } + + RenderSyncBar(app, dl, vs); + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.balance.two-row", "sync-gap").sizeOr(2.0f))); + + // Row 2: 3 mini-cards inline + { + float twoRowCardH = S.drawElement("tabs.balance.two-row", "card-height").size; + float miniH; + if (twoRowCardH >= 0.0f) { + miniH = twoRowCardH; // explicit override from ui.toml + } else { + miniH = std::max( + S.drawElement("tabs.balance.two-row", "mini-min-height").sizeOr(28.0f), + S.drawElement("tabs.balance.two-row", "mini-base-height").sizeOr(36.0f) * vs); + } + float miniW = (availW - 2 * cGap) / 3.0f; + ImVec2 origin = ImGui::GetCursorScreenPos(); + GlassPanelSpec spec; + spec.rounding = std::max( + S.drawElement("tabs.balance.two-row", "mini-rounding-min").sizeOr(4.0f), + glassRound * S.drawElement("tabs.balance.two-row", "mini-rounding-ratio").sizeOr(0.5f)); + ImFont* capFont = Type().caption(); + float indicatorR = S.drawElement("tabs.balance.two-row", "indicator-radius").sizeOr(3.0f); + int balDecimals = (int)S.drawElement("tabs.balance.two-row", "balance-decimals").sizeOr(4.0f); + float twoRowPadOverride = S.drawElement("tabs.balance.two-row", "card-padding").size; + float miniPad = (twoRowPadOverride >= 0.0f) ? twoRowPadOverride : Layout::spacingSm(); + + // Shielded mini-card + { + ImVec2 cMin = origin; + ImVec2 cMax(cMin.x + miniW, cMin.y + miniH); + DrawGlassPanel(dl, cMin, cMax, spec); + float cx = cMin.x + miniPad; + float cy = cMin.y + (miniH - capFont->LegacySize) * 0.5f; + dl->AddCircleFilled(ImVec2(cx + 4 * dp, cy + capFont->LegacySize * 0.5f), indicatorR, Success()); + snprintf(buf, sizeof(buf), "%.*f", balDecimals, s_dispShielded); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + 12 * dp, cy), Success(), buf); + + // Percentage of total (right-aligned) + float shieldPct = (s_dispTotal > 1e-9) ? (float)(s_dispShielded / s_dispTotal * 100.0) : 0.0f; + snprintf(buf, sizeof(buf), "%.0f%%", shieldPct); + ImVec2 pctSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cMax.x - pctSz.x - miniPad, cy), + WithAlpha(Success(), 160), buf); + } + + // Transparent mini-card + { + ImVec2 cMin(origin.x + miniW + cGap, origin.y); + ImVec2 cMax(cMin.x + miniW, cMin.y + miniH); + DrawGlassPanel(dl, cMin, cMax, spec); + float cx = cMin.x + miniPad; + float cy = cMin.y + (miniH - capFont->LegacySize) * 0.5f; + dl->AddCircleFilled(ImVec2(cx + 4 * dp, cy + capFont->LegacySize * 0.5f), indicatorR, Warning()); + snprintf(buf, sizeof(buf), "%.*f", balDecimals, s_dispTransparent); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + 12 * dp, cy), Warning(), buf); + + // Percentage of total (right-aligned) + float transPct = (s_dispTotal > 1e-9) ? (float)(s_dispTransparent / s_dispTotal * 100.0) : 0.0f; + snprintf(buf, sizeof(buf), "%.0f%%", transPct); + ImVec2 pctSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cMax.x - pctSz.x - miniPad, cy), + WithAlpha(Warning(), 160), buf); + } + + // Market mini-card + { + ImVec2 cMin(origin.x + 2 * (miniW + cGap), origin.y); + ImVec2 cMax(cMin.x + miniW, cMin.y + miniH); + DrawGlassPanel(dl, cMin, cMax, spec); + float cx = cMin.x + miniPad; + float cy = cMin.y + (miniH - capFont->LegacySize) * 0.5f; + const auto& market = state.market; + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", market.price_usd); + else if (market.price_usd > 0) + snprintf(buf, sizeof(buf), "$%.8f", market.price_usd); + else + snprintf(buf, sizeof(buf), "$--.--"); + ImVec2 priceSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), buf); + + float sparkRight = cMax.x - miniPad; + if (market.price_usd > 0) { + bool pos = market.change_24h >= 0; + snprintf(buf, sizeof(buf), "%s%.1f%%", pos ? "+" : "", market.change_24h); + ImVec2 chgSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float chgX = cMax.x - chgSz.x - miniPad; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(chgX, cy), + pos ? Success() : Error(), buf); + sparkRight = chgX; + + // Sparkline between price and percentage + if (market.price_history.size() >= 2) { + float sparkGap = S.drawElement("tabs.balance.two-row", "sparkline-gap").sizeOr(6.0f); + float sparkPad = S.drawElement("tabs.balance.two-row", "sparkline-pad").sizeOr(4.0f); + float sparkLeft = cx + priceSz.x + sparkGap; + float sparkRightEdge = sparkRight - sparkGap; + if (sparkLeft < sparkRightEdge) { + ImVec2 spMin(sparkLeft, cMin.y + sparkPad); + ImVec2 spMax(sparkRightEdge, cMax.y - sparkPad); + ImU32 lineCol = pos + ? WithAlpha(Success(), 200) + : WithAlpha(Error(), 200); + DrawSparkline(dl, spMin, spMax, + market.price_history, lineCol); + } + } + } + } + + ImGui::Dummy(ImVec2(availW, miniH)); + } + + ImGui::Dummy(ImVec2(0, cGap)); + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float twoRowAddrOverride = S.drawElement("tabs.balance.two-row", "address-table-height").size; + float addrH = (twoRowAddrOverride >= 0.0f) ? twoRowAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +// ============================================================================ +// Layout 8: Minimal (card-less typography only) +// ============================================================================ +static void RenderBalanceMinimal(App* app) { + using namespace material; + const auto& S = schema::UISchema::instance(); + const auto& state = app->state(); + UpdateBalanceLerp(app); + + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + float availW = contentAvail.x; + float hs = Layout::hScale(availW); + float vs = Layout::vScale(contentAvail.y); + float glassRound = Layout::glassRounding(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + char buf[64]; + + // Top margin + float minTopMargin = S.drawElement("tabs.balance.minimal", "top-margin").size; + if (minTopMargin >= 0.0f) + ImGui::Dummy(ImVec2(0, minTopMargin)); + + ImFont* heroFont = Type().h2(); + ImFont* sub1 = Type().subtitle1(); + ImFont* capFont = Type().caption(); + + // Line 1: Big balance + market price + snprintf(buf, sizeof(buf), "%.8f %s", s_dispTotal, DRAGONX_TICKER); + ImVec2 pos = ImGui::GetCursorScreenPos(); + DrawTextShadow(dl, heroFont, heroFont->LegacySize, pos, OnSurface(), buf); + ImVec2 heroSz = heroFont->CalcTextSizeA(heroFont->LegacySize, 10000.0f, 0.0f, buf); + + // Market price right-aligned + const auto& market = state.market; + if (market.price_usd > 0) { + if (market.price_usd >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", market.price_usd); + else + snprintf(buf, sizeof(buf), "$%.8f", market.price_usd); + ImVec2 pSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float rightEdge = pos.x + availW; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rightEdge - pSz.x, pos.y + heroSz.y - capFont->LegacySize), + OnSurfaceMedium(), buf); + } + ImGui::Dummy(heroSz); + + // Line 2: Shielded + Transparent + snprintf(buf, sizeof(buf), "Shielded: %.8f", s_dispShielded); + Type().textColored(TypeStyle::Caption, Success(), buf); + ImGui::SameLine(0, Layout::spacingLg()); + snprintf(buf, sizeof(buf), "Transparent: %.8f", s_dispTransparent); + Type().textColored(TypeStyle::Caption, Warning(), buf); + + // USD value + double usd_value = state.getBalanceUSD(); + if (usd_value > 0.0) snprintf(buf, sizeof(buf), "$%.2f USD", usd_value); + else snprintf(buf, sizeof(buf), "$-.-- USD"); + ImGui::SameLine(0, Layout::spacingLg()); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + + RenderSyncBar(app, dl, vs); + + // Dashed separator + { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImVec2 sepPos = ImGui::GetCursorScreenPos(); + float dashLen = S.drawElement("tabs.balance.minimal", "dash-length").sizeOr(6.0f); + float gapLen = S.drawElement("tabs.balance.minimal", "dash-gap").sizeOr(4.0f); + float sepAlpha = S.drawElement("tabs.balance.minimal", "separator-alpha").sizeOr(25.0f); + float sepThick = S.drawElement("tabs.balance.minimal", "separator-thickness").sizeOr(1.0f); + float x = sepPos.x; + float endX = sepPos.x + availW; + while (x < endX) { + float x2 = std::min(x + dashLen, endX); + dl->AddLine(ImVec2(x, sepPos.y), ImVec2(x2, sepPos.y), + IM_COL32(255, 255, 255, (int)sepAlpha), sepThick); + x += dashLen + gapLen; + } + ImGui::Dummy(ImVec2(availW, 1)); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + float recentReserve = contentAvail.y * S.drawElement("tabs.balance", "recent-tx-reserve-ratio").sizeOr(0.18f); + float minAddrOverride = S.drawElement("tabs.balance.minimal", "address-table-height").size; + float addrH = (minAddrOverride >= 0.0f) ? minAddrOverride + : ImGui::GetContentRegionAvail().y - recentReserve + - Layout::spacingXl() - Type().h6()->LegacySize - Layout::spacingMd(); + RenderSharedAddressList(app, addrH, availW, glassRound, hs, vs); + RenderSharedRecentTx(app, recentReserve, availW, hs, vs); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/balance_tab.h b/src/ui/windows/balance_tab.h new file mode 100644 index 0000000..880aa86 --- /dev/null +++ b/src/ui/windows/balance_tab.h @@ -0,0 +1,45 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include + +namespace dragonx { +class App; + +namespace ui { + +// A single balance layout entry read from ui.toml +struct BalanceLayoutEntry { + std::string id; // e.g. "classic", "donut", "minimal" + std::string name; // Display name, e.g. "Classic", "Donut Chart" + bool enabled = true; // Whether this layout appears in the settings dropdown +}; + +// Get the list of available balance layouts (parsed from ui.toml). +// On first call (or after RefreshBalanceLayoutConfig()), parses the +// "tabs.balance.layouts.options" array from the schema. +const std::vector& GetBalanceLayouts(); + +// Get the default layout ID from ui.toml ("tabs.balance.layouts.default"). +const std::string& GetDefaultBalanceLayout(); + +// Re-read layout config from schema (call after theme/skin hot-reload). +void RefreshBalanceLayoutConfig(); + +// Legacy int-to-string migration for old settings.json files. +// Maps BalanceLayout enum ordinals (0-8) to their string IDs. +std::string MigrateBalanceLayoutIndex(int index); + +/** + * @brief Render the Balance tab + * Shows balance summary and address list. + * Dispatches to the selected layout from Settings. + */ +void RenderBalanceTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/block_info_dialog.cpp b/src/ui/windows/block_info_dialog.cpp new file mode 100644 index 0000000..11b55e7 --- /dev/null +++ b/src/ui/windows/block_info_dialog.cpp @@ -0,0 +1,315 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "block_info_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../util/i18n.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +#include +#include +#include + +namespace dragonx { +namespace ui { + +using json = nlohmann::json; + +// Static state +static bool s_open = false; +static int s_height = 0; +static bool s_loading = false; +static bool s_has_data = false; +static std::string s_error; + +// Block data +static std::string s_block_hash; +static int64_t s_block_time = 0; +static int s_tx_count = 0; +static int s_block_size = 0; +static std::string s_bits; +static double s_difficulty = 0.0; +static std::string s_prev_hash; +static std::string s_next_hash; +static std::string s_merkle_root; +static int s_confirmations = 0; + +// Pending RPC app pointer (for async callback) +static App* s_pending_app = nullptr; + +void BlockInfoDialog::show(int initialHeight) +{ + s_open = true; + s_height = initialHeight > 0 ? initialHeight : 1; + s_loading = false; + s_has_data = false; + s_error.clear(); +} + +// Callback to handle getblock response +static void handleBlockResponseUnified(const json& result, const std::string& error) +{ + s_loading = false; + + if (!error.empty()) { + s_error = "Error: " + error; + return; + } + + if (!result.is_null()) { + auto block = result; + + s_block_hash = block.value("hash", ""); + s_block_time = block.value("time", (int64_t)0); + s_confirmations = block.value("confirmations", 0); + s_block_size = block.value("size", 0); + s_bits = block.value("bits", ""); + s_difficulty = block.value("difficulty", 0.0); + s_prev_hash = block.value("previousblockhash", ""); + s_next_hash = block.value("nextblockhash", ""); + s_merkle_root = block.value("merkleroot", ""); + + if (block.contains("tx") && block["tx"].is_array()) { + s_tx_count = static_cast(block["tx"].size()); + } else { + s_tx_count = 0; + } + + s_has_data = true; + } else { + s_error = "Invalid response from daemon"; + } +} + +void BlockInfoDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.block-info"); + auto heightInput = S.input("dialogs.block-info", "height-input"); + auto lbl = S.label("dialogs.block-info", "label"); + auto hashLbl = S.label("dialogs.block-info", "hash-label"); + auto hashFrontLbl = S.label("dialogs.block-info", "hash-front-label"); + auto hashBackLbl = S.label("dialogs.block-info", "hash-back-label"); + auto closeBtn = S.button("dialogs.block-info", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Block Information"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Block Information", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + auto* rpc = app->rpc(); + const auto& state = app->getWalletState(); + + // Height input + ImGui::Text("Block Height:"); + ImGui::SetNextItemWidth(heightInput.width); + ImGui::InputInt("##Height", &s_height); + if (s_height < 1) s_height = 1; + + ImGui::SameLine(); + + // Current block info + if (state.sync.blocks > 0) { + ImGui::TextDisabled("(Current: %d)", state.sync.blocks); + } + + ImGui::SameLine(); + + // Fetch button + if (s_loading) { + ImGui::BeginDisabled(); + } + + if (material::StyledButton("Get Block Info", ImVec2(0,0), S.resolveFont(closeBtn.font))) { + if (rpc && rpc->isConnected()) { + s_loading = true; + s_error.clear(); + s_has_data = false; + s_pending_app = app; + + // Use getBlock(height) which uses UnifiedCallback + rpc->getBlock(s_height, handleBlockResponseUnified); + } + } + + if (s_loading) { + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::TextDisabled("Loading..."); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Error display + if (!s_error.empty()) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); + ImGui::TextWrapped("%s", s_error.c_str()); + ImGui::PopStyleColor(); + } + + // Block info display + if (s_has_data) { + // Block hash + ImGui::Text("Block Hash:"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 0.8f, 1.0f, 1.0f)); + ImGui::TextWrapped("%s", s_block_hash.c_str()); + ImGui::PopStyleColor(); + + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Click to copy"); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(s_block_hash.c_str()); + Notifications::instance().success("Block hash copied"); + } + + ImGui::Spacing(); + + // Timestamp + ImGui::Text("Timestamp:"); + ImGui::SameLine(lbl.position); + if (s_block_time > 0) { + std::time_t t = static_cast(s_block_time); + char time_buf[64]; + std::strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&t)); + ImGui::Text("%s", time_buf); + } else { + ImGui::TextDisabled("Unknown"); + } + + // Confirmations + ImGui::Text("Confirmations:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%d", s_confirmations); + + // Transaction count + ImGui::Text("Transactions:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%d", s_tx_count); + + // Size + ImGui::Text("Size:"); + ImGui::SameLine(lbl.position); + if (s_block_size > 1024 * 1024) { + ImGui::Text("%.2f MB", s_block_size / (1024.0 * 1024.0)); + } else if (s_block_size > 1024) { + ImGui::Text("%.2f KB", s_block_size / 1024.0); + } else { + ImGui::Text("%d bytes", s_block_size); + } + + // Difficulty + ImGui::Text("Difficulty:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%.4f", s_difficulty); + + // Bits + ImGui::Text("Bits:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%s", s_bits.c_str()); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Merkle root + ImGui::Text("Merkle Root:"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.7f, 0.7f, 0.7f, 1.0f)); + ImGui::TextWrapped("%s", s_merkle_root.c_str()); + ImGui::PopStyleColor(); + + ImGui::Spacing(); + + // Previous block + if (!s_prev_hash.empty()) { + ImGui::Text("Previous Block:"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 0.8f, 1.0f, 1.0f)); + + // Truncate for display + std::string prev_short = s_prev_hash; + if (prev_short.length() > static_cast(hashLbl.truncate)) { + prev_short = prev_short.substr(0, hashFrontLbl.truncate) + "..." + prev_short.substr(prev_short.length() - hashBackLbl.truncate); + } + ImGui::Text("%s", prev_short.c_str()); + ImGui::PopStyleColor(); + + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Click to view previous block"); + } + if (ImGui::IsItemClicked() && s_height > 1) { + s_height--; + s_has_data = false; + } + } + + // Next block + if (!s_next_hash.empty()) { + ImGui::Text("Next Block:"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 0.8f, 1.0f, 1.0f)); + + // Truncate for display + std::string next_short = s_next_hash; + if (next_short.length() > static_cast(hashLbl.truncate)) { + next_short = next_short.substr(0, hashFrontLbl.truncate) + "..." + next_short.substr(next_short.length() - hashBackLbl.truncate); + } + ImGui::Text("%s", next_short.c_str()); + ImGui::PopStyleColor(); + + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Click to view next block"); + } + if (ImGui::IsItemClicked()) { + s_height++; + s_has_data = false; + } + } + } + + ImGui::Spacing(); + ImGui::Spacing(); + + // Navigation buttons + if (s_has_data) { + if (s_height > 1) { + if (material::StyledButton("<< Previous", ImVec2(0,0), S.resolveFont(closeBtn.font))) { + s_height--; + s_has_data = false; + s_error.clear(); + } + ImGui::SameLine(); + } + + if (!s_next_hash.empty()) { + if (material::StyledButton("Next >>", ImVec2(0,0), S.resolveFont(closeBtn.font))) { + s_height++; + s_has_data = false; + s_error.clear(); + } + } + } + + // Close button at bottom + ImGui::SetCursorPosY(ImGui::GetWindowHeight() - 40); + if (material::StyledButton("Close", ImVec2(closeBtn.width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/block_info_dialog.h b/src/ui/windows/block_info_dialog.h new file mode 100644 index 0000000..5c63b8b --- /dev/null +++ b/src/ui/windows/block_info_dialog.h @@ -0,0 +1,35 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for viewing block information by height + * + * Allows entering a block height to view: + * - Block hash + * - Timestamp + * - Number of transactions + * - Size, bits, difficulty + * - Previous/next block hash + */ +class BlockInfoDialog { +public: + // Show the dialog, optionally at a specific height + static void show(int initialHeight = -1); + + // Render the dialog (call each frame) + static void render(App* app); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/console_tab.cpp b/src/ui/windows/console_tab.cpp new file mode 100644 index 0000000..44679d0 --- /dev/null +++ b/src/ui/windows/console_tab.cpp @@ -0,0 +1,1736 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "console_tab.h" +#include "../material/colors.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../layout.h" +#include "../effects/imgui_acrylic.h" +#include "../material/color_theme.h" +#include "../theme.h" +#include "../../embedded/IconsMaterialDesign.h" + +#include +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +// Static color definitions — defaults; overridden from ui.toml in constructor +ImU32 ConsoleTab::COLOR_COMMAND = IM_COL32(191, 209, 229, 255); +ImU32 ConsoleTab::COLOR_RESULT = IM_COL32(200, 200, 200, 255); +ImU32 ConsoleTab::COLOR_ERROR = IM_COL32(246, 71, 64, 255); +ImU32 ConsoleTab::COLOR_DAEMON = IM_COL32(160, 160, 160, 180); +ImU32 ConsoleTab::COLOR_INFO = IM_COL32(191, 209, 229, 255); +bool ConsoleTab::s_scanline_enabled = true; +float ConsoleTab::s_console_zoom = 1.0f; +bool ConsoleTab::s_daemon_messages_enabled = true; +bool ConsoleTab::s_errors_only_enabled = false; + +void ConsoleTab::refreshColors() +{ + auto& S = schema::UI(); + bool dark = material::IsDarkTheme(); + + // Try schema overrides first, then use sensible per-theme defaults + if (S.isLoaded()) { + auto cmd = S.drawElement("console", "color-command"); + auto res = S.drawElement("console", "color-result"); + auto err = S.drawElement("console", "color-error"); + auto dmn = S.drawElement("console", "color-daemon"); + auto inf = S.drawElement("console", "color-info"); + + ImU32 defCmd = dark ? IM_COL32(191, 209, 229, 255) : IM_COL32(21, 101, 192, 255); + ImU32 defRes = dark ? IM_COL32(200, 200, 200, 255) : IM_COL32(50, 50, 50, 255); + ImU32 defErr = dark ? IM_COL32(246, 71, 64, 255) : IM_COL32(198, 40, 40, 255); + ImU32 defDmn = dark ? IM_COL32(160, 160, 160, 180) : IM_COL32(90, 90, 90, 200); + ImU32 defInf = dark ? IM_COL32(191, 209, 229, 255) : IM_COL32(21, 101, 192, 255); + + COLOR_COMMAND = !cmd.color.empty() ? S.resolveColor(cmd.color, defCmd) : defCmd; + COLOR_RESULT = !res.color.empty() ? S.resolveColor(res.color, defRes) : defRes; + COLOR_ERROR = !err.color.empty() ? S.resolveColor(err.color, defErr) : defErr; + COLOR_DAEMON = !dmn.color.empty() ? S.resolveColor(dmn.color, defDmn) : defDmn; + COLOR_INFO = !inf.color.empty() ? S.resolveColor(inf.color, defInf) : defInf; + } else { + // No schema — use hardcoded defaults per theme + COLOR_COMMAND = dark ? IM_COL32(191, 209, 229, 255) : IM_COL32(21, 101, 192, 255); + COLOR_RESULT = dark ? IM_COL32(200, 200, 200, 255) : IM_COL32(50, 50, 50, 255); + COLOR_ERROR = dark ? IM_COL32(246, 71, 64, 255) : IM_COL32(198, 40, 40, 255); + COLOR_DAEMON = dark ? IM_COL32(160, 160, 160, 180) : IM_COL32(90, 90, 90, 200); + COLOR_INFO = dark ? IM_COL32(191, 209, 229, 255) : IM_COL32(21, 101, 192, 255); + } +} + +ConsoleTab::ConsoleTab() +{ + // Load console colors from ui.toml schema (uses current theme) + refreshColors(); + + // Add welcome message + addLine("DragonX Wallet Console", COLOR_INFO); + addLine("Type 'help' for available commands", COLOR_INFO); + addLine("", COLOR_RESULT); +} + +void ConsoleTab::render(daemon::EmbeddedDaemon* daemon, rpc::RPCClient* rpc, rpc::RPCWorker* worker, daemon::XmrigManager* xmrig) +{ + using namespace material; + + // Refresh console colors when dark/light theme changes + { + static bool s_lastDark = IsDarkTheme(); + bool nowDark = IsDarkTheme(); + if (nowDark != s_lastDark) { + // Save old colors to remap existing lines + ImU32 oldCmd = COLOR_COMMAND, oldRes = COLOR_RESULT; + ImU32 oldErr = COLOR_ERROR, oldDmn = COLOR_DAEMON; + ImU32 oldInf = COLOR_INFO; + refreshColors(); + // Remap stored line colors from old to new + { + std::lock_guard lock(lines_mutex_); + for (auto& line : lines_) { + if (line.color == oldCmd) line.color = COLOR_COMMAND; + else if (line.color == oldRes) line.color = COLOR_RESULT; + else if (line.color == oldErr) line.color = COLOR_ERROR; + else if (line.color == oldDmn) line.color = COLOR_DAEMON; + else if (line.color == oldInf) line.color = COLOR_INFO; + } + } + s_lastDark = nowDark; + } + } + + // Check for daemon state changes + if (daemon) { + auto current_state = daemon->getState(); + + // Show message when daemon starts + if (current_state == daemon::EmbeddedDaemon::State::Starting && + last_daemon_state_ == daemon::EmbeddedDaemon::State::Stopped) { + addLine("", COLOR_RESULT); + addLine("=== Starting DragonX Full Node ===", COLOR_INFO); + addLine("Capturing daemon output...", COLOR_INFO); + addLine("", COLOR_RESULT); + shown_startup_message_ = true; + } + else if (current_state == daemon::EmbeddedDaemon::State::Running && + last_daemon_state_ != daemon::EmbeddedDaemon::State::Running) { + addLine("=== Daemon is running ===", COLOR_INFO); + } + else if (current_state == daemon::EmbeddedDaemon::State::Stopped && + last_daemon_state_ == daemon::EmbeddedDaemon::State::Running) { + addLine("", COLOR_RESULT); + addLine("=== Daemon stopped ===", COLOR_INFO); + } + else if (current_state == daemon::EmbeddedDaemon::State::Error) { + addLine("=== Daemon error: " + daemon->getLastError() + " ===", COLOR_ERROR); + } + + last_daemon_state_ = current_state; + } + + // Check for new daemon output — always capture so toggle works as a live filter + if (daemon) { + std::string new_output = daemon->getOutputSince(last_daemon_output_size_); + if (!new_output.empty()) { + // Split by newlines and add each line + std::istringstream stream(new_output); + std::string line; + while (std::getline(stream, line)) { + if (!line.empty()) { + // Color based on content: [ERROR] -> red, [WARN] -> warning color + ImU32 lineColor = COLOR_DAEMON; + if (line.find("[ERROR]") != std::string::npos || + line.find("error:") != std::string::npos || + line.find("Error:") != std::string::npos) { + lineColor = COLOR_ERROR; + } + addLine("[daemon] " + line, lineColor); + } + } + } + } + + // Check for new xmrig output (pool mining) + if (xmrig && xmrig->isRunning()) { + std::string new_output = xmrig->getOutputSince(last_xmrig_output_size_); + if (!new_output.empty()) { + std::istringstream stream(new_output); + std::string line; + while (std::getline(stream, line)) { + if (!line.empty()) { + // Color xmrig output - errors in red, accepted shares in green + ImU32 lineColor = COLOR_DAEMON; + if (line.find("error") != std::string::npos || + line.find("ERROR") != std::string::npos || + line.find("failed") != std::string::npos) { + lineColor = COLOR_ERROR; + } else if (line.find("accepted") != std::string::npos) { + lineColor = COLOR_INFO; + } + addLine("[xmrig] " + line, lineColor); + } + } + } + } else if (!xmrig || !xmrig->isRunning()) { + // Reset offset when xmrig stops so we get fresh output next time + if (last_xmrig_output_size_ != 0) { + last_xmrig_output_size_ = 0; + } + } + + // Main console layout + ImGui::BeginChild("ConsoleContainer", ImVec2(0, 0), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar); + + // Toolbar + renderToolbar(daemon); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Output area (scrollable) — glass panel background + float frameH = ImGui::GetFrameHeightWithSpacing(); + float itemSp = ImGui::GetStyle().ItemSpacing.y; + float input_height = (Layout::spacingSm() + itemSp) // Dummy(0,sm) + spacing + + frameH + Layout::spacingSm() + Layout::spacingXs() + schema::UI().drawElement("tabs.console", "input-cursor-offset").size; // input glass panel + cursor offset + float outputH = ImGui::GetContentRegionAvail().y - input_height; + float availHeight = ImGui::GetContentRegionAvail().y; + if (outputH < std::max(schema::UI().drawElement("tabs.console", "output-min-height").size, availHeight * schema::UI().drawElement("tabs.console", "output-min-height-ratio").size)) outputH = std::max(schema::UI().drawElement("tabs.console", "output-min-height").size, availHeight * schema::UI().drawElement("tabs.console", "output-min-height-ratio").size); + + ImDrawList* dlOut = ImGui::GetWindowDrawList(); + ImVec2 outPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 outPanelMax(outPanelMin.x + ImGui::GetContentRegionAvail().x, outPanelMin.y + outputH); + GlassPanelSpec outGlass; + outGlass.rounding = Layout::glassRounding(); + outGlass.fillAlpha = 12; + DrawGlassPanel(dlOut, outPanelMin, outPanelMax, outGlass); + + int consoleParentVtx = dlOut->VtxBuffer.Size; + + ImGui::BeginChild("ConsoleOutput", ImVec2(0, outputH), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + ImDrawList* consoleChildDL = ImGui::GetWindowDrawList(); + int consoleChildVtx = consoleChildDL->VtxBuffer.Size; + float consoleScrollY = ImGui::GetScrollY(); + float consoleScrollMaxY = ImGui::GetScrollMaxY(); + // Use smaller font for console output + ImGui::PushFont(Type().caption()); + ImGui::SetWindowFontScale(s_console_zoom); + renderOutput(); + ImGui::SetWindowFontScale(1.0f); + ImGui::PopFont(); + ImGui::EndChild(); + + // CSS-style clipping mask + { + float fadeZone = std::min(Type().caption()->LegacySize * 3.0f, outputH * 0.18f); + ApplyScrollEdgeMask(dlOut, consoleParentVtx, consoleChildDL, consoleChildVtx, + outPanelMin.y, outPanelMax.y, fadeZone, consoleScrollY, consoleScrollMaxY); + } + + // CRT scanline effect over output area — aligned to text lines + if (s_scanline_enabled) { + float panelH = outPanelMax.y - outPanelMin.y; + + // --- Text-aligned horizontal scanlines --- + // Stride matches the actual text line height so each band sits between lines. + float textLineH = output_line_height_; + if (textLineH <= 1.0f) textLineH = Type().caption()->LegacySize * s_console_zoom + 2.0f; // fallback + float bandH = schema::UI().drawElement("tabs.console", "scanline-gap").sizeOr(2.0f); + int lineAlpha = (int)schema::UI().drawElement("tabs.console", "scanline-line-alpha").sizeOr(18.0f); + + // Glow fringe parameters (soft gradient above/below each band) + float glowSpread = schema::UI().drawElement("tabs.console", "scanline-glow-spread").sizeOr(0.0f); + float glowIntensity = schema::UI().drawElement("tabs.console", "scanline-glow-intensity").sizeOr(0.6f); + int glowRGB = (int)schema::UI().drawElement("tabs.console", "scanline-glow-color").sizeOr(255.0f); + bool drawGlow = glowSpread > 0.0f && glowIntensity > 0.0f && lineAlpha > 0; + int glowAlpha = drawGlow ? std::min(255, (int)(lineAlpha * glowIntensity)) : 0; + ImU32 glowPeak = IM_COL32(glowRGB, glowRGB, glowRGB, glowAlpha); + ImU32 glowClear = IM_COL32(glowRGB, glowRGB, glowRGB, 0); + + if (textLineH >= 1.0f && lineAlpha > 0) { + ImU32 lineCol = IM_COL32(255, 255, 255, lineAlpha); + float stride = textLineH; // one text line per scanline period + // Align with text: account for inner padding and scroll position + float padY = Layout::spacingSm(); + float scrollFrac = std::fmod(consoleScrollY, stride); + float startY = outPanelMin.y + padY - scrollFrac; + // Ensure first band starts above the visible area + while (startY > outPanelMin.y) startY -= stride; + for (float y = startY; y < outPanelMax.y; y += stride) { + // Place the dark band at the bottom edge of each text line period + float bandTop = y + stride - bandH; + float bandBot = y + stride; + float yTop = std::max(bandTop, outPanelMin.y); + float yBot = std::min(bandBot, outPanelMax.y); + if (yTop < yBot) { + // Glow fringes (gradient tapers away from band) + if (drawGlow) { + // Above fringe: transparent at top, glowPeak at bottom + float gTop = std::max(yTop - glowSpread, outPanelMin.y); + if (gTop < yTop) { + dlOut->AddRectFilledMultiColor( + ImVec2(outPanelMin.x, gTop), ImVec2(outPanelMax.x, yTop), + glowClear, glowClear, glowPeak, glowPeak); + } + // Below fringe: glowPeak at top, transparent at bottom + float gBot = std::min(yBot + glowSpread, outPanelMax.y); + if (yBot < gBot) { + dlOut->AddRectFilledMultiColor( + ImVec2(outPanelMin.x, yBot), ImVec2(outPanelMax.x, gBot), + glowPeak, glowPeak, glowClear, glowClear); + } + } + // Opaque scanline band (drawn on top of glow) + dlOut->AddRectFilled(ImVec2(outPanelMin.x, yTop), ImVec2(outPanelMax.x, yBot), lineCol); + } + } + } + + // --- Animated sweep band (brighter moving highlight) --- + float scanSpeed = schema::UI().drawElement("tabs.console", "scanline-speed").sizeOr(40.0f); + float scanH = schema::UI().drawElement("tabs.console", "scanline-height").sizeOr(30.0f); + int scanAlpha = (int)schema::UI().drawElement("tabs.console", "scanline-alpha").sizeOr(12.0f); + float t = (float)std::fmod(ImGui::GetTime() * scanSpeed, (double)(panelH + scanH)); + float scanY = outPanelMin.y + t - scanH; + float yTop = std::max(scanY, outPanelMin.y); + float yBot = std::min(scanY + scanH, outPanelMax.y); + if (yTop < yBot) { + float mid = (yTop + yBot) * 0.5f; + ImU32 clear = IM_COL32(255, 255, 255, 0); + ImU32 peak = IM_COL32(255, 255, 255, scanAlpha); + dlOut->AddRectFilledMultiColor( + ImVec2(outPanelMin.x, yTop), ImVec2(outPanelMax.x, mid), + clear, clear, peak, peak); + dlOut->AddRectFilledMultiColor( + ImVec2(outPanelMin.x, mid), ImVec2(outPanelMax.x, yBot), + peak, peak, clear, clear); + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Input area + renderInput(rpc, worker); + + ImGui::EndChild(); +} + +void ConsoleTab::renderCommandsPopupModal() +{ + if (!show_commands_popup_) { + renderCommandsPopup(); + return; + } + // Called at top-level window scope so the modal blocks all input. + ImGui::OpenPopup("RPC Command Reference"); + show_commands_popup_ = false; + renderCommandsPopup(); +} + +void ConsoleTab::renderToolbar(daemon::EmbeddedDaemon* daemon) +{ + using namespace material; + ImDrawList* dl = ImGui::GetWindowDrawList(); + + // Glass panel for toolbar + float toolbarH = ImGui::GetFrameHeightWithSpacing() + Layout::spacingMd(); + ImVec2 tbMin = ImGui::GetCursorScreenPos(); + ImVec2 tbMax(tbMin.x + ImGui::GetContentRegionAvail().x, tbMin.y + toolbarH); + GlassPanelSpec tbGlass; + tbGlass.rounding = Layout::glassRounding(); + tbGlass.fillAlpha = 12; + DrawGlassPanel(dl, tbMin, tbMax, tbGlass); + + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (toolbarH - ImGui::GetFrameHeight()) * 0.5f); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + Layout::spacingMd()); + + // Daemon status with colored dot + if (daemon) { + auto state = daemon->getState(); + const char* status_text = "Unknown"; + ImU32 dotCol = IM_COL32(150, 150, 150, 255); + bool pulse = false; + + switch (state) { + case daemon::EmbeddedDaemon::State::Stopped: + status_text = "Stopped"; + dotCol = IM_COL32(150, 150, 150, 255); + break; + case daemon::EmbeddedDaemon::State::Starting: + status_text = "Starting"; + dotCol = Warning(); + pulse = true; + break; + case daemon::EmbeddedDaemon::State::Running: + status_text = "Running"; + dotCol = Success(); + break; + case daemon::EmbeddedDaemon::State::Stopping: + status_text = "Stopping"; + dotCol = Warning(); + pulse = true; + break; + case daemon::EmbeddedDaemon::State::Error: + status_text = "Error"; + dotCol = Error(); + break; + } + + ImVec2 cp = ImGui::GetCursorScreenPos(); + float dotR = schema::UI().drawElement("tabs.console", "status-dot-radius-base").size + schema::UI().drawElement("tabs.console", "status-dot-radius-scale").size * Layout::hScale(); + float dotY = cp.y + ImGui::GetTextLineHeight() * 0.5f; + float dotX = cp.x + dotR + 2; + + if (pulse) { + float a = schema::UI().drawElement("animations", "pulse-base-glow").size + schema::UI().drawElement("animations", "pulse-amp-glow").size * (float)std::sin((double)ImGui::GetTime() * schema::UI().drawElement("animations", "pulse-speed-fast").size); + ImU32 pCol = (dotCol & 0x00FFFFFF) | ((ImU32)(255 * a) << 24); + dl->AddCircleFilled(ImVec2(dotX, dotY), dotR, pCol); + } else { + dl->AddCircleFilled(ImVec2(dotX, dotY), dotR, dotCol); + } + + ImGui::Dummy(ImVec2(dotR * 2 + 6, 0)); + ImGui::SameLine(); + Type().textColored(TypeStyle::Caption, dotCol, status_text); + } else { + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), "No daemon"); + } + + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + + // Auto-scroll toggle + if (ImGui::Checkbox("Auto-scroll", &auto_scroll_)) { + if (auto_scroll_) { + scroll_to_bottom_ = true; + new_lines_since_scroll_ = 0; + } + } + + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + + // Daemon messages toggle + { + static bool s_prev_daemon_enabled = true; + ImGui::Checkbox("Daemon", &s_daemon_messages_enabled); + // When toggling daemon filter while auto-scroll is active, scroll to bottom + if (s_prev_daemon_enabled != s_daemon_messages_enabled && auto_scroll_) { + scroll_to_bottom_ = true; + } + s_prev_daemon_enabled = s_daemon_messages_enabled; + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Show daemon output messages"); + } + + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + + // Errors-only toggle + { + static bool s_prev_errors_only = false; + ImGui::Checkbox("Errors", &s_errors_only_enabled); + // When toggling errors filter while auto-scroll is active, scroll to bottom + if (s_prev_errors_only != s_errors_only_enabled && auto_scroll_) { + scroll_to_bottom_ = true; + } + s_prev_errors_only = s_errors_only_enabled; + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Show only error messages"); + } + + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + + // Clear button + if (TactileButton("Clear", ImVec2(0, 0), schema::UI().resolveFont("button"))) { + clear(); + clearSelection(); + } + + ImGui::SameLine(); + + // Copy button — material styled + if (TactileButton("Copy", ImVec2(0, 0), schema::UI().resolveFont("button"))) { + std::lock_guard lock(lines_mutex_); + if (has_selection_) { + std::string selected = getSelectedText(); + if (!selected.empty()) { + ImGui::SetClipboardText(selected.c_str()); + } + } else { + // Copy all output if nothing selected + std::string all; + for (const auto& line : lines_) { + all += line.text + "\n"; + } + if (!all.empty()) { + ImGui::SetClipboardText(all.c_str()); + } + } + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip(has_selection_ ? "Copy selected text" : "Copy all output"); + } + + ImGui::SameLine(); + + // Commands reference button + if (TactileButton("Commands", ImVec2(0, 0), schema::UI().resolveFont("button"))) { + show_commands_popup_ = true; + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Show RPC command reference"); + } + + ImGui::SameLine(); + + // Line count + { + std::lock_guard lock(lines_mutex_); + ImGui::TextDisabled("(%zu lines)", lines_.size()); + } + + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + + // Output filter input + float zoomBtnSpace = ImGui::GetFrameHeight() * 2.0f + Layout::spacingSm() * 3.0f; + float filterAvail = ImGui::GetContentRegionAvail().x - zoomBtnSpace; + float filterW = std::min(schema::UI().drawElement("tabs.console", "filter-max-width").size, filterAvail * schema::UI().drawElement("tabs.console", "filter-width-ratio").size); + ImGui::SetNextItemWidth(filterW); + ImGui::InputTextWithHint("##ConsoleFilter", "Filter output...", filter_text_, sizeof(filter_text_)); + + // Zoom +/- buttons (right side of toolbar) + ImGui::SameLine(); + ImGui::Spacing(); + ImGui::SameLine(); + { + auto& S = schema::UI(); + float zoomStep = S.drawElement("tabs.console", "zoom-step").sizeOr(0.1f); + float zoomMin = S.drawElement("tabs.console", "zoom-min").sizeOr(0.5f); + float zoomMax = S.drawElement("tabs.console", "zoom-max").sizeOr(3.0f); + float btnSz = ImGui::GetFrameHeight(); + + if (TactileButton(ICON_MD_REMOVE, ImVec2(btnSz, btnSz), Type().iconMed())) { + s_console_zoom = std::max(zoomMin, s_console_zoom - zoomStep); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Zoom out (%.0f%%)", s_console_zoom * 100.0f); + } + ImGui::SameLine(); + if (TactileButton(ICON_MD_ADD, ImVec2(btnSz, btnSz), Type().iconMed())) { + s_console_zoom = std::min(zoomMax, s_console_zoom + zoomStep); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Zoom in (%.0f%%)", s_console_zoom * 100.0f); + } + } +} + +void ConsoleTab::renderOutput() +{ + using namespace material; + auto& S = schema::UI(); + std::lock_guard lock(lines_mutex_); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, S.drawElement("tabs.console", "output").size)); + + // Inner padding for glass panel + float padX = Layout::spacingMd(); + float padY = Layout::spacingSm(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + padY); + ImGui::Indent(padX); + + float line_height = ImGui::GetTextLineHeightWithSpacing(); + output_line_height_ = line_height; // store for scanline alignment + output_origin_ = ImGui::GetCursorScreenPos(); + output_scroll_y_ = ImGui::GetScrollY(); + + // Build filtered line index list BEFORE mouse handling (so screenToTextPos works) + std::string filter_str(filter_text_); + bool has_text_filter = !filter_str.empty(); + bool hide_daemon = !s_daemon_messages_enabled; + bool errors_only = s_errors_only_enabled; + bool has_filter = has_text_filter || hide_daemon || errors_only; + visible_indices_.clear(); + if (has_filter) { + std::string filter_lower; + if (has_text_filter) { + filter_lower = filter_str; + std::transform(filter_lower.begin(), filter_lower.end(), filter_lower.begin(), ::tolower); + } + for (int i = 0; i < static_cast(lines_.size()); i++) { + // Skip daemon lines when daemon toggle is off + if (hide_daemon && lines_[i].color == COLOR_DAEMON) continue; + // When errors-only is enabled, skip non-error lines + if (errors_only && lines_[i].color != COLOR_ERROR) continue; + if (has_text_filter) { + std::string lower = lines_[i].text; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower.find(filter_lower) == std::string::npos) continue; + } + visible_indices_.push_back(i); + } + } else { + // No filter - all lines are visible + for (int i = 0; i < static_cast(lines_.size()); i++) { + visible_indices_.push_back(i); + } + } + int visible_count = static_cast(visible_indices_.size()); + + // Calculate wrapped heights for each visible line + // This is needed because TextWrapped creates variable-height content + float wrap_width = ImGui::GetContentRegionAvail().x - padX * 2; + if (wrap_width < 50.0f) wrap_width = 50.0f; // Minimum wrap width + + wrapped_heights_.resize(visible_count); + cumulative_y_offsets_.resize(visible_count); + total_wrapped_height_ = 0.0f; + cached_wrap_width_ = wrap_width; + + for (int vi = 0; vi < visible_count; vi++) { + int i = visible_indices_[vi]; + const std::string& text = lines_[i].text; + + // Calculate wrapped text size - CalcTextSize with wrap_width > 0 + ImVec2 sz; + if (text.empty()) { + sz = ImVec2(0.0f, line_height); + } else { + sz = ImGui::CalcTextSize(text.c_str(), nullptr, false, wrap_width); + // Add a small margin for item spacing + sz.y = std::max(sz.y, line_height); + } + + cumulative_y_offsets_[vi] = total_wrapped_height_; + wrapped_heights_[vi] = sz.y; + total_wrapped_height_ += sz.y; + } + + // Use raw IO for mouse handling to bypass child window event consumption + ImGuiIO& io = ImGui::GetIO(); + ImVec2 mouse_pos = io.MousePos; + + // Manual hit test: is mouse within this child window? + ImVec2 win_min = ImGui::GetWindowPos(); + ImVec2 win_max = ImVec2(win_min.x + ImGui::GetWindowWidth(), + win_min.y + ImGui::GetWindowHeight()); + bool mouse_in_output = (mouse_pos.x >= win_min.x && mouse_pos.x < win_max.x && + mouse_pos.y >= win_min.y && mouse_pos.y < win_max.y && + !ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup)); + + // Disable auto-scroll when user scrolls up (wheel scroll) + if (mouse_in_output && io.MouseWheel > 0.0f) { + auto_scroll_ = false; + } + + // Set cursor to text selection when hovering + if (mouse_in_output) { + ImGui::SetMouseCursor(ImGuiMouseCursor_TextInput); + } + + // Mouse press - start selection (use raw IO mouse state) + if (mouse_in_output && io.MouseClicked[0]) { + sel_anchor_ = screenToTextPos(mouse_pos, line_height); + sel_end_ = sel_anchor_; + is_selecting_ = true; + has_selection_ = false; + } + + // Mouse drag - extend selection (continue even if mouse leaves the window) + if (is_selecting_ && io.MouseDown[0]) { + TextPos new_end = screenToTextPos(mouse_pos, line_height); + sel_end_ = new_end; + // Consider it a real selection once the position changes + if (sel_end_.line != sel_anchor_.line || sel_end_.col != sel_anchor_.col) { + has_selection_ = true; + } + } + + // Mouse release - finalize selection + if (is_selecting_ && io.MouseReleased[0]) { + sel_end_ = screenToTextPos(mouse_pos, line_height); + is_selecting_ = false; + } + + // Ctrl+C / Ctrl+A + if (mouse_in_output || has_selection_) { + if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_C)) { + std::string selected = getSelectedText(); + if (!selected.empty()) { + ImGui::SetClipboardText(selected.c_str()); + } + } + if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_A)) { + // Select all + if (!lines_.empty()) { + sel_anchor_ = {0, 0}; + sel_end_ = {static_cast(lines_.size()) - 1, + static_cast(lines_.back().text.size())}; + has_selection_ = true; + } + } + } + + // Get selection bounds (ordered) + TextPos sel_start_pos = selectionStart(); + TextPos sel_end_pos = selectionEnd(); + + // Render lines with selection highlighting + // Use manual rendering instead of ImGuiListClipper to support variable-height wrapped lines + float scroll_y = ImGui::GetScrollY(); + float window_height = ImGui::GetWindowHeight(); + float visible_top = scroll_y; + float visible_bottom = scroll_y + window_height; + + // Find first visible line using binary search + int first_visible = 0; + if (!cumulative_y_offsets_.empty()) { + int lo = 0, hi = static_cast(cumulative_y_offsets_.size()) - 1; + while (lo < hi) { + int mid = (lo + hi) / 2; + float line_bottom = cumulative_y_offsets_[mid] + wrapped_heights_[mid]; + if (line_bottom < visible_top) { + lo = mid + 1; + } else { + hi = mid; + } + } + first_visible = lo; + } + + // Add invisible spacer for lines before first visible (for correct scroll) + if (first_visible > 0 && first_visible < static_cast(cumulative_y_offsets_.size())) { + ImGui::Dummy(ImVec2(0, cumulative_y_offsets_[first_visible])); + } + + // Render visible lines + int last_rendered_vi = first_visible - 1; // Track actual last rendered line + for (int vi = first_visible; vi < visible_count; vi++) { + // Early exit if we're past the visible region + if (vi < static_cast(cumulative_y_offsets_.size()) && + cumulative_y_offsets_[vi] > visible_bottom) { + break; + } + last_rendered_vi = vi; + + int i = visible_indices_[vi]; + const auto& line = lines_[i]; + ImVec2 text_pos = ImGui::GetCursorScreenPos(); + float this_line_height = (vi < static_cast(wrapped_heights_.size())) + ? wrapped_heights_[vi] : line_height; + + // Draw selection highlight for this line + if (has_selection_ && i >= sel_start_pos.line && i <= sel_end_pos.line) { + int sel_col_start = 0; + int sel_col_end = static_cast(line.text.size()); + + if (i == sel_start_pos.line) { + sel_col_start = sel_start_pos.col; + } + if (i == sel_end_pos.line) { + sel_col_end = sel_end_pos.col; + } + + if (sel_col_start < sel_col_end) { + // Calculate pixel positions for highlight + float x_start = 0; + float x_end = 0; + + if (sel_col_start > 0 && sel_col_start <= static_cast(line.text.size())) { + ImVec2 sz = ImGui::CalcTextSize(line.text.c_str(), + line.text.c_str() + sel_col_start); + x_start = sz.x; + } + if (sel_col_end <= static_cast(line.text.size())) { + ImVec2 sz = ImGui::CalcTextSize(line.text.c_str(), + line.text.c_str() + sel_col_end); + x_end = sz.x; + } else { + x_end = ImGui::CalcTextSize(line.text.c_str()).x; + } + + // If full line selected, extend highlight to window edge + if (sel_col_end >= static_cast(line.text.size())) { + x_end = std::max(x_end + S.drawElement("tabs.console", "selection-extension").size, ImGui::GetWindowWidth()); + } + + // Use actual wrapped height for selection highlight + ImVec2 rect_min(text_pos.x + x_start, text_pos.y); + ImVec2 rect_max(text_pos.x + x_end, text_pos.y + this_line_height); + ImGui::GetWindowDrawList()->AddRectFilled( + rect_min, rect_max, + WithAlpha(Secondary(), 80) // Selection highlight + ); + } + } + + ImGui::PushStyleColor(ImGuiCol_Text, ImColor(line.color).Value); + ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x - padX); + ImGui::TextWrapped("%s", line.text.c_str()); + ImGui::PopTextWrapPos(); + ImGui::PopStyleColor(); + } + + // Add spacer for lines after last visible (to maintain correct content height) + if (last_rendered_vi >= 0 && last_rendered_vi < visible_count - 1) { + float rendered_height = (last_rendered_vi < static_cast(cumulative_y_offsets_.size())) + ? cumulative_y_offsets_[last_rendered_vi] + wrapped_heights_[last_rendered_vi] + : 0.0f; + float remaining_height = total_wrapped_height_ - rendered_height; + if (remaining_height > 0) { + ImGui::Dummy(ImVec2(0, remaining_height)); + } + } + + ImGui::Unindent(padX); + ImGui::PopStyleVar(); + + // Add bottom padding so the last line sits above the fade-out zone. + // Only the fade zone height is used — no extra padding beyond that, + // so text can still overflow into the fade and scrolling stays snappy. + { + float fadeZone = std::min(Type().caption()->LegacySize * 3.0f, + ImGui::GetWindowHeight() * 0.18f); + ImGui::Dummy(ImVec2(0, fadeZone)); + } + + // Auto-scroll - when enabled, always scroll to bottom of content + // This ensures daemon output stays visible and scrolled to bottom + if (auto_scroll_) { + ImGui::SetScrollHereY(1.0f); + scroll_to_bottom_ = false; + new_lines_since_scroll_ = 0; + } + + // Filter indicator (text filter only — daemon toggle is already visible in toolbar) + if (has_text_filter) { + char filterBuf[128]; + snprintf(filterBuf, sizeof(filterBuf), "Showing %d of %zu lines", + visible_count, lines_.size()); + ImVec2 indicatorPos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddText(indicatorPos, + WithAlpha(Warning(), 180), filterBuf); + ImGui::Dummy(ImVec2(0, ImGui::GetTextLineHeight())); + } + + // Right-click context menu + if (ImGui::BeginPopupContextWindow("ConsoleContextMenu")) { + if (ImGui::MenuItem("Copy", "Ctrl+C", false, has_selection_)) { + std::string selected = getSelectedText(); + if (!selected.empty()) { + ImGui::SetClipboardText(selected.c_str()); + } + } + if (ImGui::MenuItem("Select All", "Ctrl+A")) { + if (!lines_.empty()) { + sel_anchor_ = {0, 0}; + sel_end_ = {static_cast(lines_.size()) - 1, + static_cast(lines_.back().text.size())}; + has_selection_ = true; + } + } + ImGui::Separator(); + if (ImGui::MenuItem("Clear Console")) { + // Can't call clear() here (already holding lock), just mark for clearing + lines_.clear(); + has_selection_ = false; + } + ImGui::EndPopup(); + } + + // "New output" indicator when user is scrolled up and new lines arrived + if (!auto_scroll_ && new_lines_since_scroll_ > 0) { + float indicW = 140.0f; + float indicH = 24.0f; + ImDrawList* dlInd = ImGui::GetWindowDrawList(); + ImVec2 wMin = ImGui::GetWindowPos(); + ImVec2 wSize = ImGui::GetWindowSize(); + float ix = wMin.x + (wSize.x - indicW) * 0.5f; + float iy = wMin.y + wSize.y - indicH - 8.0f; + ImVec2 iMin(ix, iy); + ImVec2 iMax(ix + indicW, iy + indicH); + + dlInd->AddRectFilled(iMin, iMax, IM_COL32(40, 40, 40, 220), 12.0f); + dlInd->AddRect(iMin, iMax, IM_COL32(255, 218, 0, 120), 12.0f); + + char buf[48]; + snprintf(buf, sizeof(buf), " %d new line%s", + new_lines_since_scroll_, new_lines_since_scroll_ != 1 ? "s" : ""); + ImFont* capFont = Type().caption(); + if (!capFont) capFont = ImGui::GetFont(); + ImFont* icoFont = Type().iconSmall(); + if (!icoFont) icoFont = capFont; + + // Measure icon + text to center them together + ImVec2 icoSz = icoFont->CalcTextSizeA(icoFont->LegacySize, FLT_MAX, 0, ICON_MD_ARROW_DOWNWARD); + ImVec2 txtSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + float totalW = icoSz.x + txtSz.x; + float startX = ix + (indicW - totalW) * 0.5f; + float icoY = iy + (indicH - icoSz.y) * 0.5f; + float txtY = iy + (indicH - txtSz.y) * 0.5f; + ImU32 col = IM_COL32(255, 218, 0, 255); + dlInd->AddText(icoFont, icoFont->LegacySize, ImVec2(startX, icoY), col, ICON_MD_ARROW_DOWNWARD); + dlInd->AddText(capFont, capFont->LegacySize, ImVec2(startX + icoSz.x, txtY), col, buf); + + // Click to jump to bottom + ImGui::SetCursorScreenPos(iMin); + if (ImGui::InvisibleButton("##scrollToBottom", ImVec2(indicW, indicH))) { + auto_scroll_ = true; + scroll_to_bottom_ = true; + new_lines_since_scroll_ = 0; + } + } +} + +ConsoleTab::TextPos ConsoleTab::screenToTextPos(ImVec2 screen_pos, float line_height) const +{ + TextPos pos; + + if (visible_indices_.empty()) { + return {0, 0}; + } + + // Calculate which VISIBLE line based on Y position relative to output origin + // Use cumulative_y_offsets_ for accurate wrapped text positioning + float relative_y = screen_pos.y - output_origin_.y; + + // Find the visible line using cumulative Y offsets (binary search) + int visible_line = 0; + if (!cumulative_y_offsets_.empty()) { + // Binary search for the line that contains this Y position + int lo = 0, hi = static_cast(cumulative_y_offsets_.size()) - 1; + while (lo < hi) { + int mid = (lo + hi + 1) / 2; + if (cumulative_y_offsets_[mid] <= relative_y) { + lo = mid; + } else { + hi = mid - 1; + } + } + visible_line = lo; + } else { + // Fallback to fixed line height if offsets not calculated + visible_line = static_cast(relative_y / line_height); + } + + // Clamp visible line to valid range + if (visible_line < 0) visible_line = 0; + if (visible_line >= static_cast(visible_indices_.size())) { + visible_line = static_cast(visible_indices_.size()) - 1; + pos.line = visible_indices_[visible_line]; + pos.col = static_cast(lines_[pos.line].text.size()); + return pos; + } + + // Map visible line index to actual line index + pos.line = visible_indices_[visible_line]; + + // Calculate column from X position + const std::string& text = lines_[pos.line].text; + float relative_x = screen_pos.x - output_origin_.x; + + if (relative_x <= 0 || text.empty()) { + pos.col = 0; + return pos; + } + + // Binary search for the character position + // Walk character by character for accuracy + pos.col = 0; + for (int c = 0; c < static_cast(text.size()); c++) { + ImVec2 sz = ImGui::CalcTextSize(text.c_str(), text.c_str() + c + 1); + float char_mid = (c > 0) + ? (ImGui::CalcTextSize(text.c_str(), text.c_str() + c).x + sz.x) * 0.5f + : sz.x * 0.5f; + if (relative_x < char_mid) { + pos.col = c; + return pos; + } + pos.col = c + 1; + } + + pos.col = static_cast(text.size()); + return pos; +} + +bool ConsoleTab::isPosBeforeOrEqual(const TextPos& a, const TextPos& b) const +{ + if (a.line < b.line) return true; + if (a.line > b.line) return false; + return a.col <= b.col; +} + +ConsoleTab::TextPos ConsoleTab::selectionStart() const +{ + return isPosBeforeOrEqual(sel_anchor_, sel_end_) ? sel_anchor_ : sel_end_; +} + +ConsoleTab::TextPos ConsoleTab::selectionEnd() const +{ + return isPosBeforeOrEqual(sel_anchor_, sel_end_) ? sel_end_ : sel_anchor_; +} + +std::string ConsoleTab::getSelectedText() const +{ + if (!has_selection_) return ""; + + TextPos start = selectionStart(); + TextPos end = selectionEnd(); + + if (start.line < 0 || start.line >= static_cast(lines_.size())) return ""; + + // Build a set of visible line indices for quick lookup + // (Only copy visible lines when filtering is active) + std::unordered_set visible_set(visible_indices_.begin(), visible_indices_.end()); + bool has_filter = !visible_indices_.empty() && visible_indices_.size() < lines_.size(); + + std::string result; + bool first_line = true; + + for (int i = start.line; i <= end.line && i < static_cast(lines_.size()); i++) { + // Skip lines that aren't visible when filtering + if (has_filter && visible_set.find(i) == visible_set.end()) { + continue; + } + + const std::string& text = lines_[i].text; + + int col_start = 0; + int col_end = static_cast(text.size()); + + if (i == start.line) col_start = std::min(start.col, static_cast(text.size())); + if (i == end.line) col_end = std::min(end.col, static_cast(text.size())); + + // Add newline between lines (but not before first) + if (!first_line) { + result += "\n"; + } + first_line = false; + + if (col_start < col_end) { + result += text.substr(col_start, col_end - col_start); + } + } + + return result; +} + +void ConsoleTab::clearSelection() +{ + has_selection_ = false; + is_selecting_ = false; + sel_anchor_ = {-1, 0}; + sel_end_ = {-1, 0}; +} + +void ConsoleTab::renderInput(rpc::RPCClient* rpc, rpc::RPCWorker* worker) +{ + using namespace material; + + // Glass panel for input area + ImDrawList* dlIn = ImGui::GetWindowDrawList(); + float inputPanelH = ImGui::GetFrameHeightWithSpacing() + Layout::spacingSm() + Layout::spacingXs(); + ImVec2 inMin = ImGui::GetCursorScreenPos(); + ImVec2 inMax(inMin.x + ImGui::GetContentRegionAvail().x, inMin.y + inputPanelH); + GlassPanelSpec inGlass; + inGlass.rounding = Layout::glassRounding(); + inGlass.fillAlpha = 12; + material::DrawGlassPanel(dlIn, inMin, inMax, inGlass); + + // Center content vertically within glass panel + float inputFrameH = ImGui::GetFrameHeight(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (inputPanelH - inputFrameH) * 0.5f); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + Layout::spacingMd()); + + + + // Input field + ImGui::PushItemWidth(-Layout::spacingMd()); + + ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue | + ImGuiInputTextFlags_CallbackHistory | + ImGuiInputTextFlags_CallbackCompletion; + + bool reclaim_focus = false; + + auto callback = [](ImGuiInputTextCallbackData* data) -> int { + ConsoleTab* console = static_cast(data->UserData); + + if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) { + // Handle history navigation + if (console->command_history_.empty()) return 0; + + int prev_index = console->history_index_; + + if (data->EventKey == ImGuiKey_UpArrow) { + if (console->history_index_ < 0) { + console->history_index_ = static_cast(console->command_history_.size()) - 1; + } else if (console->history_index_ > 0) { + console->history_index_--; + } + } else if (data->EventKey == ImGuiKey_DownArrow) { + if (console->history_index_ >= 0) { + console->history_index_++; + if (console->history_index_ >= static_cast(console->command_history_.size())) { + console->history_index_ = -1; + } + } + } + + if (prev_index != console->history_index_) { + const char* history_str = (console->history_index_ >= 0) + ? console->command_history_[console->history_index_].c_str() + : ""; + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, history_str); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) { + // Tab completion for common RPC commands + static const char* commands[] = { + // Control + "help", "getinfo", "stop", + // Network + "getnetworkinfo", "getpeerinfo", "getconnectioncount", + "addnode", "setban", "listbanned", "clearbanned", "ping", + // Blockchain + "getblockchaininfo", "getblockcount", "getbestblockhash", + "getblock", "getblockhash", "getblockheader", "getdifficulty", + "getrawmempool", "gettxout", "coinsupply", "getchaintips", + // Mining + "getmininginfo", "setgenerate", "getgenerate", + "getnetworkhashps", "getblocksubsidy", + // Wallet + "getbalance", "z_gettotalbalance", "z_getbalances", + "getnewaddress", "z_getnewaddress", + "listaddresses", "z_listaddresses", + "sendtoaddress", "z_sendmany", + "listtransactions", "listunspent", "z_listunspent", + "z_getoperationstatus", "z_getoperationresult", + "getwalletinfo", "backupwallet", + "dumpprivkey", "importprivkey", + "z_exportkey", "z_importkey", + "signmessage", "settxfee", + // Raw Transactions + "createrawtransaction", "decoderawtransaction", + "getrawtransaction", "sendrawtransaction", "signrawtransaction", + // Utility + "validateaddress", "z_validateaddress", "estimatefee", + // Built-in + "clear" + }; + + std::string input(data->Buf); + if (!input.empty()) { + // Collect all matches + std::vector matches; + for (const char* cmd : commands) { + if (strncmp(cmd, input.c_str(), input.length()) == 0) { + matches.push_back(cmd); + } + } + + if (matches.size() == 1) { + // Single match — complete it + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, matches[0]); + } else if (matches.size() > 1) { + // Multiple matches — show list in console and complete common prefix + console->addLine("Completions:", ConsoleTab::COLOR_INFO); + std::string line = " "; + for (size_t m = 0; m < matches.size(); m++) { + if (m > 0) line += " "; + line += matches[m]; + if (line.length() > 60) { + console->addLine(line, ConsoleTab::COLOR_RESULT); + line = " "; + } + } + if (line.length() > 2) { + console->addLine(line, ConsoleTab::COLOR_RESULT); + } + + // Complete to longest common prefix + std::string prefix = matches[0]; + for (size_t m = 1; m < matches.size(); m++) { + size_t len = 0; + while (len < prefix.length() && len < strlen(matches[m]) && + prefix[len] == matches[m][len]) len++; + prefix = prefix.substr(0, len); + } + if (prefix.length() > input.length()) { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, prefix.c_str()); + } + } + } + } + + return 0; + }; + + if (ImGui::InputText("##ConsoleInput", input_buffer_, sizeof(input_buffer_), flags, callback, this)) { + std::string cmd(input_buffer_); + if (!cmd.empty()) { + executeCommand(cmd, rpc, worker); + input_buffer_[0] = '\0'; + reclaim_focus = true; + } + } + + ImGui::PopItemWidth(); + + // Auto-focus on input + if (reclaim_focus) { + ImGui::SetKeyboardFocusHere(-1); + } +} + +void ConsoleTab::renderCommandsPopup() +{ + using namespace material; + + // Center the modal + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + float popW = std::min(schema::UI().drawElement("tabs.console", "popup-max-width").size, ImGui::GetMainViewport()->Size.x * schema::UI().drawElement("tabs.console", "popup-width-ratio").size); + float popH = std::min(schema::UI().drawElement("tabs.console", "popup-max-height").size, ImGui::GetMainViewport()->Size.y * schema::UI().drawElement("tabs.console", "popup-height-ratio").size); + ImGui::SetNextWindowSize(ImVec2(popW, popH), ImGuiCond_Appearing); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(Layout::spacingXl(), Layout::spacingLg())); + if (!effects::ImGuiAcrylic::BeginAcrylicPopupModal("RPC Command Reference", nullptr, + ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ImGui::PopStyleVar(); + return; + } + + Type().text(TypeStyle::H6, "RPC Command Reference"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Search filter + static char cmdFilter[128] = {0}; + ImGui::SetNextItemWidth(-1); + ImGui::InputTextWithHint("##CmdSearch", "Search commands...", cmdFilter, sizeof(cmdFilter)); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Command entries + struct CmdEntry { const char* name; const char* desc; const char* params; }; + + static const CmdEntry controlCmds[] = { + {"help", "List all commands, or get help for a specified command", "[\"command\"]"}, + {"getinfo", "Get general info about the node", ""}, + {"stop", "Stop the daemon", ""}, + }; + static const CmdEntry networkCmds[] = { + {"getnetworkinfo", "Return P2P network state info", ""}, + {"getpeerinfo", "Get data about each connected peer", ""}, + {"getconnectioncount", "Get number of peer connections", ""}, + {"getnettotals", "Get network traffic statistics", ""}, + {"addnode", "Add, remove, or connect to a node", "\"node\" \"add|remove|onetry\""}, + {"setban", "Add or remove an IP/subnet from the ban list", "\"ip\" \"add|remove\" [bantime] [absolute]"}, + {"listbanned", "List all banned IPs/subnets", ""}, + {"clearbanned", "Clear all banned IPs", ""}, + {"ping", "Ping all peers to measure round-trip time", ""}, + }; + static const CmdEntry blockchainCmds[] = { + {"getblockchaininfo", "Get current blockchain state", ""}, + {"getblockcount", "Get number of blocks in longest chain", ""}, + {"getbestblockhash", "Get hash of the tip block", ""}, + {"getblock", "Get block data for a given hash or height", "\"hash|height\" [verbosity]"}, + {"getblockhash", "Get block hash at a given height", "height"}, + {"getblockheader", "Get block header for a given hash", "\"hash\" [verbose]"}, + {"getdifficulty", "Get proof-of-work difficulty", ""}, + {"getrawmempool", "Get all txids in mempool", "[verbose]"}, + {"getmempoolinfo", "Get mempool state info", ""}, + {"gettxout", "Get details about an unspent output", "\"txid\" n [includemempool]"}, + {"coinsupply", "Get coin supply information", "[height]"}, + {"getchaintips", "Get all known chain tips", ""}, + {"getchaintxstats", "Get chain transaction statistics", "[nblocks] [\"blockhash\"]"}, + {"verifychain", "Verify the blockchain database", "[checklevel] [numblocks]"}, + {"kvsearch", "Search the blockchain key-value store", "\"key\""}, + {"kvupdate", "Update a key-value pair on-chain", "\"key\" \"value\" days"}, + }; + static const CmdEntry miningCmds[] = { + {"getmininginfo", "Get mining-related information", ""}, + {"setgenerate", "Turn mining on or off (true/false [threads])", "generate [genproclimit]"}, + {"getgenerate", "Check if the node is mining", ""}, + {"getnetworkhashps", "Get estimated network hash rate", "[blocks] [height]"}, + {"getblocksubsidy", "Get block reward at a given height", "[height]"}, + {"getblocktemplate", "Get block template for mining", "[\"jsonrequestobject\"]"}, + {"submitblock", "Submit a mined block to the network", "\"hexdata\""}, + }; + static const CmdEntry walletCmds[] = { + {"getbalance", "Get wallet transparent balance", "[\"account\"] [minconf]"}, + {"z_gettotalbalance", "Get total transparent + shielded balance", "[minconf]"}, + {"z_getbalances", "Get all balances (transparent + shielded)", ""}, + {"getnewaddress", "Generate a new transparent address", ""}, + {"z_getnewaddress", "Generate a new shielded address", "[\"type\"]"}, + {"listaddresses", "List all transparent addresses", ""}, + {"z_listaddresses", "List all z-addresses", ""}, + {"sendtoaddress", "Send to a specific address", "\"address\" amount"}, + {"z_sendmany", "Send to multiple z/t-addresses with shielded support", "\"fromaddress\" [{\"address\":\"...\",\"amount\":...}]"}, + {"z_shieldcoinbase", "Shield transparent coinbase funds to a z-address", "\"fromaddress\" \"tozaddress\" [fee] [limit]"}, + {"z_mergetoaddress", "Merge multiple UTXOs/notes to one address", "[\"fromaddress\",...] \"toaddress\" [fee] [limit]"}, + {"listtransactions", "List recent wallet transactions", "[\"account\"] [count] [from]"}, + {"listunspent", "List unspent transaction outputs", "[minconf] [maxconf]"}, + {"z_listunspent", "List unspent shielded notes", "[minconf] [maxconf]"}, + {"z_getoperationstatus", "Get status of async z operations", "[\"operationid\",...]"}, + {"z_getoperationresult", "Get result of completed z operations", "[\"operationid\",...]"}, + {"z_listoperationids", "List all async z operation IDs", ""}, + {"getwalletinfo", "Get wallet state info", ""}, + {"backupwallet", "Back up wallet to a file", "\"destination\""}, + {"dumpprivkey", "Dump private key for an address", "\"address\""}, + {"importprivkey", "Import a private key into the wallet", "\"privkey\" [\"label\"] [rescan]"}, + {"dumpwallet", "Dump all wallet keys to a file", "\"filename\""}, + {"importwallet", "Import wallet from a dump file", "\"filename\""}, + {"z_exportkey", "Export spending key for a z-address", "\"zaddr\""}, + {"z_importkey", "Import a z-address spending key", "\"zkey\" [rescan] [startheight]"}, + {"z_exportviewingkey", "Export viewing key for a z-address", "\"zaddr\""}, + {"z_importviewingkey", "Import a z-address viewing key", "\"vkey\" [rescan] [startheight]"}, + {"z_exportwallet", "Export all wallet keys (including z-keys) to file", "\"filename\""}, + {"signmessage", "Sign a message with an address key", "\"address\" \"message\""}, + {"settxfee", "Set the transaction fee per kB", "amount"}, + {"walletpassphrase", "Unlock the wallet with passphrase", "\"passphrase\" timeout"}, + {"walletlock", "Lock the wallet", ""}, + {"encryptwallet", "Encrypt the wallet with a passphrase", "\"passphrase\""}, + }; + static const CmdEntry rawTxCmds[] = { + {"createrawtransaction", "Create a raw transaction spending given inputs", "[{\"txid\":\"...\",\"vout\":n},...] {\"address\":amount,...}"}, + {"decoderawtransaction", "Decode raw transaction hex string", "\"hexstring\""}, + {"decodescript", "Decode a hex-encoded script", "\"hex\""}, + {"getrawtransaction", "Get raw transaction data by txid", "\"txid\" [verbose]"}, + {"sendrawtransaction", "Submit raw transaction to the network", "\"hexstring\" [allowhighfees]"}, + {"signrawtransaction", "Sign a raw transaction with private keys", "\"hexstring\""}, + {"fundrawtransaction", "Add inputs to meet output value", "\"hexstring\""}, + }; + static const CmdEntry utilCmds[] = { + {"validateaddress", "Validate a transparent address", "\"address\""}, + {"z_validateaddress", "Validate a z-address", "\"zaddr\""}, + {"estimatefee", "Estimate fee for a transaction", "nblocks"}, + {"verifymessage", "Verify a signed message", "\"address\" \"signature\" \"message\""}, + {"createmultisig", "Create a multisig address", "nrequired [\"key\",...]"}, + {"invalidateblock", "Mark a block as invalid", "\"hash\""}, + {"reconsiderblock", "Reconsider a previously invalidated block", "\"hash\""}, + }; + + struct CmdCategory { const char* name; const CmdEntry* commands; int count; }; + + static const CmdCategory categories[] = { + {"Control", controlCmds, IM_ARRAYSIZE(controlCmds)}, + {"Network", networkCmds, IM_ARRAYSIZE(networkCmds)}, + {"Blockchain", blockchainCmds, IM_ARRAYSIZE(blockchainCmds)}, + {"Mining", miningCmds, IM_ARRAYSIZE(miningCmds)}, + {"Wallet", walletCmds, IM_ARRAYSIZE(walletCmds)}, + {"Raw Transactions", rawTxCmds, IM_ARRAYSIZE(rawTxCmds)}, + {"Utility", utilCmds, IM_ARRAYSIZE(utilCmds)}, + }; + + std::string filter(cmdFilter); + std::transform(filter.begin(), filter.end(), filter.begin(), ::tolower); + + ImGui::BeginChild("CmdListScroll", ImVec2(0, -ImGui::GetFrameHeightWithSpacing() - Layout::spacingXs()), + false); + + ImGui::PushFont(Type().caption()); + + float cmdMinWidth = schema::UI().drawElement("tabs.console", "cmd-min-width").sizeOr(500.0f); + float popupInnerW = ImGui::GetContentRegionAvail().x; + bool showParams = popupInnerW >= cmdMinWidth; + int catIdx = 0; + + for (const auto& cat : categories) { + // Count matching commands in this category + int matchCount = 0; + if (filter.empty()) { + matchCount = cat.count; + } else { + for (int i = 0; i < cat.count; i++) { + std::string name(cat.commands[i].name); + std::string desc(cat.commands[i].desc); + std::string params(cat.commands[i].params); + std::transform(name.begin(), name.end(), name.begin(), ::tolower); + std::transform(desc.begin(), desc.end(), desc.begin(), ::tolower); + std::transform(params.begin(), params.end(), params.begin(), ::tolower); + if (name.find(filter) != std::string::npos || + desc.find(filter) != std::string::npos || + params.find(filter) != std::string::npos) { + matchCount++; + } + } + } + if (matchCount == 0) { catIdx++; continue; } + + // Default-open only the first category (Control); collapse the rest + ImGuiTreeNodeFlags headerFlags = (catIdx == 0) ? ImGuiTreeNodeFlags_DefaultOpen : 0; + // When filtering, open all matching categories + if (!filter.empty()) headerFlags = ImGuiTreeNodeFlags_DefaultOpen; + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(Primary())); + // Show match count badge when filtering + char headerLabel[128]; + if (!filter.empty()) { + snprintf(headerLabel, sizeof(headerLabel), "%s (%d)", cat.name, matchCount); + } else { + snprintf(headerLabel, sizeof(headerLabel), "%s", cat.name); + } + bool open = ImGui::CollapsingHeader(headerLabel, headerFlags); + ImGui::PopStyleColor(); + catIdx++; + + if (open) { + float nameColW = schema::UI().drawElement("tabs.console", "cmd-name-col-width").size * Layout::hScale(); + float paramsColW = schema::UI().drawElement("tabs.console", "cmd-params-col-width").size * Layout::hScale(); + int numCols = showParams ? 3 : 2; + if (ImGui::BeginTable("##cmds", numCols, ImGuiTableFlags_None)) { + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, nameColW); + if (showParams) + ImGui::TableSetupColumn("Parameters", ImGuiTableColumnFlags_WidthFixed, paramsColW); + ImGui::TableSetupColumn("Desc", ImGuiTableColumnFlags_WidthStretch); + + for (int i = 0; i < cat.count; i++) { + const auto& cmd = cat.commands[i]; + std::string nameLower(cmd.name); + std::string descLower(cmd.desc); + std::string paramsLower(cmd.params); + std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower); + std::transform(descLower.begin(), descLower.end(), descLower.begin(), ::tolower); + std::transform(paramsLower.begin(), paramsLower.end(), paramsLower.begin(), ::tolower); + + if (!filter.empty() && + nameLower.find(filter) == std::string::npos && + descLower.find(filter) == std::string::npos && + paramsLower.find(filter) == std::string::npos) { + continue; + } + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushStyleColor(ImGuiCol_Text, + ImGui::ColorConvertU32ToFloat4(IM_COL32(100, 180, 255, 255))); + ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0.2f, 0.4f, 0.6f, 0.3f)); + char selId[128]; + snprintf(selId, sizeof(selId), "%s##cmdRef", cmd.name); + if (ImGui::Selectable(selId, false)) { + if (cmd.params[0] != '\0') { + snprintf(input_buffer_, sizeof(input_buffer_), "%s %s", cmd.name, cmd.params); + } else { + strncpy(input_buffer_, cmd.name, sizeof(input_buffer_) - 1); + input_buffer_[sizeof(input_buffer_) - 1] = '\0'; + } + ImGui::CloseCurrentPopup(); + } + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (cmd.params[0] != '\0') + ImGui::SetTooltip("Click to insert '%s %s' into input", cmd.name, cmd.params); + else + ImGui::SetTooltip("Click to insert '%s' into input", cmd.name); + } + ImGui::PopStyleColor(3); + if (showParams) { + ImGui::TableNextColumn(); + // Style optional params [param] in dimmed text + const char* p = cmd.params; + bool first = true; + while (*p) { + const char* bracketStart = strchr(p, '['); + if (bracketStart) { + // Draw required part before bracket + if (bracketStart > p) { + if (!first) ImGui::SameLine(0, 0); + std::string req(p, bracketStart); + ImGui::TextColored( + ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled()), + "%s", req.c_str()); + first = false; + } + // Find matching ] + const char* bracketEnd = strchr(bracketStart, ']'); + if (bracketEnd) { + if (!first) ImGui::SameLine(0, 0); + std::string opt(bracketStart, bracketEnd + 1); + ImGui::TextColored( + ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium()), + "%s", opt.c_str()); + first = false; + p = bracketEnd + 1; + } else { + if (!first) ImGui::SameLine(0, 0); + ImGui::TextColored( + ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled()), + "%s", bracketStart); + first = false; + break; + } + } else { + if (!first) ImGui::SameLine(0, 0); + ImGui::TextColored( + ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled()), + "%s", p); + first = false; + break; + } + } + } + ImGui::TableNextColumn(); + ImGui::TextColored( + ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium()), + "%s", cmd.desc); + } + + ImGui::EndTable(); + } + ImGui::Spacing(); + } + } + + ImGui::PopFont(); + ImGui::EndChild(); + + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Close button + if (ImGui::Button("Close", ImVec2(-1, 0))) { + cmdFilter[0] = '\0'; + ImGui::CloseCurrentPopup(); + } + + effects::ImGuiAcrylic::EndAcrylicPopup(); + ImGui::PopStyleVar(); +} + +void ConsoleTab::executeCommand(const std::string& cmd, rpc::RPCClient* rpc, rpc::RPCWorker* worker) +{ + using namespace material; + // Add to history (avoid duplicates) + if (command_history_.empty() || command_history_.back() != cmd) { + command_history_.push_back(cmd); + if (command_history_.size() > 100) { + command_history_.erase(command_history_.begin()); + } + } + history_index_ = -1; + + // Echo command + addLine("> " + cmd, COLOR_COMMAND); + + // Handle built-in commands + if (cmd == "clear") { + clear(); + return; + } + + if (cmd == "help") { + addLine("Available commands:", COLOR_INFO); + addLine(" clear - Clear console output", COLOR_RESULT); + addLine(" help - Show this help", COLOR_RESULT); + addLine("", COLOR_RESULT); + addLine("Common RPC commands (when connected):", COLOR_INFO); + addLine(" getinfo - Get daemon info", COLOR_RESULT); + addLine(" getbalance - Get transparent balance", COLOR_RESULT); + addLine(" z_gettotalbalance - Get total balance", COLOR_RESULT); + addLine(" getblockcount - Get current block height", COLOR_RESULT); + addLine(" getpeerinfo - Get connected peers", COLOR_RESULT); + addLine(" setgenerate true/false [threads] - Mining on/off", COLOR_RESULT); + addLine(" getmininginfo - Get mining status", COLOR_RESULT); + addLine(" stop - Stop the daemon", COLOR_RESULT); + addLine("", COLOR_RESULT); + addLine("Click 'Commands' in the toolbar for full RPC reference", COLOR_INFO); + addLine("Use Tab for command completion, Up/Down for history", COLOR_INFO); + return; + } + + // Execute RPC command + if (!rpc || !rpc->isConnected()) { + addLine("Error: Not connected to daemon", COLOR_ERROR); + return; + } + + // Parse command and arguments + std::vector args; + std::istringstream iss(cmd); + std::string token; + while (iss >> token) { + args.push_back(token); + } + + if (args.empty()) return; + + std::string method = args[0]; + nlohmann::json params = nlohmann::json::array(); + + // Convert remaining args to JSON params + for (size_t i = 1; i < args.size(); i++) { + const std::string& arg = args[i]; + + // Try to parse as number + try { + if (arg.find('.') != std::string::npos) { + params.push_back(std::stod(arg)); + } else { + // Check for bool + if (arg == "true") { + params.push_back(true); + } else if (arg == "false") { + params.push_back(false); + } else { + // Try as integer + params.push_back(std::stoll(arg)); + } + } + } catch (...) { + // Keep as string + params.push_back(arg); + } + } + + // Execute RPC call on worker thread to avoid blocking UI + if (worker) { + // Capture 'this' for addLine calls in MainCb (runs on main thread, ConsoleTab outlives callbacks) + auto self = this; + worker->post([rpc, method, params, self]() -> rpc::RPCWorker::MainCb { + std::string result_str; + bool is_error = false; + try { + result_str = rpc->callRaw(method, params); + if (result_str == "null") { + result_str = "(no result)"; + } + } catch (const std::exception& e) { + result_str = e.what(); + is_error = true; + } + return [result_str, is_error, self]() { + // Process results on main thread where ImGui colors are available + using namespace material; + if (is_error) { + self->addLine("Error: " + result_str, COLOR_ERROR); + return; + } + + bool is_json = false; + if (!result_str.empty()) { + char first = result_str[0]; + is_json = (first == '{' || first == '['); + } + ImU32 json_key_col = WithAlpha(Secondary(), 255); + ImU32 json_str_col = WithAlpha(Success(), 255); + ImU32 json_num_col = WithAlpha(Warning(), 255); + ImU32 json_brace_col = IM_COL32(200, 200, 200, 150); + + std::istringstream stream(result_str); + std::string line; + while (std::getline(stream, line)) { + if (is_json && !line.empty()) { + std::string trimmed = line; + size_t first = trimmed.find_first_not_of(" \t"); + if (first != std::string::npos) trimmed = trimmed.substr(first); + + ImU32 lineCol = COLOR_RESULT; + if (trimmed[0] == '{' || trimmed[0] == '}' || + trimmed[0] == '[' || trimmed[0] == ']') { + lineCol = json_brace_col; + } else if (trimmed[0] == '\"') { + size_t colon = trimmed.find("\": "); + if (colon != std::string::npos || trimmed.find("\":") != std::string::npos) { + lineCol = json_key_col; + } else { + lineCol = json_str_col; + } + } else if (std::isdigit(trimmed[0]) || trimmed[0] == '-') { + lineCol = json_num_col; + } else if (trimmed == "true," || trimmed == "false," || + trimmed == "true" || trimmed == "false" || + trimmed == "null," || trimmed == "null") { + lineCol = json_num_col; + } + self->addLine(line, lineCol); + } else { + self->addLine(line, COLOR_RESULT); + } + } + }; + }); + } else { + // Fallback: synchronous execution if no worker available + try { + std::string result_str = rpc->callRaw(method, params); + if (result_str == "null") result_str = "(no result)"; + std::istringstream stream(result_str); + std::string line; + while (std::getline(stream, line)) { + addLine(line, COLOR_RESULT); + } + } catch (const std::exception& e) { + addLine("Error: " + std::string(e.what()), COLOR_ERROR); + } + } +} + +void ConsoleTab::addLine(const std::string& line, ImU32 color) +{ + std::lock_guard lock(lines_mutex_); + + lines_.push_back({line, color}); + + // Limit buffer size + while (lines_.size() > 10000) { + lines_.pop_front(); + } + + // Track new output while user is scrolled up + if (!auto_scroll_) { + new_lines_since_scroll_++; + } + + scroll_to_bottom_ = auto_scroll_; +} + +void ConsoleTab::addCommandResult(const std::string& cmd, const std::string& result, bool is_error) +{ + addLine("> " + cmd, COLOR_COMMAND); + + std::istringstream stream(result); + std::string line; + while (std::getline(stream, line)) { + addLine(line, is_error ? COLOR_ERROR : COLOR_RESULT); + } +} + +void ConsoleTab::clear() +{ + { + std::lock_guard lock(lines_mutex_); + lines_.clear(); + last_daemon_output_size_ = 0; + last_xmrig_output_size_ = 0; + } + // addLine() takes the lock itself, so call it outside the locked scope + addLine("Console cleared", COLOR_INFO); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/console_tab.h b/src/ui/windows/console_tab.h new file mode 100644 index 0000000..52dfe5c --- /dev/null +++ b/src/ui/windows/console_tab.h @@ -0,0 +1,148 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "../layout.h" +#include "../../daemon/embedded_daemon.h" +#include "../../daemon/xmrig_manager.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +/** + * @brief Console tab for daemon output and command input + * + * Shows dragonxd output and allows executing RPC commands. + */ +class ConsoleTab { +public: + ConsoleTab(); + ~ConsoleTab() = default; + + /** + * @brief Render the console tab + * @param daemon Pointer to embedded daemon (may be null) + * @param rpc Pointer to RPC client for command execution + * @param xmrig Pointer to xmrig manager for pool mining output (may be null) + */ + void render(daemon::EmbeddedDaemon* daemon, rpc::RPCClient* rpc, rpc::RPCWorker* worker, daemon::XmrigManager* xmrig = nullptr); + + /** + * @brief Render the RPC Command Reference popup at top-level scope. + * Must be called outside any child window so the modal blocks all input. + */ + void renderCommandsPopupModal(); + + /** + * @brief Add a line to the console output + */ + void addLine(const std::string& line, ImU32 color = IM_COL32(200, 200, 200, 255)); + + /** + * @brief Clear console output + */ + void clear(); + + /** + * @brief Check if auto-scroll is enabled + */ + bool isAutoScrollEnabled() const { return auto_scroll_; } + + // Scanline effect toggle (set from settings) + static bool s_scanline_enabled; + + // Console output zoom factor (1.0 = default caption font size) + static float s_console_zoom; + + // Show/hide daemon output messages + static bool s_daemon_messages_enabled; + + // Show only error messages (filter toggle) + static bool s_errors_only_enabled; + + /// Refresh console text colors for current theme (call after theme switch) + static void refreshColors(); + + // Colors — follow active theme (public for use by notification forwarding) + static ImU32 COLOR_COMMAND; + static ImU32 COLOR_RESULT; + static ImU32 COLOR_ERROR; + static ImU32 COLOR_DAEMON; + static ImU32 COLOR_INFO; + +private: + struct ConsoleLine { + std::string text; + ImU32 color; + }; + + void executeCommand(const std::string& cmd, rpc::RPCClient* rpc, rpc::RPCWorker* worker); + void addCommandResult(const std::string& cmd, const std::string& result, bool is_error = false); + void renderToolbar(daemon::EmbeddedDaemon* daemon); + void renderOutput(); + void renderInput(rpc::RPCClient* rpc, rpc::RPCWorker* worker); + void renderCommandsPopup(); + + // Selection helpers + void handleSelection(); + std::string getSelectedText() const; + void clearSelection(); + + // Convert screen position to line/column + struct TextPos { + int line = -1; + int col = 0; + }; + TextPos screenToTextPos(ImVec2 screen_pos, float line_height) const; + bool isPosBeforeOrEqual(const TextPos& a, const TextPos& b) const; + TextPos selectionStart() const; // Returns the earlier of sel_anchor_ and sel_end_ + TextPos selectionEnd() const; // Returns the later of sel_anchor_ and sel_end_ + + std::deque lines_; + std::vector command_history_; + int history_index_ = -1; + char input_buffer_[4096] = {0}; + bool auto_scroll_ = true; + bool scroll_to_bottom_ = false; + int new_lines_since_scroll_ = 0; // new lines while scrolled up (for indicator) + size_t last_daemon_output_size_ = 0; + size_t last_xmrig_output_size_ = 0; + bool shown_startup_message_ = false; + daemon::EmbeddedDaemon::State last_daemon_state_ = daemon::EmbeddedDaemon::State::Stopped; + + // Text selection state + bool is_selecting_ = false; + bool has_selection_ = false; + TextPos sel_anchor_; // Where the mouse was first pressed + TextPos sel_end_; // Where the mouse currently is / was released + float output_scroll_y_ = 0.0f; // Track scroll position for selection + ImVec2 output_origin_ = {0, 0}; // Top-left of output area + float output_line_height_ = 0.0f; // Text line height (for scanline alignment) + + std::mutex lines_mutex_; + + // Output filter + char filter_text_[128] = {0}; + mutable std::vector visible_indices_; // Cached for selection mapping + + // Wrapped line height caching (for variable-height text wrapping) + mutable std::vector wrapped_heights_; // Height of each visible line (accounts for wrapping) + mutable std::vector cumulative_y_offsets_; // Cumulative Y offset for each visible line + mutable float total_wrapped_height_ = 0.0f; // Total height of all visible lines + mutable float cached_wrap_width_ = 0.0f; // Wrap width used for cached heights + + // Commands popup + bool show_commands_popup_ = false; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/export_all_keys_dialog.cpp b/src/ui/windows/export_all_keys_dialog.cpp new file mode 100644 index 0000000..c5b1d10 --- /dev/null +++ b/src/ui/windows/export_all_keys_dialog.cpp @@ -0,0 +1,258 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "export_all_keys_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../material/type.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using json = nlohmann::json; + +// Static state +static bool s_open = false; +static bool s_exporting = false; +static std::string s_status; +static std::string s_exported_keys; +static int s_total_addresses = 0; +static int s_exported_count = 0; +static bool s_include_z = true; +static bool s_include_t = true; +static char s_filename[256] = ""; + +void ExportAllKeysDialog::show() +{ + s_open = true; + s_exporting = false; + s_status.clear(); + s_exported_keys.clear(); + s_total_addresses = 0; + s_exported_count = 0; + s_include_z = true; + s_include_t = true; + + // Generate default filename with timestamp + std::time_t now = std::time(nullptr); + char timebuf[32]; + std::strftime(timebuf, sizeof(timebuf), "%Y%m%d_%H%M%S", std::localtime(&now)); + snprintf(s_filename, sizeof(s_filename), "dragonx_keys_%s.txt", timebuf); +} + +bool ExportAllKeysDialog::isOpen() +{ + return s_open; +} + +void ExportAllKeysDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.export-all-keys"); + auto exportBtn = S.button("dialogs.export-all-keys", "export-button"); + auto closeBtn = S.button("dialogs.export-all-keys", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Export All Private Keys"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Export All Private Keys", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + // Warning + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); + ImGui::PushFont(material::Type().iconSmall()); + ImGui::Text(ICON_MD_WARNING); + ImGui::PopFont(); + ImGui::SameLine(0, 4.0f); + ImGui::TextWrapped("DANGER: This will export ALL private keys from your wallet! " + "Anyone with access to this file can steal your funds. " + "Store it securely and delete after use."); + ImGui::PopStyleColor(); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + if (s_exporting) { + ImGui::BeginDisabled(); + } + + // Options + ImGui::Text("Export options:"); + ImGui::Checkbox("Include Z-addresses (shielded)", &s_include_z); + ImGui::Checkbox("Include T-addresses (transparent)", &s_include_t); + + ImGui::Spacing(); + + // Filename + ImGui::Text("Output filename:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##Filename", s_filename, sizeof(s_filename)); + + ImGui::Spacing(); + ImGui::TextDisabled("File will be saved in: ~/.config/ObsidianDragon/"); + + if (s_exporting) { + ImGui::EndDisabled(); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Export button + if (s_exporting) { + ImGui::BeginDisabled(); + } + + if (material::StyledButton("Export Keys", ImVec2(exportBtn.width, 0), S.resolveFont(exportBtn.font))) { + if (!s_include_z && !s_include_t) { + Notifications::instance().warning("Select at least one address type"); + } else if (!app->rpc() || !app->rpc()->isConnected()) { + Notifications::instance().error("Not connected to daemon"); + } else { + s_exporting = true; + s_exported_keys.clear(); + s_exported_count = 0; + s_status = "Exporting keys..."; + + const auto& state = app->getWalletState(); + + // Count total addresses to export + s_total_addresses = 0; + if (s_include_z) s_total_addresses += static_cast(state.z_addresses.size()); + if (s_include_t) s_total_addresses += static_cast(state.t_addresses.size()); + + if (s_total_addresses == 0) { + s_exporting = false; + s_status = "No addresses to export"; + return; + } + + // Collect addresses to export (copy for worker thread) + std::vector z_addrs, t_addrs; + if (s_include_z) { + for (const auto& a : state.z_addresses) z_addrs.push_back(a.address); + } + if (s_include_t) { + for (const auto& a : state.t_addresses) t_addrs.push_back(a.address); + } + std::string filename(s_filename); + + // Run all key exports on worker thread + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), z_addrs, t_addrs, filename]() -> rpc::RPCWorker::MainCb { + std::string keys; + int exported = 0; + int total = static_cast(z_addrs.size() + t_addrs.size()); + + // Header + keys = "# DragonX Wallet - Private Keys Export\n"; + keys += "# Generated: "; + std::time_t now = std::time(nullptr); + char timebuf[64]; + std::strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\n", std::localtime(&now)); + keys += timebuf; + keys += "# KEEP THIS FILE SECURE!\n\n"; + + // Export Z-addresses + if (!z_addrs.empty()) { + keys += "# === Z-Addresses (Shielded) ===\n\n"; + for (const auto& addr : z_addrs) { + try { + auto result = rpc->call("z_exportkey", {addr}); + if (result.is_string()) { + keys += "# Address: " + addr + "\n"; + keys += result.get() + "\n\n"; + } + } catch (...) {} + exported++; + } + } + + // Export T-addresses + if (!t_addrs.empty()) { + keys += "# === T-Addresses (Transparent) ===\n\n"; + for (const auto& addr : t_addrs) { + try { + auto result = rpc->call("dumpprivkey", {addr}); + if (result.is_string()) { + keys += "# Address: " + addr + "\n"; + keys += result.get() + "\n\n"; + } + } catch (...) {} + exported++; + } + } + + // Save to file (still on worker thread) + std::string configDir = util::Platform::getConfigDir(); + std::string filepath = configDir + "/" + filename; + bool writeOk = false; + { + std::ofstream file(filepath); + if (file.is_open()) { + file << keys; + file.close(); + writeOk = true; + } + } + + return [exported, total, filepath, writeOk]() { + s_exported_count = exported; + s_exporting = false; + if (writeOk) { + s_status = "Exported to: " + filepath; + Notifications::instance().success("Keys exported successfully"); + } else { + s_status = "Failed to write file"; + Notifications::instance().error("Failed to save key file"); + } + }; + }); + } + } + } + + if (s_exporting) { + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::TextDisabled("Exporting %d/%d...", s_exported_count, s_total_addresses); + } + + ImGui::SameLine(); + if (material::StyledButton("Close", ImVec2(closeBtn.width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + + // Status + if (!s_status.empty()) { + ImGui::Spacing(); + ImGui::TextWrapped("%s", s_status.c_str()); + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/export_all_keys_dialog.h b/src/ui/windows/export_all_keys_dialog.h new file mode 100644 index 0000000..7d23897 --- /dev/null +++ b/src/ui/windows/export_all_keys_dialog.h @@ -0,0 +1,33 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for exporting all wallet keys to a file + * + * Exports all z-address and t-address private keys to a text file + */ +class ExportAllKeysDialog { +public: + // Show the dialog + static void show(); + + // Render the dialog (call each frame) + static void render(App* app); + + // Check if dialog is open + static bool isOpen(); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/export_transactions_dialog.cpp b/src/ui/windows/export_transactions_dialog.cpp new file mode 100644 index 0000000..8c69777 --- /dev/null +++ b/src/ui/windows/export_transactions_dialog.cpp @@ -0,0 +1,173 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "export_transactions_dialog.h" +#include "../../app.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +// Static state +static bool s_open = false; +static char s_filename[256] = ""; +static std::string s_status; + +// Helper to escape CSV field +static std::string escapeCSV(const std::string& field) +{ + if (field.find(',') != std::string::npos || + field.find('"') != std::string::npos || + field.find('\n') != std::string::npos) { + // Escape quotes and wrap in quotes + std::string escaped; + escaped.reserve(field.size() + 4); + escaped += '"'; + for (char c : field) { + if (c == '"') escaped += "\"\""; + else escaped += c; + } + escaped += '"'; + return escaped; + } + return field; +} + +void ExportTransactionsDialog::show() +{ + s_open = true; + s_status.clear(); + + // Generate default filename with timestamp + std::time_t now = std::time(nullptr); + char timebuf[32]; + std::strftime(timebuf, sizeof(timebuf), "%Y%m%d_%H%M%S", std::localtime(&now)); + snprintf(s_filename, sizeof(s_filename), "dragonx_transactions_%s.csv", timebuf); +} + +bool ExportTransactionsDialog::isOpen() +{ + return s_open; +} + +void ExportTransactionsDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.export-transactions"); + auto exportBtn = S.button("dialogs.export-transactions", "export-button"); + auto closeBtn = S.button("dialogs.export-transactions", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Export Transactions to CSV"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Export Transactions to CSV", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + const auto& state = app->getWalletState(); + + ImGui::Text("Export %zu transactions to CSV file.", state.transactions.size()); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Filename + ImGui::Text("Output filename:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##Filename", s_filename, sizeof(s_filename)); + + ImGui::Spacing(); + ImGui::TextDisabled("File will be saved in: ~/.config/ObsidianDragon/"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Export button + if (material::StyledButton("Export", ImVec2(exportBtn.width, 0), S.resolveFont(exportBtn.font))) { + if (state.transactions.empty()) { + Notifications::instance().warning("No transactions to export"); + } else { + std::string configDir = util::Platform::getConfigDir(); + std::string filepath = configDir + "/" + s_filename; + + std::ofstream file(filepath); + if (!file.is_open()) { + s_status = "Failed to create file"; + Notifications::instance().error("Failed to create CSV file"); + } else { + // Write CSV header + file << "Date,Type,Amount,Address,TXID,Confirmations,Memo\n"; + + // Write transactions + for (const auto& tx : state.transactions) { + // Date + std::time_t t = static_cast(tx.timestamp); + char datebuf[32]; + std::strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M:%S", std::localtime(&t)); + file << datebuf << ","; + + // Type + file << escapeCSV(tx.type) << ","; + + // Amount + std::ostringstream amt; + amt << std::fixed << std::setprecision(8) << tx.amount; + file << amt.str() << ","; + + // Address + file << escapeCSV(tx.address) << ","; + + // TXID + file << escapeCSV(tx.txid) << ","; + + // Confirmations + file << tx.confirmations << ","; + + // Memo + file << escapeCSV(tx.memo) << "\n"; + } + + file.close(); + + s_status = "Exported " + std::to_string(state.transactions.size()) + + " transactions to: " + filepath; + Notifications::instance().success("Transactions exported successfully"); + } + } + } + + ImGui::SameLine(); + if (material::StyledButton("Close", ImVec2(closeBtn.width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + + // Status + if (!s_status.empty()) { + ImGui::Spacing(); + ImGui::TextWrapped("%s", s_status.c_str()); + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/export_transactions_dialog.h b/src/ui/windows/export_transactions_dialog.h new file mode 100644 index 0000000..0660851 --- /dev/null +++ b/src/ui/windows/export_transactions_dialog.h @@ -0,0 +1,31 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for exporting transactions to CSV + */ +class ExportTransactionsDialog { +public: + // Show the dialog + static void show(); + + // Render the dialog (call each frame) + static void render(App* app); + + // Check if dialog is open + static bool isOpen(); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/import_key_dialog.cpp b/src/ui/windows/import_key_dialog.cpp new file mode 100644 index 0000000..c6499c0 --- /dev/null +++ b/src/ui/windows/import_key_dialog.cpp @@ -0,0 +1,291 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "import_key_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../../util/i18n.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../material/type.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +#include +#include +#include + +namespace dragonx { +namespace ui { + +using json = nlohmann::json; + +// Static state +static bool s_open = false; +static char s_key_input[4096] = ""; +static bool s_rescan = true; +static int s_rescan_height = 0; // 0 = full rescan +static bool s_importing = false; +static std::string s_status; +static int s_total_keys = 0; +static int s_imported_keys = 0; +static int s_failed_keys = 0; + +// Helper to detect key type +static std::string detectKeyType(const std::string& key) +{ + if (key.empty()) return "unknown"; + + // Z-address spending keys start with "secret-extended-key-" or "SK" prefix patterns + if (key.substr(0, 20) == "secret-extended-key-") { + return "z-spending"; + } + + // Legacy z-addr keys (SK prefix) + if (key.length() >= 2 && key[0] == 'S' && key[1] == 'K') { + return "z-spending"; + } + + // T-address private keys (WIF format) - start with 5, K, or L for Bitcoin-derived + // DragonX/HUSH uses different prefixes + if (key.length() >= 51 && key.length() <= 52) { + char first = key[0]; + if (first == '5' || first == 'K' || first == 'L' || first == 'U') { + return "t-privkey"; + } + } + + return "unknown"; +} + +// Helper to split input into individual keys +static std::vector splitKeys(const std::string& input) +{ + std::vector keys; + std::istringstream stream(input); + std::string line; + + while (std::getline(stream, line)) { + // Trim whitespace + size_t start = line.find_first_not_of(" \t\r\n"); + size_t end = line.find_last_not_of(" \t\r\n"); + + if (start != std::string::npos && end != std::string::npos) { + std::string key = line.substr(start, end - start + 1); + if (!key.empty() && key[0] != '#') { // Skip comments + keys.push_back(key); + } + } + } + + return keys; +} + +void ImportKeyDialog::show() +{ + s_open = true; + s_key_input[0] = '\0'; + s_rescan = true; + s_rescan_height = 0; + s_importing = false; + s_status.clear(); + s_total_keys = 0; + s_imported_keys = 0; + s_failed_keys = 0; +} + +bool ImportKeyDialog::isOpen() +{ + return s_open; +} + +void ImportKeyDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.import-key"); + auto keyInput = S.input("dialogs.import-key", "key-input"); + auto rescanInput = S.input("dialogs.import-key", "rescan-height-input"); + auto importBtn = S.button("dialogs.import-key", "import-button"); + auto closeBtn = S.button("dialogs.import-key", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Import Private Key"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Import Private Key", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + // Warning + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.8f, 0.0f, 1.0f)); + ImGui::PushFont(material::Type().iconSmall()); + ImGui::Text(ICON_MD_WARNING); + ImGui::PopFont(); + ImGui::SameLine(0, 4.0f); + ImGui::TextWrapped("Warning: Never share your private keys! " + "Importing keys from untrusted sources can compromise your wallet."); + ImGui::PopStyleColor(); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Key input + ImGui::Text("Private Key(s):"); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Enter one or more private keys, one per line.\n" + "Supports both z-address and t-address keys.\n" + "Lines starting with # are treated as comments."); + } + + if (s_importing) { + ImGui::BeginDisabled(); + } + + ImGui::SetNextItemWidth(-1); + ImGui::InputTextMultiline("##KeyInput", s_key_input, sizeof(s_key_input), + ImVec2(-1, keyInput.height > 0 ? keyInput.height : 150), ImGuiInputTextFlags_AllowTabInput); + + // Paste button + if (material::StyledButton("Paste from Clipboard", ImVec2(0,0), S.resolveFont(importBtn.font))) { + const char* clipboard = ImGui::GetClipboardText(); + if (clipboard) { + strncpy(s_key_input, clipboard, sizeof(s_key_input) - 1); + } + } + + ImGui::SameLine(); + if (material::StyledButton("Clear", ImVec2(0,0), S.resolveFont(importBtn.font))) { + s_key_input[0] = '\0'; + } + + ImGui::Spacing(); + + // Rescan options + ImGui::Checkbox("Rescan blockchain after import", &s_rescan); + + if (s_rescan) { + ImGui::Indent(); + ImGui::Text("Start height:"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(rescanInput.width); + ImGui::InputInt("##RescanHeight", &s_rescan_height); + if (s_rescan_height < 0) s_rescan_height = 0; + ImGui::SameLine(); + ImGui::TextDisabled("(0 = full rescan)"); + ImGui::Unindent(); + } + + if (s_importing) { + ImGui::EndDisabled(); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Import button + if (s_importing) { + ImGui::BeginDisabled(); + } + + if (material::StyledButton("Import Key(s)", ImVec2(importBtn.width, 0), S.resolveFont(importBtn.font))) { + auto keys = splitKeys(s_key_input); + + if (keys.empty()) { + Notifications::instance().warning("No valid keys found in input"); + } else if (!app->rpc() || !app->rpc()->isConnected()) { + Notifications::instance().error("Not connected to daemon"); + } else { + s_importing = true; + s_total_keys = static_cast(keys.size()); + s_imported_keys = 0; + s_failed_keys = 0; + s_status = "Importing..."; + + // Import keys on worker thread to avoid freezing UI + bool rescan = s_rescan; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), keys, rescan]() -> rpc::RPCWorker::MainCb { + int imported = 0; + int failed = 0; + + for (const auto& key : keys) { + std::string keyType = detectKeyType(key); + + try { + if (keyType == "z-spending") { + rpc->call("z_importkey", {key, rescan ? "yes" : "no"}); + imported++; + } else if (keyType == "t-privkey") { + rpc->call("importprivkey", {key, "", rescan}); + imported++; + } else { + failed++; + } + } catch (...) { + failed++; + } + } + + return [imported, failed]() { + s_imported_keys = imported; + s_failed_keys = failed; + s_importing = false; + char buf[128]; + snprintf(buf, sizeof(buf), "Import complete: %d success, %d failed", + imported, failed); + s_status = buf; + if (imported > 0) { + Notifications::instance().success("Keys imported successfully"); + } + }; + }); + } + } + } + + if (s_importing) { + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::TextDisabled("Importing %d/%d...", s_imported_keys + s_failed_keys, s_total_keys); + } + + ImGui::SameLine(); + if (material::StyledButton("Close", ImVec2(closeBtn.width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + + // Status + if (!s_status.empty()) { + ImGui::Spacing(); + bool success = s_failed_keys == 0 && !s_importing; + ImGui::TextColored( + success ? ImVec4(0.2f, 0.8f, 0.2f, 1.0f) : ImVec4(1.0f, 0.8f, 0.0f, 1.0f), + "%s", s_status.c_str() + ); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Help text + ImGui::TextDisabled("Supported key formats:"); + ImGui::BulletText("Z-address spending keys (secret-extended-key-...)"); + ImGui::BulletText("T-address WIF private keys"); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/import_key_dialog.h b/src/ui/windows/import_key_dialog.h new file mode 100644 index 0000000..c2ae4a5 --- /dev/null +++ b/src/ui/windows/import_key_dialog.h @@ -0,0 +1,36 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for importing private keys + * + * Supports importing: + * - Z-address private keys (z_importkey) + * - T-address private keys (importprivkey) + * - Batch import (multiple keys, one per line) + */ +class ImportKeyDialog { +public: + // Show the dialog + static void show(); + + // Render the dialog (call each frame) + static void render(App* app); + + // Check if dialog is open + static bool isOpen(); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/key_export_dialog.cpp b/src/ui/windows/key_export_dialog.cpp new file mode 100644 index 0000000..f2006b4 --- /dev/null +++ b/src/ui/windows/key_export_dialog.cpp @@ -0,0 +1,247 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "key_export_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../../util/i18n.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +// Static member initialization +bool KeyExportDialog::s_open = false; +bool KeyExportDialog::s_fetching = false; +bool KeyExportDialog::s_show_key = false; +KeyExportDialog::KeyType KeyExportDialog::s_key_type = KeyExportDialog::KeyType::Private; +std::string KeyExportDialog::s_address; +std::string KeyExportDialog::s_key; +std::string KeyExportDialog::s_error; + +void KeyExportDialog::show(const std::string& address, KeyType type) +{ + s_open = true; + s_fetching = false; + s_show_key = false; + s_key_type = type; + s_address = address; + s_key.clear(); + s_error.clear(); +} + +bool KeyExportDialog::isOpen() +{ + return s_open; +} + +void KeyExportDialog::render(App* app) +{ + if (!s_open) return; + + const char* title = (s_key_type == KeyType::Private) ? + TR("export_private_key") : TR("export_viewing_key"); + + auto& S = schema::UI(); + auto win = S.window("dialogs.key-export"); + auto warningBox = S.drawElement("dialogs.key-export", "warning-box"); + auto addrInput = S.input("dialogs.key-export", "address-input"); + auto revealBtn = S.button("dialogs.key-export", "reveal-button"); + auto keyDisplay = S.drawElement("dialogs.key-export", "key-display"); + auto toggleBtn = S.button("dialogs.key-export", "toggle-button"); + auto copyBtn = S.button("dialogs.key-export", "copy-button"); + auto closeBtn = S.button("dialogs.key-export", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImGui::OpenPopup(title); + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal(title, &s_open, + ImGuiWindowFlags_NoResize, acrylicTheme.popup)) { + ImGui::Spacing(); + + // Warning section with colored background + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.6f, 0.2f, 0.2f, 0.3f)); + ImGui::BeginChild("WarningBox", ImVec2(-1, warningBox.height > 0 ? warningBox.height : 80), true); + + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), " WARNING!"); + ImGui::Spacing(); + + if (s_key_type == KeyType::Private) { + ImGui::TextWrapped(" Keep this key SECRET! Anyone with this key can spend your " + "funds. Never share it online or with untrusted parties."); + } else { + ImGui::TextWrapped(" This viewing key allows others to see your incoming transactions " + "and balance, but NOT spend your funds. Share only with trusted parties."); + } + + ImGui::EndChild(); + ImGui::PopStyleColor(); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Address display + ImGui::Text("Address:"); + + // Determine if it's a z-address (longer) or t-address + bool is_zaddr = s_address.length() > 50; + + if (is_zaddr) { + // Use multiline for z-addresses + char addr_buf[512]; + strncpy(addr_buf, s_address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##Address", addr_buf, sizeof(addr_buf), + ImVec2(-1, addrInput.height > 0 ? addrInput.height : 60), ImGuiInputTextFlags_ReadOnly); + } else { + char addr_buf[128]; + strncpy(addr_buf, s_address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##Address", addr_buf, sizeof(addr_buf), ImGuiInputTextFlags_ReadOnly); + } + + ImGui::Spacing(); + + // Key display section + const char* key_label = (s_key_type == KeyType::Private) ? "Private Key:" : "Viewing Key:"; + ImGui::Text("%s", key_label); + + if (s_fetching) { + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Fetching key from wallet..."); + } else if (!s_error.empty()) { + ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "Error: %s", s_error.c_str()); + } else if (s_key.empty()) { + // Show button to fetch key + if (material::StyledButton("Reveal Key", ImVec2(revealBtn.width, 0), S.resolveFont(revealBtn.font))) { + s_fetching = true; + + // Check if z-address or t-address + bool is_zaddress = (s_address.length() > 50 || s_address[0] == 'z'); + + if (s_key_type == KeyType::Private) { + // Export private key + std::string addr = s_address; + std::string method = is_zaddress ? "z_exportkey" : "dumpprivkey"; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), addr, method]() -> rpc::RPCWorker::MainCb { + std::string key; + std::string error; + try { + auto result = rpc->call(method, {addr}); + key = result.get(); + } catch (const std::exception& e) { + error = e.what(); + } + return [key, error]() { + if (error.empty()) { + s_key = key; + s_show_key = false; // Don't show by default + } else { + s_error = error; + } + s_fetching = false; + }; + }); + } + } else { + // Export viewing key (only for z-addresses) + if (is_zaddress) { + std::string addr = s_address; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), addr]() -> rpc::RPCWorker::MainCb { + std::string key; + std::string error; + try { + auto result = rpc->call("z_exportviewingkey", {addr}); + key = result.get(); + } catch (const std::exception& e) { + error = e.what(); + } + return [key, error]() { + if (error.empty()) { + s_key = key; + s_show_key = true; // Viewing keys are less sensitive + } else { + s_error = error; + } + s_fetching = false; + }; + }); + } + } else { + s_error = "Viewing keys are only available for shielded (z) addresses"; + s_fetching = false; + } + } + } + ImGui::SameLine(); + ImGui::TextDisabled("Click to retrieve the key from your wallet"); + } else { + // Key has been fetched - display it + + if (s_show_key) { + // Show the actual key + char key_buf[1024]; + strncpy(key_buf, s_key.c_str(), sizeof(key_buf) - 1); + key_buf[sizeof(key_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##Key", key_buf, sizeof(key_buf), + ImVec2(-1, keyDisplay.height > 0 ? keyDisplay.height : 80), ImGuiInputTextFlags_ReadOnly); + } else { + // Show masked + std::string masked(s_key.length(), '*'); + char masked_buf[1024]; + strncpy(masked_buf, masked.c_str(), sizeof(masked_buf) - 1); + masked_buf[sizeof(masked_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##Key", masked_buf, sizeof(masked_buf), + ImVec2(-1, keyDisplay.height > 0 ? keyDisplay.height : 80), ImGuiInputTextFlags_ReadOnly); + } + + // Show/Hide and Copy buttons + ImGui::Spacing(); + + if (material::StyledButton(s_show_key ? "Hide" : "Show", ImVec2(toggleBtn.width, 0), S.resolveFont(toggleBtn.font))) { + s_show_key = !s_show_key; + } + + ImGui::SameLine(); + + if (material::StyledButton(TR("copy_to_clipboard"), ImVec2(copyBtn.width, 0), S.resolveFont(copyBtn.font))) { + ImGui::SetClipboardText(s_key.c_str()); + // Could add a notification here + } + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Close button + float button_width = closeBtn.width; + float avail_width = ImGui::GetContentRegionAvail().x; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (avail_width - button_width) / 2.0f); + + if (material::StyledButton("Close", ImVec2(button_width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + // Clear sensitive data + s_key.clear(); + s_show_key = false; + } + + effects::ImGuiAcrylic::EndAcrylicPopup(); + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/key_export_dialog.h b/src/ui/windows/key_export_dialog.h new file mode 100644 index 0000000..8c148f0 --- /dev/null +++ b/src/ui/windows/key_export_dialog.h @@ -0,0 +1,57 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for exporting private/viewing keys + * + * Displays the private or viewing key for a given address with + * security warnings and copy functionality. + */ +class KeyExportDialog { +public: + enum class KeyType { + Private, + Viewing + }; + + /** + * @brief Show the key export dialog for an address + * @param address The address to export key for + * @param type The type of key to export + */ + static void show(const std::string& address, KeyType type); + + /** + * @brief Render the dialog (call every frame) + * @param app Pointer to app instance for RPC calls + */ + static void render(App* app); + + /** + * @brief Check if dialog is currently open + */ + static bool isOpen(); + +private: + static bool s_open; + static bool s_fetching; + static bool s_show_key; + static KeyType s_key_type; + static std::string s_address; + static std::string s_key; + static std::string s_error; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/main_window.cpp b/src/ui/windows/main_window.cpp new file mode 100644 index 0000000..07e8061 --- /dev/null +++ b/src/ui/windows/main_window.cpp @@ -0,0 +1,20 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "main_window.h" +#include "../../app.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +void RenderMainWindow(App* app) +{ + // Main window rendering is handled by App::render() + // This file is for any shared window utilities + (void)app; +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/main_window.h b/src/ui/windows/main_window.h new file mode 100644 index 0000000..687ade3 --- /dev/null +++ b/src/ui/windows/main_window.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the main window content + * Called from App::render(), manages the overall layout + */ +void RenderMainWindow(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/market_tab.cpp b/src/ui/windows/market_tab.cpp new file mode 100644 index 0000000..4835d93 --- /dev/null +++ b/src/ui/windows/market_tab.cpp @@ -0,0 +1,819 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "market_tab.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../data/wallet_state.h" +#include "../../config/settings.h" +#include "../../data/exchange_info.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../material/typography.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "../../util/platform.h" +#include "../layout.h" +#include "imgui.h" + +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ---- Market tab persistent state ---- +static std::vector s_price_history; +static std::vector s_time_history; +static bool s_history_initialized = false; +static double s_last_refresh_time = 0.0; + +// Exchange / pair selection +static int s_exchange_idx = 0; +static int s_pair_idx = 0; +static float s_pair_scroll = 0.0f; +static float s_pair_scroll_target = 0.0f; +static bool s_pair_dragging = false; +static float s_pair_drag_start_x = 0.0f; +static float s_pair_drag_start_scroll = 0.0f; +static bool s_market_state_loaded = false; + +// Helper: load selected exchange/pair from settings +static void LoadMarketState(config::Settings* settings) +{ + if (s_market_state_loaded || !settings) return; + s_market_state_loaded = true; + + const auto& registry = data::getExchangeRegistry(); + std::string savedExchange = settings->getSelectedExchange(); + std::string savedPair = settings->getSelectedPair(); + + for (int ei = 0; ei < (int)registry.size(); ei++) { + if (registry[ei].name == savedExchange) { + s_exchange_idx = ei; + for (int pi = 0; pi < (int)registry[ei].pairs.size(); pi++) { + if (registry[ei].pairs[pi].displayName == savedPair) { + s_pair_idx = pi; + break; + } + } + break; + } + } +} + +// Helper: format compact currency +static std::string FormatCompactUSD(double val) +{ + char buf[64]; + if (val >= 1e9) snprintf(buf, sizeof(buf), "$%.2fB", val / 1e9); + else if (val >= 1e6) snprintf(buf, sizeof(buf), "$%.2fM", val / 1e6); + else if (val >= 1e3) snprintf(buf, sizeof(buf), "$%.2fK", val / 1e3); + else snprintf(buf, sizeof(buf), "$%.2f", val); + return std::string(buf); +} + +// Helper: format price to sensible precision +static std::string FormatPrice(double price) +{ + char buf[64]; + if (price >= 0.01) snprintf(buf, sizeof(buf), "$%.4f", price); + else if (price >= 0.0001) snprintf(buf, sizeof(buf), "$%.6f", price); + else snprintf(buf, sizeof(buf), "$%.8f", price); + return std::string(buf); +} + +void RenderMarketTab(App* app) +{ + auto& S = schema::UI(); + auto summaryPanel = S.table("tabs.market", "summary-panel"); + auto btcPriceLbl = S.label("tabs.market", "btc-price-label"); + auto change24hLbl = S.label("tabs.market", "change-24h-label"); + auto volumeLbl = S.label("tabs.market", "volume-label"); + auto volumeValLbl = S.label("tabs.market", "volume-value-label"); + auto mktCapLbl = S.label("tabs.market", "market-cap-label"); + auto mktCapValLbl = S.label("tabs.market", "market-cap-value-label"); + auto chartElem = S.drawElement("tabs.market", "chart"); + auto portfolioValLbl = S.label("tabs.market", "portfolio-value-label"); + auto portfolioBtcLbl = S.label("tabs.market", "portfolio-btc-label"); + const auto& state = app->getWalletState(); + const auto& market = state.market; + + // Load persisted exchange/pair on first frame + LoadMarketState(app->settings()); + + // Exchange registry + const auto& registry = data::getExchangeRegistry(); + if (s_exchange_idx >= (int)registry.size()) s_exchange_idx = 0; + const auto& currentExchange = registry[s_exchange_idx]; + if (s_pair_idx >= (int)currentExchange.pairs.size()) s_pair_idx = 0; + + // Non-scrolling container — content resizes to fit available height + ImVec2 marketAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##MarketScroll", marketAvail, false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + + // Responsive: scale factors per frame + float availWidth = ImGui::GetContentRegionAvail().x; + float hs = Layout::hScale(availWidth); + float vs = Layout::vScale(marketAvail.y); + float pad = Layout::cardInnerPadding(); + float gap = Layout::cardGap(); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = Layout::glassRounding(); + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* h4 = Type().h4(); + ImFont* body2 = Type().body2(); + + char buf[128]; + + // ================================================================ + // Proportional section budget — all content fits without scrolling + // ================================================================ + float mkSHdr = ovFont->LegacySize + Layout::spacingXs() + + ImGui::GetStyle().ItemSpacing.y * 2.0f; + float mkGapOver = gap + ImGui::GetStyle().ItemSpacing.y; + float mkOverhead = 3.0f * (mkSHdr + mkGapOver) + 2.0f * mkGapOver; + float pairBarH = S.drawElement("tabs.market", "pair-bar-height").height; + float mkCardBudget = std::max(200.0f, marketAvail.y - mkOverhead); + + Layout::SectionBudget mb(mkCardBudget); + float statsMarketBudH = mb.allocate(0.14f, S.drawElement("tabs.market", "stats-card-min-height").size); + float portfolioBudgetH = mb.allocate(0.18f, 50.0f); + + // ================================================================ + // PRICE HERO — Large glass card with price + change badge + // ================================================================ + { + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = std::max(S.drawElement("tabs.market", "hero-card-min-height").size, S.drawElement("tabs.market", "hero-card-height").size * vs); + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // Accent stripe — clipped to card rounded corners + { + float sw = S.drawElement("tabs.market", "accent-stripe-width").size; + dl->PushClipRect(cardMin, ImVec2(cardMin.x + sw, cardMax.y), true); + dl->AddRectFilled(cardMin, cardMax, WithAlpha(S.resolveColor("var(--accent-market)", Success()), 200), + glassSpec.rounding, ImDrawFlags_RoundCornersLeft); + dl->PopClipRect(); + } + + float cx = cardMin.x + Layout::spacingLg(); + float cy = cardMin.y + Layout::spacingLg(); + + if (market.price_usd > 0) { + // Large price with text shadow + std::string priceStr = FormatPrice(market.price_usd); + ImU32 priceCol = Success(); + DrawTextShadow(dl, h4, h4->LegacySize, ImVec2(cx, cy), priceCol, priceStr.c_str()); + + // BTC price beside it + float priceW = h4->CalcTextSizeA(h4->LegacySize, FLT_MAX, 0, priceStr.c_str()).x; + snprintf(buf, sizeof(buf), "%.10f BTC", market.price_btc); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx + priceW + Layout::spacingXl(), cy + (h4->LegacySize - capFont->LegacySize)), + OnSurfaceMedium(), buf); + + // 24h change badge + float badgeY = cy + h4->LegacySize + 8; + ImU32 chgCol = market.change_24h >= 0 ? Success() : Error(); + snprintf(buf, sizeof(buf), "%s%.2f%%", market.change_24h >= 0 ? "+" : "", market.change_24h); + + ImVec2 txtSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + float badgePad = Layout::spacingSm() + Layout::spacingXs(); + ImVec2 bMin(cx, badgeY); + ImVec2 bMax(cx + txtSz.x + badgePad * 2, badgeY + txtSz.y + badgePad); + ImU32 badgeBg = market.change_24h >= 0 ? WithAlpha(Success(), 30) : WithAlpha(Error(), 30); + dl->AddRectFilled(bMin, bMax, badgeBg, 4.0f); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + badgePad, badgeY + badgePad * 0.5f), chgCol, buf); + + // "24h" label after badge + dl->AddText(capFont, capFont->LegacySize, + ImVec2(bMax.x + 6, badgeY + badgePad * 0.5f), OnSurfaceDisabled(), "24h"); + } else { + DrawTextShadow(dl, sub1, sub1->LegacySize, ImVec2(cx, cy + 10), OnSurfaceDisabled(), "Price data unavailable"); + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // STATS — Three glass cards (Price | Volume | Market Cap) + // ================================================================ + { + float cardW = (availWidth - 2 * gap) / 3.0f; + float cardH = std::min(StatCardHeight(vs), statsMarketBudH); + ImVec2 origin = ImGui::GetCursorScreenPos(); + + struct StatInfo { const char* label; std::string value; ImU32 col; ImU32 accent; }; + StatInfo cards[3] = { + {"PRICE", market.price_usd > 0 ? FormatPrice(market.price_usd) : "N/A", + OnSurface(), WithAlpha(Success(), 200)}, + {"24H VOLUME", FormatCompactUSD(market.volume_24h), + OnSurface(), WithAlpha(Secondary(), 200)}, + {"MARKET CAP", FormatCompactUSD(market.market_cap), + OnSurface(), WithAlpha(Warning(), 200)}, + }; + + for (int i = 0; i < 3; i++) { + float xOff = i * (cardW + gap); + ImVec2 cMin(origin.x + xOff, origin.y); + ImVec2 cMax(cMin.x + cardW, cMin.y + cardH); + + StatCardSpec sc; + sc.overline = cards[i].label; + sc.value = cards[i].value.c_str(); + sc.valueCol = cards[i].col; + sc.accentCol = cards[i].accent; + sc.centered = true; + DrawStatCard(dl, cMin, cMax, sc, glassSpec); + } + + ImGui::Dummy(ImVec2(availWidth, cardH)); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // PRICE CHART — Custom drawn inside glass panel (matches app design) + // ================================================================ + { + // Initialize history with simulated data if not set + if (!s_history_initialized && market.price_usd > 0) { + s_price_history.clear(); + s_time_history.clear(); + double base = market.price_usd; + for (int i = 0; i < 24; i++) { + double variance = ((rand() % 1000) - 500) / 10000.0 * base; + s_price_history.push_back(base + variance); + s_time_history.push_back(static_cast(i)); + } + s_history_initialized = true; + } + + // Chart height from schema + float chartH = std::max(60.0f, chartElem.height * vs); + ImVec2 chartMin = ImGui::GetCursorScreenPos(); + ImVec2 chartMax(chartMin.x + availWidth, chartMin.y + chartH); + DrawGlassPanel(dl, chartMin, chartMax, glassSpec); + + if (!s_price_history.empty() && s_price_history.size() >= 2) { + float chartPad = pad; + float labelPadLeft = std::max(S.drawElement("tabs.market", "chart-y-axis-min-padding").size, S.drawElement("tabs.market", "chart-y-axis-padding").size * hs); + float labelPadBottom = Layout::spacingXl(); + + float plotLeft = chartMin.x + labelPadLeft; + float plotRight = chartMax.x - chartPad; + float plotTop = chartMin.y + chartPad; + float plotBottom = chartMax.y - labelPadBottom; + float plotW = plotRight - plotLeft; + float plotH = plotBottom - plotTop; + + // Compute Y range with padding + double yMin = *std::min_element(s_price_history.begin(), s_price_history.end()); + double yMax = *std::max_element(s_price_history.begin(), s_price_history.end()); + if (yMax <= yMin) { yMax = yMin + 1e-8; } + double yRange = yMax - yMin; + double yPadding = yRange * 0.12; + yMin -= yPadding; + yMax += yPadding; + + // Horizontal grid lines (4 lines) + for (int g = 0; g <= 4; g++) { + float gy = plotTop + plotH * (float)g / 4.0f; + dl->AddLine(ImVec2(plotLeft, gy), ImVec2(plotRight, gy), + IM_COL32(255, 255, 255, 12), 1.0f); + double labelVal = yMax - (yMax - yMin) * (double)g / 4.0; + snprintf(buf, sizeof(buf), "$%.6f", labelVal); + ImVec2 labelSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(plotLeft - labelSz.x - 6, gy - labelSz.y * 0.5f), + OnSurfaceDisabled(), buf); + } + + // Build points + size_t n = s_price_history.size(); + std::vector points(n); + + ImU32 lineCol = market.change_24h >= 0 + ? WithAlpha(Success(), 220) : WithAlpha(Error(), 220); + ImU32 fillCol = market.change_24h >= 0 + ? WithAlpha(Success(), 25) : WithAlpha(Error(), 25); + ImU32 dotCol = market.change_24h >= 0 + ? Success() : Error(); + + for (size_t i = 0; i < n; i++) { + float t = (n > 1) ? (float)i / (float)(n - 1) : 0.0f; + float x = plotLeft + t * plotW; + float y = plotBottom - (float)((s_price_history[i] - yMin) / (yMax - yMin)) * plotH; + points[i] = ImVec2(x, y); + } + + // Fill under curve + for (size_t i = 0; i + 1 < n; i++) { + ImVec2 quad[4] = { + points[i], + points[i + 1], + ImVec2(points[i + 1].x, plotBottom), + ImVec2(points[i].x, plotBottom) + }; + dl->AddConvexPolyFilled(quad, 4, fillCol); + } + + // Line + dl->AddPolyline(points.data(), (int)points.size(), lineCol, ImDrawFlags_None, S.drawElement("tabs.market", "chart-line-thickness").size); + + // Dots + float dotR = std::max(S.drawElement("tabs.market", "chart-dot-min-radius").size, S.drawElement("tabs.market", "chart-dot-radius").size * hs); + for (size_t i = 0; i < n; i++) { + dl->AddCircleFilled(points[i], dotR, dotCol); + } + + // X-axis labels + const int xlabels[] = {0, 6, 12, 18, 23}; + const char* xlabelText[] = {"24h", "18h", "12h", "6h", "Now"}; + for (int xi = 0; xi < 5; xi++) { + int idx = xlabels[xi]; + float t = (float)idx / (float)(n - 1); + float x = plotLeft + t * plotW; + ImVec2 lblSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, xlabelText[xi]); + float lx = x - lblSz.x * 0.5f; + if (lx < plotLeft) lx = plotLeft; + if (lx + lblSz.x > plotRight) lx = plotRight - lblSz.x; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(lx, plotBottom + 2), OnSurfaceDisabled(), xlabelText[xi]); + } + + // Hover crosshair + tooltip + ImVec2 mousePos = ImGui::GetIO().MousePos; + if (mousePos.x >= plotLeft && mousePos.x <= plotRight && + mousePos.y >= plotTop && mousePos.y <= plotBottom + labelPadBottom) + { + float mx = mousePos.x - plotLeft; + float closest_t = mx / plotW; + int idx = (int)(closest_t * (n - 1) + 0.5f); + if (idx < 0) idx = 0; + if (idx >= (int)n) idx = (int)n - 1; + + float px = points[idx].x; + float py = points[idx].y; + + dl->AddLine(ImVec2(px, plotTop), ImVec2(px, plotBottom), + IM_COL32(255, 255, 255, 40), 1.0f); + dl->AddLine(ImVec2(plotLeft, py), ImVec2(plotRight, py), + IM_COL32(255, 255, 255, 40), 1.0f); + + float hoverDotR = std::max(S.drawElement("tabs.market", "chart-hover-dot-min-radius").size, S.drawElement("tabs.market", "chart-hover-dot-radius").size * hs); + float hoverRingR = std::max(S.drawElement("tabs.market", "chart-hover-ring-min-radius").size, S.drawElement("tabs.market", "chart-hover-ring-radius").size * hs); + dl->AddCircleFilled(ImVec2(px, py), hoverDotR, dotCol); + dl->AddCircle(ImVec2(px, py), hoverRingR, IM_COL32(255, 255, 255, 80), 0, 1.5f); + + snprintf(buf, sizeof(buf), "%dh ago: %s", + 24 - idx, FormatPrice(s_price_history[idx]).c_str()); + ImVec2 tipSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + float tipPad = Layout::spacingSm() + Layout::spacingXs(); + float tipX = px + 10; + float tipY = py - tipSz.y - tipPad * 2 - 4; + if (tipX + tipSz.x + tipPad * 2 > plotRight) + tipX = px - tipSz.x - tipPad * 2 - 10; + if (tipY < plotTop) tipY = py + 10; + + ImVec2 tipMin(tipX, tipY); + ImVec2 tipMax(tipX + tipSz.x + tipPad * 2, tipY + tipSz.y + tipPad * 2); + dl->AddRectFilled(tipMin, tipMax, IM_COL32(20, 20, 30, 230), 4.0f); + dl->AddRect(tipMin, tipMax, IM_COL32(255, 255, 255, 30), 4.0f, 0, 1.0f); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(tipX + tipPad, tipY + tipPad), dotCol, buf); + } + } else { + const char* msg = "No price history available"; + ImVec2 ts = sub1->CalcTextSizeA(sub1->LegacySize, FLT_MAX, 0, msg); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(chartMin.x + (availWidth - ts.x) * 0.5f, chartMin.y + chartH * 0.45f), + OnSurfaceDisabled(), msg); + } + + // --- Refresh button + timestamp pinned in chart top-right --- + { + float iconBtnSz = capFont->LegacySize + 8.0f; + float refreshX = chartMax.x - pad; + float refreshY = chartMin.y + pad * 0.5f; + + // Draw refresh icon button + ImVec2 btnMin(refreshX - iconBtnSz, refreshY); + ImVec2 btnMax(refreshX, refreshY + iconBtnSz); + bool refreshHov = material::IsRectHovered(btnMin, btnMax); + if (refreshHov) { + dl->AddRectFilled(btnMin, btnMax, IM_COL32(255, 255, 255, 20), 4.0f); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + ImFont* iconSmall = material::Typography::instance().iconSmall(); + ImVec2 iconSz = iconSmall->CalcTextSizeA(iconSmall->LegacySize, FLT_MAX, 0, ICON_MD_REFRESH); + dl->AddText(iconSmall, iconSmall->LegacySize, + ImVec2(btnMin.x + (iconBtnSz - iconSz.x) * 0.5f, btnMin.y + (iconBtnSz - iconSz.y) * 0.5f), + refreshHov ? OnSurface() : OnSurfaceMedium(), ICON_MD_REFRESH); + + ImGui::SetCursorScreenPos(btnMin); + if (ImGui::InvisibleButton("##RefreshMarket", ImVec2(iconBtnSz, iconBtnSz))) { + app->refreshMarketData(); + s_history_initialized = false; + s_last_refresh_time = ImGui::GetTime(); + } + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Refresh price data"); + + // Timestamp text to the left of refresh button + if (s_last_refresh_time > 0.0) { + double elapsed = ImGui::GetTime() - s_last_refresh_time; + if (elapsed < 60.0) + snprintf(buf, sizeof(buf), "%.0fs ago", elapsed); + else if (elapsed < 3600.0) + snprintf(buf, sizeof(buf), "%.0fm ago", elapsed / 60.0); + else + snprintf(buf, sizeof(buf), "%.1fh ago", elapsed / 3600.0); + ImVec2 tsSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(btnMin.x - tsSz.x - 6, btnMin.y + (iconBtnSz - tsSz.y) * 0.5f), + OnSurfaceDisabled(), buf); + } + } + + ImGui::SetCursorScreenPos(ImVec2(chartMin.x, chartMin.y + chartH)); + ImGui::Dummy(ImVec2(availWidth, 0)); + } + + // ================================================================ + // EXCHANGE SELECTOR — Combo dropdown + pair name + trade link + // ================================================================ + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.market", "exchange-top-gap").size)); + { + float comboW = S.drawElement("tabs.market", "exchange-combo-width").size; + + ImGui::PushFont(body2); + ImGui::PushItemWidth(comboW); + if (ImGui::BeginCombo("##ExchangeCombo", currentExchange.name.c_str())) { + for (int i = 0; i < (int)registry.size(); i++) { + bool selected = (i == s_exchange_idx); + if (ImGui::Selectable(registry[i].name.c_str(), selected)) { + if (i != s_exchange_idx) { + s_exchange_idx = i; + s_pair_idx = 0; + s_pair_scroll = 0.0f; + s_pair_scroll_target = 0.0f; + s_history_initialized = false; + app->settings()->setSelectedExchange(registry[i].name); + if (!registry[i].pairs.empty()) + app->settings()->setSelectedPair(registry[i].pairs[0].displayName); + app->settings()->save(); + app->refreshMarketData(); + } + } + if (selected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + ImGui::PopItemWidth(); + + // Show current pair name beside combo + if (!currentExchange.pairs.empty()) { + ImGui::SameLine(0, Layout::spacingLg()); + Type().textColored(TypeStyle::Subtitle1, OnSurface(), + currentExchange.pairs[s_pair_idx].displayName.c_str()); + + // "Open on exchange" button + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::PushFont(material::Typography::instance().iconSmall()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 4)); + snprintf(buf, sizeof(buf), ICON_MD_OPEN_IN_NEW "##TradeLink"); + if (ImGui::Button(buf)) { + util::Platform::openUrl(currentExchange.pairs[s_pair_idx].tradeUrl); + } + ImGui::PopStyleVar(); + ImGui::PopFont(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Open on %s", currentExchange.name.c_str()); + } + + // Attribution + ImGui::SameLine(0, Layout::spacingLg()); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), "Price data from CoinGecko API"); + + if (!market.last_updated.empty()) { + ImGui::SameLine(0, 12); + snprintf(buf, sizeof(buf), " \xc2\xb7 Updated %s", market.last_updated.c_str()); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + + ImGui::PopFont(); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // PAIR BAR — Horizontally scrolling chip selector (always visible) + // ================================================================ + { + float chipH = S.drawElement("tabs.market", "pair-chip-height").height; + float chipR = S.drawElement("tabs.market", "pair-chip-radius").radius; + float chipSpacing = S.drawElement("tabs.market", "pair-chip-spacing").size; + float fadeW = S.drawElement("tabs.market", "pair-bar-fade-width").size; + float arrowSz = S.drawElement("tabs.market", "pair-bar-arrow-size").size; + + ImVec2 barOrigin = ImGui::GetCursorScreenPos(); + float barW = availWidth; + float barH = pairBarH; + + // Compute total content width of all chips + float totalChipW = 0.0f; + std::vector chipWidths; + for (const auto& pair : currentExchange.pairs) { + float tw = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, pair.displayName.c_str()).x; + float cw = tw + Layout::spacingLg() * 2.0f; + chipWidths.push_back(cw); + totalChipW += cw + chipSpacing; + } + totalChipW -= chipSpacing; // no trailing spacing + + float scrollableW = barW - arrowSz * 2.0f - Layout::spacingSm() * 2.0f; + float maxScroll = std::max(0.0f, totalChipW - scrollableW); + + // Smooth scroll lerp + s_pair_scroll += (s_pair_scroll_target - s_pair_scroll) * 0.15f; + if (std::abs(s_pair_scroll - s_pair_scroll_target) < 0.5f) + s_pair_scroll = s_pair_scroll_target; + + // Clamp + s_pair_scroll_target = std::clamp(s_pair_scroll_target, 0.0f, maxScroll); + s_pair_scroll = std::clamp(s_pair_scroll, 0.0f, maxScroll); + + // Left arrow button + float arrowY = barOrigin.y + (barH - arrowSz) * 0.5f; + bool canScrollLeft = s_pair_scroll_target > 0.01f; + ImGui::SetCursorScreenPos(ImVec2(barOrigin.x, arrowY)); + ImGui::BeginDisabled(!canScrollLeft); + ImGui::PushFont(material::Typography::instance().iconSmall()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + if (ImGui::Button(ICON_MD_CHEVRON_LEFT "##PairLeft", ImVec2(arrowSz, arrowSz))) { + // Scroll left by average chip width + float avgChipW = totalChipW / currentExchange.pairs.size(); + s_pair_scroll_target -= avgChipW + chipSpacing; + if (s_pair_scroll_target < 0) s_pair_scroll_target = 0; + } + ImGui::PopStyleVar(); + ImGui::PopFont(); + ImGui::EndDisabled(); + + // Chip area with clipping + float chipAreaLeft = barOrigin.x + arrowSz + Layout::spacingSm(); + float chipAreaRight = barOrigin.x + barW - arrowSz - Layout::spacingSm(); + float chipY = barOrigin.y + (barH - chipH) * 0.5f; + + dl->PushClipRect(ImVec2(chipAreaLeft, barOrigin.y), + ImVec2(chipAreaRight, barOrigin.y + barH), true); + + // Render chips + float cx = chipAreaLeft - s_pair_scroll; + bool anyClicked = false; + for (int i = 0; i < (int)currentExchange.pairs.size(); i++) { + float cw = chipWidths[i]; + ImVec2 cMin(cx, chipY); + ImVec2 cMax(cx + cw, chipY + chipH); + + bool selected = (i == s_pair_idx); + ImU32 chipBg = selected ? WithAlpha(Primary(), 200) : WithAlpha(OnSurface(), 20); + ImU32 chipBorder = selected ? Primary() : WithAlpha(OnSurface(), 40); + ImU32 chipText = selected ? IM_COL32(255, 255, 255, 255) : OnSurface(); + + dl->AddRectFilled(cMin, cMax, chipBg, chipR); + dl->AddRect(cMin, cMax, chipBorder, chipR, 0, 1.0f); + + ImVec2 textSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, + currentExchange.pairs[i].displayName.c_str()); + float textX = cx + (cw - textSz.x) * 0.5f; + float textY = chipY + (chipH - textSz.y) * 0.5f; + dl->AddText(capFont, capFont->LegacySize, ImVec2(textX, textY), chipText, + currentExchange.pairs[i].displayName.c_str()); + + // Click detection via invisible button + ImGui::SetCursorScreenPos(cMin); + snprintf(buf, sizeof(buf), "##PairChip%d", i); + if (ImGui::InvisibleButton(buf, ImVec2(cw, chipH))) { + if (!s_pair_dragging || std::abs(ImGui::GetIO().MousePos.x - s_pair_drag_start_x) < 4.0f) { + s_pair_idx = i; + anyClicked = true; + app->settings()->setSelectedPair(currentExchange.pairs[i].displayName); + app->settings()->save(); + s_history_initialized = false; + app->refreshMarketData(); + } + } + + cx += cw + chipSpacing; + } + + dl->PopClipRect(); + + // Fade overlays on edges + ImU32 bgCol = IM_COL32(0, 0, 0, 0); + ImU32 surfaceCol = Surface(); + if (s_pair_scroll > 1.0f) { + // Left fade + dl->AddRectFilledMultiColor( + ImVec2(chipAreaLeft, barOrigin.y), ImVec2(chipAreaLeft + fadeW, barOrigin.y + barH), + surfaceCol, bgCol, bgCol, surfaceCol); + } + if (s_pair_scroll < maxScroll - 1.0f) { + // Right fade + dl->AddRectFilledMultiColor( + ImVec2(chipAreaRight - fadeW, barOrigin.y), ImVec2(chipAreaRight, barOrigin.y + barH), + bgCol, surfaceCol, surfaceCol, bgCol); + } + + // Right arrow button + bool canScrollRight = s_pair_scroll_target < maxScroll - 0.01f; + ImGui::SetCursorScreenPos(ImVec2(barOrigin.x + barW - arrowSz, arrowY)); + ImGui::BeginDisabled(!canScrollRight); + ImGui::PushFont(material::Typography::instance().iconSmall()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + if (ImGui::Button(ICON_MD_CHEVRON_RIGHT "##PairRight", ImVec2(arrowSz, arrowSz))) { + float avgChipW = totalChipW / currentExchange.pairs.size(); + s_pair_scroll_target += avgChipW + chipSpacing; + if (s_pair_scroll_target > maxScroll) s_pair_scroll_target = maxScroll; + } + ImGui::PopStyleVar(); + ImGui::PopFont(); + ImGui::EndDisabled(); + + // Mouse wheel horizontal scroll when hovering pair bar + ImVec2 mPos = ImGui::GetIO().MousePos; + if (mPos.x >= barOrigin.x && mPos.x <= barOrigin.x + barW && + mPos.y >= barOrigin.y && mPos.y <= barOrigin.y + barH) { + float wheel = ImGui::GetIO().MouseWheel; + if (wheel != 0.0f) { + float avgChipW = totalChipW / currentExchange.pairs.size(); + s_pair_scroll_target -= wheel * (avgChipW + chipSpacing); + s_pair_scroll_target = std::clamp(s_pair_scroll_target, 0.0f, maxScroll); + } + } + + // Mouse drag scrolling + if (ImGui::IsMouseClicked(0) && mPos.x >= chipAreaLeft && mPos.x <= chipAreaRight && + mPos.y >= barOrigin.y && mPos.y <= barOrigin.y + barH) { + s_pair_dragging = true; + s_pair_drag_start_x = mPos.x; + s_pair_drag_start_scroll = s_pair_scroll_target; + } + if (s_pair_dragging) { + if (ImGui::IsMouseDown(0)) { + float dx = mPos.x - s_pair_drag_start_x; + s_pair_scroll_target = std::clamp(s_pair_drag_start_scroll - dx, 0.0f, maxScroll); + } else { + s_pair_dragging = false; + } + } + + // Arrow key navigation + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)) { + if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow) && s_pair_idx > 0) { + s_pair_idx--; + app->settings()->setSelectedPair(currentExchange.pairs[s_pair_idx].displayName); + app->settings()->save(); + s_history_initialized = false; + app->refreshMarketData(); + anyClicked = true; + } + if (ImGui::IsKeyPressed(ImGuiKey_RightArrow) && s_pair_idx < (int)currentExchange.pairs.size() - 1) { + s_pair_idx++; + app->settings()->setSelectedPair(currentExchange.pairs[s_pair_idx].displayName); + app->settings()->save(); + s_history_initialized = false; + app->refreshMarketData(); + anyClicked = true; + } + } + + // Auto-scroll to keep selected chip visible + if (anyClicked) { + float chipLeft = 0; + for (int i = 0; i < s_pair_idx; i++) + chipLeft += chipWidths[i] + chipSpacing; + float chipRight = chipLeft + chipWidths[s_pair_idx]; + if (chipLeft < s_pair_scroll_target) + s_pair_scroll_target = chipLeft - chipSpacing; + if (chipRight > s_pair_scroll_target + scrollableW) + s_pair_scroll_target = chipRight - scrollableW + chipSpacing; + s_pair_scroll_target = std::clamp(s_pair_scroll_target, 0.0f, maxScroll); + } + + // Advance cursor past the bar + ImGui::SetCursorScreenPos(ImVec2(barOrigin.x, barOrigin.y + barH)); + ImGui::Dummy(ImVec2(availWidth, 0)); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // PORTFOLIO — Glass card with balance breakdown + // ================================================================ + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "PORTFOLIO"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + double total_balance = state.totalBalance; + double private_balance = state.privateBalance; + double transparent_balance = state.transparentBalance; + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + float cardH = std::max(50.0f, portfolioBudgetH); + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // Accent stripe + { + float sw = S.drawElement("tabs.market", "accent-stripe-width").size; + dl->PushClipRect(cardMin, ImVec2(cardMin.x + sw, cardMax.y), true); + dl->AddRectFilled(cardMin, cardMax, WithAlpha(S.resolveColor("var(--accent-portfolio)", Secondary()), 200), + glassSpec.rounding, ImDrawFlags_RoundCornersLeft); + dl->PopClipRect(); + } + + float cx = cardMin.x + Layout::spacingLg(); + float cy = cardMin.y + Layout::spacingLg(); + + if (market.price_usd > 0) { + double portfolio_usd = total_balance * market.price_usd; + if (portfolio_usd >= 1.0) + snprintf(buf, sizeof(buf), "$%.2f USD", portfolio_usd); + else + snprintf(buf, sizeof(buf), "$%.6f USD", portfolio_usd); + DrawTextShadow(dl, sub1, sub1->LegacySize, ImVec2(cx, cy), Success(), buf); + + double portfolio_btc = total_balance * market.price_btc; + snprintf(buf, sizeof(buf), "%.10f BTC", portfolio_btc); + float valW = sub1->CalcTextSizeA(sub1->LegacySize, FLT_MAX, 0, buf).x; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cardMax.x - valW - pad, cy + 2), OnSurfaceMedium(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), OnSurfaceDisabled(), "No price data"); + } + + cy += sub1->LegacySize + 8; + + snprintf(buf, sizeof(buf), "%.8f %s", total_balance, DRAGONX_TICKER); + dl->AddText(body2, body2->LegacySize, ImVec2(cx, cy), OnSurface(), buf); + + snprintf(buf, sizeof(buf), "Z: %.4f | T: %.4f", private_balance, transparent_balance); + float brkW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf).x; + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cardMax.x - brkW - pad, cy + 2), OnSurfaceDisabled(), buf); + + cy += body2->LegacySize + 8; + + if (total_balance > 0) { + float barW = availWidth - Layout::spacingXxl() * 1.5f; + float barH = std::max(S.drawElement("tabs.market", "ratio-bar-min-height").size, S.drawElement("tabs.market", "ratio-bar-height").size * vs); + float shieldedRatio = (float)(private_balance / total_balance); + if (shieldedRatio > 1.0f) shieldedRatio = 1.0f; + if (shieldedRatio < 0.0f) shieldedRatio = 0.0f; + float shieldedW = barW * shieldedRatio; + float transpW = barW - shieldedW; + + ImVec2 barStart(cx, cy); + + dl->AddRectFilled(barStart, ImVec2(barStart.x + barW, barStart.y + barH), + IM_COL32(255, 255, 255, 10), 3.0f); + if (shieldedW > 0.5f) + dl->AddRectFilled(barStart, ImVec2(barStart.x + shieldedW, barStart.y + barH), + WithAlpha(Success(), 200), + transpW > 0.5f ? ImDrawFlags_RoundCornersLeft : ImDrawFlags_RoundCornersAll, 3.0f); + if (transpW > 0.5f) + dl->AddRectFilled(ImVec2(barStart.x + shieldedW, barStart.y), + ImVec2(barStart.x + barW, barStart.y + barH), + WithAlpha(Warning(), 200), + shieldedW > 0.5f ? ImDrawFlags_RoundCornersRight : ImDrawFlags_RoundCornersAll, 3.0f); + + int pct = (int)(shieldedRatio * 100.0f + 0.5f); + snprintf(buf, sizeof(buf), "%d%% Shielded", pct); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cx, cy + barH + 2), OnSurfaceDisabled(), buf); + } + + float actualCardH = (total_balance > 0) ? std::max(60.0f, portfolioBudgetH) : cardH; + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMin.y + actualCardH)); + ImGui::Dummy(ImVec2(availWidth, 0)); + ImGui::Dummy(ImVec2(0, gap)); + } + + ImGui::EndChild(); // ##MarketScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/market_tab.h b/src/ui/windows/market_tab.h new file mode 100644 index 0000000..cccdbff --- /dev/null +++ b/src/ui/windows/market_tab.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Market tab + * Shows price information and charts + */ +void RenderMarketTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/mining_tab.cpp b/src/ui/windows/mining_tab.cpp new file mode 100644 index 0000000..9c33f33 --- /dev/null +++ b/src/ui/windows/mining_tab.cpp @@ -0,0 +1,1505 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "mining_tab.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../data/wallet_state.h" +#include "../../config/settings.h" +#include "../../util/platform.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../material/components/buttons.h" +#include "../effects/low_spec.h" +#include "../layout.h" +#include "../notifications.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// Local UI state for thread grid +static int s_selected_threads = 0; +static bool s_threads_initialized = false; + +// Drag-to-select state +static bool s_drag_active = false; +static int s_drag_anchor_thread = 0; // thread# where drag started + +// Pool mode state +static bool s_pool_mode = false; +static char s_pool_url[256] = "pool.dragonx.is"; +static char s_pool_worker[256] = "x"; +static bool s_pool_settings_dirty = false; +static bool s_pool_state_loaded = false; +static bool s_show_pool_log = false; // Toggle: false=chart, true=log + +// Get max threads based on hardware +static int GetMaxMiningThreads() +{ + int hw_threads = std::thread::hardware_concurrency(); + return std::max(1, hw_threads); +} + +// Format hashrate with appropriate units +static std::string FormatHashrate(double hashrate) +{ + char buf[64]; + if (hashrate >= 1e12) { + snprintf(buf, sizeof(buf), "%.2f TH/s", hashrate / 1e12); + } else if (hashrate >= 1e9) { + snprintf(buf, sizeof(buf), "%.2f GH/s", hashrate / 1e9); + } else if (hashrate >= 1e6) { + snprintf(buf, sizeof(buf), "%.2f MH/s", hashrate / 1e6); + } else if (hashrate >= 1e3) { + snprintf(buf, sizeof(buf), "%.2f KH/s", hashrate / 1e3); + } else { + snprintf(buf, sizeof(buf), "%.2f H/s", hashrate); + } + return std::string(buf); +} + +// Calculate estimated hours to find a block +static double EstimateHoursToBlock(double localHashrate, double networkHashrate, double difficulty) +{ + if (localHashrate <= 0 || networkHashrate <= 0) return 0; + double blocksPerHour = 3600.0 / 75.0; + double yourShare = localHashrate / networkHashrate; + if (yourShare <= 0) return 0; + return 1.0 / (blocksPerHour * yourShare); +} + +// Format estimated time +static std::string FormatEstTime(double est_hours) +{ + char buf[64]; + if (est_hours <= 0) { + return "N/A"; + } else if (est_hours < 1.0) { + snprintf(buf, sizeof(buf), "~%.0f min", est_hours * 60.0); + } else if (est_hours < 24.0) { + snprintf(buf, sizeof(buf), "~%.1f hrs", est_hours); + } else if (est_hours < 168.0) { + snprintf(buf, sizeof(buf), "~%.1f days", est_hours / 24.0); + } else { + snprintf(buf, sizeof(buf), "~%.1f weeks", est_hours / 168.0); + } + return std::string(buf); +} + +void RenderMiningTab(App* app) +{ + auto& S = schema::UI(); + auto sliderInput = S.input("tabs.mining", "thread-slider"); + auto startBtn = S.button("tabs.mining", "start-button"); + auto lbl = S.label("tabs.mining", "label-column"); + const auto& state = app->getWalletState(); + const auto& mining = state.mining; + + // Scrollable child to contain all content within available space + ImVec2 miningAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##MiningScroll", miningAvail, false, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar); + + // Responsive: scale factors per frame + float availWidth = ImGui::GetContentRegionAvail().x; + float hs = Layout::hScale(availWidth); + float vs = Layout::vScale(miningAvail.y); + float pad = Layout::cardInnerPadding(); + float gap = Layout::cardGap(); + const float dp = Layout::dpiScale(); + auto tier = Layout::currentTier(availWidth, miningAvail.y); + (void)tier; + + int max_threads = GetMaxMiningThreads(); + + if (!s_threads_initialized) { + s_selected_threads = mining.generate ? std::max(1, mining.genproclimit) : 1; + s_threads_initialized = true; + } + + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = Layout::glassRounding(); + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + char buf[128]; + + // Load pool state from settings on first frame + if (!s_pool_state_loaded) { + s_pool_mode = app->settings()->getPoolMode(); + strncpy(s_pool_url, app->settings()->getPoolUrl().c_str(), sizeof(s_pool_url) - 1); + strncpy(s_pool_worker, app->settings()->getPoolWorker().c_str(), sizeof(s_pool_worker) - 1); + + // If pool worker is empty or placeholder, default to user's first address + std::string workerStr(s_pool_worker); + if (workerStr.empty() || workerStr == "x") { + std::string defaultAddr; + for (const auto& addr : state.addresses) { + if (addr.type == "shielded" && !addr.address.empty()) { + defaultAddr = addr.address; + break; + } + } + if (defaultAddr.empty()) { + for (const auto& addr : state.addresses) { + if (addr.type == "transparent" && !addr.address.empty()) { + defaultAddr = addr.address; + break; + } + } + } + if (!defaultAddr.empty()) { + strncpy(s_pool_worker, defaultAddr.c_str(), sizeof(s_pool_worker) - 1); + s_pool_worker[sizeof(s_pool_worker) - 1] = '\0'; + } + } + s_pool_state_loaded = true; + } + + // Persist pool settings when dirty and no field is active + if (s_pool_settings_dirty && !ImGui::IsAnyItemActive()) { + app->settings()->setPoolUrl(s_pool_url); + app->settings()->setPoolWorker(s_pool_worker); + app->settings()->save(); + s_pool_settings_dirty = false; + } + + // Determine active mining state for UI + bool isMiningActive = s_pool_mode + ? state.pool_mining.xmrig_running + : mining.generate; + + // ================================================================ + // Proportional section budget — ensures all content fits without + // scrolling at the minimum window size (1024×775). + // ================================================================ + float sHdr = ovFont->LegacySize + Layout::spacingXs() + + ImGui::GetStyle().ItemSpacing.y * 2.0f; + float gapOver = gap + ImGui::GetStyle().ItemSpacing.y; + // 3 sections with headers (CHART+STATS, DETAILS+EARNINGS, BLOCKS) + float totalOverhead = 3.0f * (sHdr + gapOver) + 1.0f * gapOver; + float cardBudget = std::max(schema::UI().drawElement("tabs.mining", "card-budget-min").size, miningAvail.y - totalOverhead); + + Layout::SectionBudget cb(cardBudget); + float controlsBudgetH = cb.allocate(0.26f, 80.0f * dp); + float chartBudgetH = cb.allocate(0.22f, 60.0f * dp); + (void)cb; // remaining budget used by combined earnings+details card + + // ================================================================ + // MODE TOGGLE — SOLO | POOL segmented control + // ================================================================ + { + float toggleW = schema::UI().drawElement("tabs.mining", "mode-toggle-width").size * hs; + float toggleH = schema::UI().drawElement("tabs.mining", "mode-toggle-height").size; + float toggleRnd = schema::UI().drawElement("tabs.mining", "mode-toggle-rounding").size; + float totalW = toggleW * 2; + + ImVec2 tMin = ImGui::GetCursorScreenPos(); + ImVec2 tMax(tMin.x + totalW, tMin.y + toggleH); + + // Glass background for the segmented control + dl->AddRectFilled(tMin, tMax, WithAlpha(OnSurface(), 15), toggleRnd); + dl->AddRect(tMin, tMax, WithAlpha(OnSurface(), 40), toggleRnd); + + // SOLO button (left half) + ImVec2 soloMin = tMin; + ImVec2 soloMax(tMin.x + toggleW, tMax.y); + bool soloHov = material::IsRectHovered(soloMin, soloMax); + if (!s_pool_mode) { + dl->AddRectFilled(soloMin, soloMax, WithAlpha(Primary(), 180), toggleRnd); + } else if (soloHov) { + dl->AddRectFilled(soloMin, soloMax, WithAlpha(OnSurface(), 20), toggleRnd); + } + { + const char* label = "SOLO"; + ImVec2 sz = ovFont->CalcTextSizeA(ovFont->LegacySize, FLT_MAX, 0, label); + float lx = soloMin.x + (toggleW - sz.x) * 0.5f; + float ly = soloMin.y + (toggleH - sz.y) * 0.5f; + ImU32 col = !s_pool_mode ? IM_COL32(255, 255, 255, 230) : OnSurfaceMedium(); + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(lx, ly), col, label); + } + + // POOL button (right half) — disabled when solo mining is active + bool soloMiningActive = mining.generate; + ImVec2 poolMin(tMin.x + toggleW, tMin.y); + ImVec2 poolMax = tMax; + bool poolHov = material::IsRectHovered(poolMin, poolMax); + if (s_pool_mode) { + dl->AddRectFilled(poolMin, poolMax, WithAlpha(Primary(), 180), toggleRnd); + } else if (soloMiningActive) { + // Dimmed — solo mining blocks pool mode + } else if (poolHov) { + dl->AddRectFilled(poolMin, poolMax, WithAlpha(OnSurface(), 20), toggleRnd); + } + { + const char* label = "POOL"; + ImVec2 sz = ovFont->CalcTextSizeA(ovFont->LegacySize, FLT_MAX, 0, label); + float lx = poolMin.x + (toggleW - sz.x) * 0.5f; + float ly = poolMin.y + (toggleH - sz.y) * 0.5f; + ImU32 col = s_pool_mode ? IM_COL32(255, 255, 255, 230) + : (soloMiningActive ? OnSurfaceDisabled() : OnSurfaceMedium()); + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(lx, ly), col, label); + } + + // Invisible buttons for click targets + ImGui::SetCursorScreenPos(soloMin); + ImGui::InvisibleButton("##SoloMode", ImVec2(toggleW, toggleH)); + if (ImGui::IsItemClicked() && s_pool_mode) { + s_pool_mode = false; + app->settings()->setPoolMode(false); + app->settings()->save(); + app->stopPoolMining(); + } + if (soloHov) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + ImGui::SetCursorScreenPos(poolMin); + ImGui::InvisibleButton("##PoolMode", ImVec2(toggleW, toggleH)); + if (ImGui::IsItemClicked() && !s_pool_mode && !soloMiningActive) { + s_pool_mode = true; + app->settings()->setPoolMode(true); + app->settings()->save(); + app->stopMining(); + } + if (poolHov && !soloMiningActive) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (poolHov && soloMiningActive && !s_pool_mode) { + ImGui::SetTooltip("Stop solo mining to use pool mining"); + } + + ImGui::SetCursorScreenPos(ImVec2(tMin.x, tMax.y)); + ImGui::Dummy(ImVec2(totalW, 0)); + + // Pool URL + Worker inputs inline next to toggle (pool mode only) + if (s_pool_mode && soloMiningActive) { + // Solo mining is active — show disabled message instead of inputs + float inputFrameH = ImGui::GetFrameHeight(); + float vertOff = (toggleH - inputFrameH) * 0.5f; + ImGui::SetCursorScreenPos(ImVec2(tMax.x + Layout::spacingLg(), tMin.y + vertOff)); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(Warning())); + ImGui::AlignTextToFramePadding(); + ImGui::PushFont(Type().iconSmall()); + ImGui::TextUnformatted(ICON_MD_INFO); + ImGui::PopFont(); + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::PushFont(capFont); + ImGui::TextUnformatted("Stop solo mining to configure pool settings"); + ImGui::PopFont(); + ImGui::PopStyleColor(); + } else if (s_pool_mode) { + // Position inputs to the right of the toggle + float inputFrameH = ImGui::GetFrameHeight(); + float vertOff = (toggleH - inputFrameH) * 0.5f; + float inputsStartX = tMax.x + Layout::spacingLg(); + ImGui::SetCursorScreenPos(ImVec2(inputsStartX, tMin.y + vertOff)); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 4.0f * dp); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(8 * dp, 4 * dp)); + + // Calculate remaining width from inputs start to end of content region + float inputFrameH2 = ImGui::GetFrameHeight(); + float resetBtnW = inputFrameH2; // Square button matching input height + float contentEndX = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x; + float remainW = contentEndX - inputsStartX - Layout::spacingSm() - resetBtnW - Layout::spacingSm(); + float urlW = std::max(60.0f, remainW * 0.30f); + float wrkW = std::max(40.0f, remainW * 0.70f); + + ImGui::SetNextItemWidth(urlW); + if (ImGui::InputTextWithHint("##PoolURL", "Pool URL", s_pool_url, sizeof(s_pool_url))) { + s_pool_settings_dirty = true; + } + + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::SetNextItemWidth(wrkW); + if (ImGui::InputTextWithHint("##PoolWorker", "Payout Address", s_pool_worker, sizeof(s_pool_worker))) { + s_pool_settings_dirty = true; + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Your DRAGONX address for receiving pool payouts"); + } + + // Reset to defaults button (matching input height) + ImGui::SameLine(0, Layout::spacingSm()); + { + ImVec2 btnPos = ImGui::GetCursorScreenPos(); + ImVec2 btnSize(inputFrameH2, inputFrameH2); + ImGui::InvisibleButton("##ResetPoolDefaults", btnSize); + bool btnHov = ImGui::IsItemHovered(); + bool btnClk = ImGui::IsItemClicked(); + + ImDrawList* dl2 = ImGui::GetWindowDrawList(); + ImVec2 btnCenter(btnPos.x + btnSize.x * 0.5f, btnPos.y + btnSize.y * 0.5f); + + // Hover highlight + if (btnHov) { + dl2->AddRectFilled(btnPos, ImVec2(btnPos.x + btnSize.x, btnPos.y + btnSize.y), + StateHover(), 4.0f * dp); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Reset to defaults"); + } + + // Icon + ImFont* iconFont = Type().iconSmall(); + const char* resetIcon = ICON_MD_REFRESH; + ImVec2 iconSz = iconFont->CalcTextSizeA(iconFont->LegacySize, FLT_MAX, 0, resetIcon); + dl2->AddText(iconFont, iconFont->LegacySize, + ImVec2(btnCenter.x - iconSz.x * 0.5f, btnCenter.y - iconSz.y * 0.5f), + OnSurfaceMedium(), resetIcon); + + if (btnClk) { + strncpy(s_pool_url, "pool.dragonx.is", sizeof(s_pool_url) - 1); + // Default to user's first shielded address for pool payouts + std::string defaultAddr; + for (const auto& addr : state.addresses) { + if (addr.type == "shielded" && !addr.address.empty()) { + defaultAddr = addr.address; + break; + } + } + if (defaultAddr.empty()) { + // Fallback to transparent if no shielded available + for (const auto& addr : state.addresses) { + if (addr.type == "transparent" && !addr.address.empty()) { + defaultAddr = addr.address; + break; + } + } + } + strncpy(s_pool_worker, defaultAddr.c_str(), sizeof(s_pool_worker) - 1); + s_pool_worker[sizeof(s_pool_worker) - 1] = '\0'; + s_pool_settings_dirty = true; + } + } + + ImGui::PopStyleVar(2); + } + + // Ensure cursor Y is at toggle bottom regardless of pool input widgets, + // so the cards below stay at the same position in both solo and pool modes. + ImGui::SetCursorScreenPos(ImVec2(tMin.x, tMax.y)); + ImGui::Dummy(ImVec2(0, gap * 0.5f)); + } + + // ================================================================ + // CONTROLS — Glass card with CPU core grid (no heading) + // ================================================================ + { + // Mining button beside the controls card + float miningBtnGap = gap; + float miningBtnMaxW = availWidth * schema::UI().drawElement("tabs.mining", "btn-max-width-ratio").size; + + // --- Compute thread grid layout based on controls card width --- + // Estimate controlsW first to compute cols correctly + float estControlsW = availWidth - std::min(schema::UI().drawElement("tabs.mining", "button-max-width-clamp").size, miningBtnMaxW) - miningBtnGap; + float innerW = estControlsW - pad * 2; + float cellSz = std::clamp(schema::UI().drawElement("tabs.mining", "cell-size").size * vs, schema::UI().drawElement("tabs.mining", "cell-min-size").size, schema::UI().drawElement("tabs.mining", "cell-max-size").sizeOr(42.0f)); + float cellGap = std::max(schema::UI().drawElement("tabs.mining", "cell-gap-min").size, cellSz * schema::UI().drawElement("tabs.mining", "cell-gap-ratio").size); + int cols = std::max(1, std::min(max_threads, (int)(innerW / (cellSz + cellGap)))); + int rows = (max_threads + cols - 1) / cols; + float gridW = cols * cellSz + (cols - 1) * cellGap; + float gridH = rows * cellSz + (rows - 1) * cellGap; + + // Card sections: header(label+info+RAM inline) | grid + float headerH = capFont->LegacySize + Layout::spacingXs(); + float secGap = Layout::spacingLg(); + + // Card height from actual content, capped by proportional budget + float cardH = pad + headerH + secGap + gridH + pad; + cardH = std::clamp(cardH, schema::UI().drawElement("tabs.mining", "control-card-min-height").size, controlsBudgetH); + + // Mining button — sized to match card height (square) + float miningBtnSz = cardH; + if (miningBtnSz + miningBtnGap > miningBtnMaxW) + miningBtnSz = miningBtnMaxW; + float controlsW = availWidth - miningBtnSz - miningBtnGap; + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + ImVec2 cardMax(cardMin.x + controlsW, cardMin.y + cardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + float curY = cardMin.y + pad; + + // --- Header row: "THREADS 4 / 16" + RAM est + active indicator --- + { + ImVec2 labelPos(cardMin.x + pad, curY); + dl->AddText(ovFont, ovFont->LegacySize, labelPos, OnSurfaceMedium(), "THREADS"); + + float labelW = ovFont->CalcTextSizeA(ovFont->LegacySize, FLT_MAX, 0, "THREADS").x; + snprintf(buf, sizeof(buf), " %d / %d", s_selected_threads, max_threads); + ImVec2 countPos(labelPos.x + labelW, curY); + dl->AddText(sub1, sub1->LegacySize, countPos, OnSurface(), buf); + + // RAM estimate inline (after thread count) + // Model matches hush3 RandomX: shared ~2080MB dataset + ~256MB cache (allocated once), + // plus ~2MB scratchpad per mining thread VM. + { + float countW = sub1->CalcTextSizeA(sub1->LegacySize, FLT_MAX, 0, buf).x; + double ram_estimate_mb = schema::UI().drawElement("business", "ram-base-mb").size + + schema::UI().drawElement("business", "ram-dataset-mb").size + + schema::UI().drawElement("business", "ram-cache-mb").size + + s_selected_threads * schema::UI().drawElement("business", "ram-per-thread-mb").size; + double ram_estimate_gb = ram_estimate_mb / 1024.0; + snprintf(buf, sizeof(buf), " RAM ~%.1fGB", ram_estimate_gb); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(countPos.x + countW, curY + (sub1->LegacySize - capFont->LegacySize) * 0.5f), + OnSurfaceDisabled(), buf); + } + + // Active mining indicator (top-right) + if (mining.generate) { + float pulse = effects::isLowSpecMode() + ? schema::UI().drawElement("animations", "pulse-base-normal").size + : schema::UI().drawElement("animations", "pulse-base-normal").size + schema::UI().drawElement("animations", "pulse-amp-normal").size * (float)std::sin((double)ImGui::GetTime() * schema::UI().drawElement("animations", "pulse-speed-normal").size); + ImU32 pulseCol = WithAlpha(Success(), (int)(255 * pulse)); + float dotR = schema::UI().drawElement("tabs.mining", "active-dot-radius").size + 2.0f * hs; + dl->AddCircleFilled(ImVec2(cardMax.x - pad - dotR * 2, curY + dotR + 1 * dp), dotR, pulseCol); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(cardMax.x - pad - dotR * 2 - 60 * hs, curY), + WithAlpha(Success(), 200), "Mining"); + } + curY += headerH + secGap; + } + + // --- Thread Grid (drag-to-select) --- + { + // Center the grid horizontally within the card + float gridX = cardMin.x + pad + (innerW - gridW) * 0.5f; + float gridY = curY; + + bool threads_changed = false; + + // Track which thread the mouse is currently over (-1 = none) + int hovered_thread = -1; + + // First pass: hit-test all cells to find hovered thread + for (int i = 0; i < max_threads; i++) { + int row = i / cols; + int col = i % cols; + float cx = gridX + col * (cellSz + cellGap); + float cy = gridY + row * (cellSz + cellGap); + if (material::IsRectHovered(ImVec2(cx, cy), ImVec2(cx + cellSz, cy + cellSz))) { + hovered_thread = i + 1; + break; + } + } + + // Show pointer cursor when hovering the thread grid + if (hovered_thread > 0) + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Drag-to-select logic + if (ImGui::IsMouseClicked(0) && hovered_thread > 0) { + // Begin drag + s_drag_active = true; + s_drag_anchor_thread = hovered_thread; + s_selected_threads = hovered_thread; + threads_changed = true; + } + if (s_drag_active) { + if (ImGui::IsMouseDown(0)) { + if (hovered_thread > 0 && hovered_thread != s_selected_threads) { + // Drag selects up to the hovered thread in either direction + s_selected_threads = hovered_thread; + threads_changed = true; + } + } else { + // Mouse released — end drag + s_drag_active = false; + } + } + + // Render cells + for (int i = 0; i < max_threads; i++) { + int row = i / cols; + int col = i % cols; + float cx = gridX + col * (cellSz + cellGap); + float cy = gridY + row * (cellSz + cellGap); + ImVec2 cMin(cx, cy); + ImVec2 cMax(cx + cellSz, cy + cellSz); + + int threadNum = i + 1; + bool active = threadNum <= s_selected_threads; + bool hovered = (threadNum == hovered_thread); + + // Determine visual state + float rounding = schema::UI().drawElement("tabs.mining", "cell-rounding").size; + if (active && mining.generate) { + // Mining + active: animated heat glow using theme colors + float t = (float)ImGui::GetTime(); + float phase = t * schema::UI().drawElement("animations", "heat-glow-speed").size + i * schema::UI().drawElement("animations", "heat-glow-phase-offset").size; + float glow = effects::isLowSpecMode() ? 0.5f : 0.5f + 0.5f * (float)std::sin(phase); + + // Base color from theme (--mining-heat-glow) falling back to Primary + ImU32 heatBase = schema::UI().resolveColor("var(--mining-heat-glow)", Primary()); + int baseR = (heatBase >> 0) & 0xFF; + int baseG = (heatBase >> 8) & 0xFF; + int baseB = (heatBase >> 16) & 0xFF; + // Brighten toward white as glow increases + int r = std::min(255, (int)(baseR + (255 - baseR) * 0.3f * glow)); + int g = std::min(255, (int)(baseG + (255 - baseG) * 0.3f * glow)); + int b = std::min(255, (int)(baseB + (255 - baseB) * 0.3f * glow)); + int a = (int)(180 + 60 * glow); + ImU32 fillCol = IM_COL32(r, g, b, a); + dl->AddRectFilled(cMin, cMax, fillCol, rounding); + // Bright border + dl->AddRect(cMin, cMax, WithAlpha(Primary(), (int)(160 + 60 * glow)), rounding, 0, schema::UI().drawElement("tabs.mining", "active-cell-border-thickness").size); + } else if (active) { + // Active but not mining: solid primary fill + ImU32 pri = Primary(); + int priR = (pri >> 0) & 0xFF; + int priG = (pri >> 8) & 0xFF; + int priB = (pri >> 16) & 0xFF; + ImU32 fillCol = hovered + ? IM_COL32(priR, priG, priB, 220) + : IM_COL32(priR, priG, priB, 180); + dl->AddRectFilled(cMin, cMax, fillCol, rounding); + dl->AddRect(cMin, cMax, IM_COL32(priR, priG, priB, 255), rounding, 0, schema::UI().drawElement("tabs.mining", "cell-border-thickness").size); + } else { + // Inactive: dim outline + ImU32 fillCol = hovered + ? WithAlpha(OnSurface(), 25) + : WithAlpha(OnSurface(), 8); + dl->AddRectFilled(cMin, cMax, fillCol, rounding); + dl->AddRect(cMin, cMax, WithAlpha(OnSurface(), hovered ? 80 : 35), rounding); + } + + // Thread number label (centered) + snprintf(buf, sizeof(buf), "%d", threadNum); + ImVec2 txtSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + ImVec2 txtPos(cx + (cellSz - txtSz.x) * 0.5f, cy + (cellSz - txtSz.y) * 0.5f); + ImU32 txtCol = active ? schema::UI().resolveColor("var(--on-primary)", IM_COL32(255, 255, 255, 230)) : WithAlpha(OnSurface(), 80); + dl->AddText(capFont, capFont->LegacySize, txtPos, txtCol, buf); + } + + if (threads_changed && mining.generate) { + app->startMining(s_selected_threads); + } + if (threads_changed && s_pool_mode && state.pool_mining.xmrig_running) { + app->stopPoolMining(); + app->startPoolMining(s_selected_threads); + } + + curY += gridH + secGap; + } + + // ============================================================ + // Large square mining button — right of the controls card + // ============================================================ + { + float btnX = cardMin.x + controlsW + miningBtnGap; + float btnY = cardMin.y; + ImVec2 bMin(btnX, btnY); + ImVec2 bMax(btnX + miningBtnSz, btnY + cardH); + + bool btnHovered = material::IsRectHovered(bMin, bMax); + bool btnClicked = btnHovered && ImGui::IsMouseClicked(0); + bool isSyncing = state.sync.syncing; + bool poolBlockedBySolo = s_pool_mode && mining.generate && !state.pool_mining.xmrig_running; + bool disabled = !app->isConnected() || app->isMiningToggleInProgress() || isSyncing || poolBlockedBySolo; + + // Glass panel background with state-dependent tint + GlassPanelSpec btnGlass; + btnGlass.rounding = Layout::glassRounding(); + if (isMiningActive) { + // Active mining: warm glow + float pulse = effects::isLowSpecMode() + ? schema::UI().drawElement("animations", "pulse-base-glow").size + : schema::UI().drawElement("animations", "pulse-base-glow").size + schema::UI().drawElement("animations", "pulse-amp-glow").size * (float)std::sin((double)ImGui::GetTime() * schema::UI().drawElement("animations", "pulse-speed-slow").size); + int glowA = (int)(20 + 30 * pulse); + btnGlass.fillAlpha = glowA; + } else { + btnGlass.fillAlpha = btnHovered ? 30 : 18; + } + DrawGlassPanel(dl, bMin, bMax, btnGlass); + + // Hover highlight + if (btnHovered && !disabled) { + dl->AddRectFilled(bMin, bMax, + isMiningActive ? WithAlpha(Error(), 25) : WithAlpha(Success(), 20), + btnGlass.rounding); + } + + // Draw mining icon centered in button — Material Design ICON_MD_CONSTRUCTION + { + float btnW = bMax.x - bMin.x; + float btnH = bMax.y - bMin.y; + float cx = bMin.x + btnW * 0.5f; + float cy = bMin.y + btnH * schema::UI().drawElement("tabs.mining", "button-icon-y-ratio").size; // shift up to leave room for label + + ImU32 iconCol; + if (disabled) { + iconCol = OnSurfaceDisabled(); + } else if (isMiningActive) { + float pulse = effects::isLowSpecMode() + ? schema::UI().drawElement("animations", "pulse-base-normal").size + : schema::UI().drawElement("animations", "pulse-base-normal").size + schema::UI().drawElement("animations", "pulse-amp-normal").size * (float)std::sin((double)ImGui::GetTime() * schema::UI().drawElement("animations", "pulse-speed-normal").size); + iconCol = WithAlpha(Error(), (int)(200 + 55 * pulse)); + } else { + iconCol = btnHovered ? WithAlpha(Success(), 255) : OnSurfaceMedium(); + } + + // Use XL icon for the large mining button + ImFont* iconFont = Type().iconXL(); + const char* mineIcon = isMiningActive ? ICON_MD_CLOSE : ICON_MD_CONSTRUCTION; + ImVec2 iconSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, mineIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - iconSz.x * 0.5f, cy - iconSz.y * 0.5f), iconCol, mineIcon); + } + + // Label below icon + { + float btnW = bMax.x - bMin.x; + float btnH = bMax.y - bMin.y; + const char* label = isMiningActive ? "STOP" : "MINE"; + ImVec2 lblSz = ovFont->CalcTextSizeA(ovFont->LegacySize, FLT_MAX, 0, label); + float lblX = bMin.x + (btnW - lblSz.x) * 0.5f; + float lblY = bMin.y + btnH * schema::UI().drawElement("tabs.mining", "button-label-y-ratio").size; + ImU32 lblCol = disabled ? WithAlpha(OnSurface(), 50) : + (isMiningActive ? WithAlpha(Error(), 220) : WithAlpha(OnSurface(), 160)); + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(lblX, lblY), lblCol, label); + } + + // Tooltip + pointer cursor + if (btnHovered) { + if (!disabled) + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (isSyncing) + ImGui::SetTooltip("Syncing blockchain... (%.1f%%)", state.sync.verification_progress * 100.0); + else if (poolBlockedBySolo) + ImGui::SetTooltip("Stop solo mining before starting pool mining"); + else + ImGui::SetTooltip(isMiningActive ? "Stop Mining" : "Start Mining"); + } + + // Click action — pool or solo + if (btnClicked && !disabled) { + if (s_pool_mode) { + if (state.pool_mining.xmrig_running) + app->stopPoolMining(); + else + app->startPoolMining(s_selected_threads); + } else { + if (mining.generate) + app->stopMining(); + else + app->startMining(s_selected_threads); + } + } + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // HASHRATE + STATS — Combined glass card: stat values on top, chart below + // (Or full-card log view when toggled in pool mode) + // ================================================================ + { + ImU32 greenCol = Success(); + + // Determine view mode first + bool showLogView = s_pool_mode && s_show_pool_log && !state.pool_mining.log_lines.empty(); + bool hasLogContent = s_pool_mode && !state.pool_mining.log_lines.empty(); + // Use pool hashrate history when in pool mode, solo otherwise + const std::vector& chartHistory = s_pool_mode + ? state.pool_mining.hashrate_history + : mining.hashrate_history; + bool hasChartContent = chartHistory.size() >= 2; + + // Stat row height (single line: overline + value) + float statRowH = ovFont->LegacySize + Layout::spacingXs() + sub1->LegacySize + Layout::spacingSm(); + float totalCardH = statRowH + chartBudgetH + pad; + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + totalCardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // --- Toggle button in top-right corner (pool mode only) --- + if (s_pool_mode && (hasLogContent || hasChartContent)) { + ImFont* iconFont = Type().iconSmall(); + const char* toggleIcon = s_show_pool_log ? ICON_MD_SHOW_CHART : ICON_MD_ARTICLE; + const char* toggleTip = s_show_pool_log ? "Show hashrate chart" : "Show miner log"; + ImVec2 iconSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, toggleIcon); + float btnSize = iconSz.y + 8 * dp; + float btnX = cardMax.x - pad - btnSize; + float btnY = cardMin.y + pad * 0.5f; + ImVec2 btnMin(btnX, btnY); + ImVec2 btnMax(btnX + btnSize, btnY + btnSize); + ImVec2 btnCenter((btnMin.x + btnMax.x) * 0.5f, (btnMin.y + btnMax.y) * 0.5f); + + bool hov = IsRectHovered(btnMin, btnMax); + if (hov) { + dl->AddCircleFilled(btnCenter, btnSize * 0.5f, StateHover()); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("%s", toggleTip); + } + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(btnCenter.x - iconSz.x * 0.5f, btnCenter.y - iconSz.y * 0.5f), + OnSurfaceMedium(), toggleIcon); + if (hov && ImGui::IsMouseClicked(0)) { + s_show_pool_log = !s_show_pool_log; + } + } + + if (showLogView) { + // --- Full-card log view --- + float logPad = pad * 0.5f; + ImGui::SetCursorScreenPos(ImVec2(cardMin.x + logPad, cardMin.y + logPad)); + ImGui::BeginChild("##PoolLogInCard", ImVec2(availWidth - logPad * 2, totalCardH - logPad * 2), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_HorizontalScrollbar); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurface())); + ImFont* monoFont = Type().body2(); + ImGui::PushFont(monoFont); + for (const auto& line : state.pool_mining.log_lines) { + if (!line.empty()) + ImGui::TextUnformatted(line.c_str()); + } + ImGui::PopFont(); + ImGui::PopStyleColor(); + + // Auto-scroll to bottom only if user is already near the bottom + // This allows manual scrolling up to read history + float scrollY = ImGui::GetScrollY(); + float scrollMaxY = ImGui::GetScrollMaxY(); + if (scrollMaxY <= 0.0f || scrollY >= scrollMaxY - 20.0f * dp) + ImGui::SetScrollHereY(1.0f); + + ImGui::EndChild(); + + // Reset cursor to end of card after the child window + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); // Register position with layout system + } else { + // --- Stats + Chart view --- + + // Pool vs Solo stats — different columns + std::string col1Str, col2Str, col3Str, col4Str; + const char* col1Label; + const char* col2Label; + const char* col3Label; + const char* col4Label = nullptr; + ImU32 col1Col, col2Col, col3Col, col4Col = OnSurface(); + int numStats = 3; + + if (s_pool_mode) { + col1Label = "POOL HASHRATE"; + col1Str = FormatHashrate(state.pool_mining.hashrate_10s); + col1Col = state.pool_mining.xmrig_running ? greenCol : OnSurfaceDisabled(); + + col2Label = "THREADS / MEM"; + { + char buf[64]; + int64_t memMB = state.pool_mining.memory_used / (1024 * 1024); + if (memMB > 0) + snprintf(buf, sizeof(buf), "%d / %lld MB", state.pool_mining.threads_active, (long long)memMB); + else + snprintf(buf, sizeof(buf), "%d / --", state.pool_mining.threads_active); + col2Str = buf; + } + col2Col = OnSurface(); + + col3Label = "SHARES"; + char sharesBuf[64]; + snprintf(sharesBuf, sizeof(sharesBuf), "%lld / %lld", + (long long)state.pool_mining.accepted, + (long long)state.pool_mining.rejected); + col3Str = sharesBuf; + col3Col = OnSurface(); + + col4Label = "UPTIME"; + int64_t up = state.pool_mining.uptime_sec; + char uptBuf[64]; + if (up <= 0) + snprintf(uptBuf, sizeof(uptBuf), "N/A"); + else if (up < 3600) + snprintf(uptBuf, sizeof(uptBuf), "%lldm %llds", (long long)(up / 60), (long long)(up % 60)); + else + snprintf(uptBuf, sizeof(uptBuf), "%lldh %lldm", (long long)(up / 3600), (long long)((up % 3600) / 60)); + col4Str = uptBuf; + col4Col = OnSurface(); + numStats = 4; + } else { + double est_hours = EstimateHoursToBlock(mining.localHashrate, mining.networkHashrate, mining.difficulty); + + col1Label = "LOCAL HASHRATE"; + col1Str = FormatHashrate(mining.localHashrate); + col1Col = mining.generate ? greenCol : OnSurfaceDisabled(); + + col2Label = "NETWORK"; + col2Str = FormatHashrate(mining.networkHashrate); + col2Col = OnSurface(); + + col3Label = "EST. BLOCK"; + col3Str = FormatEstTime(est_hours); + col3Col = OnSurface(); + } + + // Draw stat values as inline columns at top of card + { + float statColW = (availWidth - pad * 2) / (float)numStats; + float sy = cardMin.y + pad * 0.5f; + + struct StatEntry { const char* label; const char* value; ImU32 col; }; + char c1Buf[64], c2Buf[64], c3Buf[64], c4Buf[64]; + snprintf(c1Buf, sizeof(c1Buf), "%s", col1Str.c_str()); + snprintf(c2Buf, sizeof(c2Buf), "%s", col2Str.c_str()); + snprintf(c3Buf, sizeof(c3Buf), "%s", col3Str.c_str()); + if (numStats > 3) snprintf(c4Buf, sizeof(c4Buf), "%s", col4Str.c_str()); + StatEntry stats[] = { + { col1Label, c1Buf, col1Col }, + { col2Label, c2Buf, col2Col }, + { col3Label, c3Buf, col3Col }, + { col4Label ? col4Label : "", c4Buf, col4Col }, + }; + + for (int si = 0; si < numStats; si++) { + float sx = cardMin.x + pad + si * statColW; + float centerX = sx + statColW * 0.5f; + + ImVec2 lblSz = ovFont->CalcTextSizeA(ovFont->LegacySize, 10000, 0, stats[si].label); + dl->AddText(ovFont, ovFont->LegacySize, + ImVec2(centerX - lblSz.x * 0.5f, sy), OnSurfaceMedium(), stats[si].label); + + ImVec2 valSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, stats[si].value); + float valY = sy + ovFont->LegacySize + Layout::spacingXs(); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(centerX - valSz.x * 0.5f, valY), stats[si].col, stats[si].value); + + // Trend arrow for hashrate (first column only) + if (si == 0 && chartHistory.size() >= 6) { + size_t hn = chartHistory.size(); + double recent = (chartHistory[hn-1] + chartHistory[hn-2] + chartHistory[hn-3]) / 3.0; + double older = (chartHistory[hn-4] + chartHistory[hn-5] + chartHistory[hn-6]) / 3.0; + ImFont* iconFont = Type().iconSmall(); + float arrowX = centerX + valSz.x * 0.5f + Layout::spacingSm(); + if (recent > older * 1.02) { + const char* icon = ICON_MD_TRENDING_UP; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(arrowX, valY + sub1->LegacySize * 0.5f - iSz.y * 0.5f), + WithAlpha(Success(), 220), icon); + } else if (recent < older * 0.98) { + const char* icon = ICON_MD_TRENDING_DOWN; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(arrowX, valY + sub1->LegacySize * 0.5f - iSz.y * 0.5f), + WithAlpha(Error(), 220), icon); + } + } + } + } + + // Sparkline chart below stats + if (hasChartContent) { + float chartTop = cardMin.y + statRowH; + float chartBot = cardMax.y; + + // Compute Y range + double yMin = *std::min_element(chartHistory.begin(), chartHistory.end()); + double yMax = *std::max_element(chartHistory.begin(), chartHistory.end()); + if (yMax <= yMin) { yMax = yMin + 1.0; } + double yRange = yMax - yMin; + double yPad2 = yRange * 0.1; + yMin -= yPad2; + yMax += yPad2; + + float plotLeft = cardMin.x + pad; + float plotRight = cardMax.x - pad; + float plotTop = chartTop + capFont->LegacySize + 4 * dp; + float plotBottom = chartBot - capFont->LegacySize * 2 - 16 * dp; + float plotW = plotRight - plotLeft; + float plotH = std::max(1.0f, plotBottom - plotTop); + + size_t n = chartHistory.size(); + std::vector points(n); + for (size_t i = 0; i < n; i++) { + float t2 = (n > 1) ? (float)i / (float)(n - 1) : 0.0f; + float x = plotLeft + t2 * plotW; + float y = plotBottom - (float)((chartHistory[i] - yMin) / (yMax - yMin)) * plotH; + points[i] = ImVec2(x, y); + } + + // Fill under curve + for (size_t i = 0; i + 1 < n; i++) { + ImVec2 quad[4] = { + points[i], points[i + 1], + ImVec2(points[i + 1].x, plotBottom), + ImVec2(points[i].x, plotBottom) + }; + dl->AddConvexPolyFilled(quad, 4, WithAlpha(Success(), 25)); + } + + // Green line + dl->AddPolyline(points.data(), (int)points.size(), + WithAlpha(Success(), 200), ImDrawFlags_None, schema::UI().drawElement("tabs.mining", "chart-line-thickness").size); + + // Y-axis labels + std::string yMaxStr = FormatHashrate(yMax); + std::string yMinStr = FormatHashrate(yMin); + dl->AddText(capFont, capFont->LegacySize, ImVec2(plotLeft + 2 * dp, plotTop - capFont->LegacySize - 2 * dp), OnSurfaceDisabled(), yMaxStr.c_str()); + dl->AddText(capFont, capFont->LegacySize, ImVec2(plotLeft + 2 * dp, plotBottom + 4 * dp), OnSurfaceDisabled(), yMinStr.c_str()); + + // X-axis labels + dl->AddText(capFont, capFont->LegacySize, + ImVec2(plotLeft, chartBot - capFont->LegacySize - 2 * dp), + OnSurfaceDisabled(), + chartHistory.size() >= 300 ? "5m ago" : + chartHistory.size() >= 60 ? "1m ago" : "start"); + std::string nowLbl = "now"; + ImVec2 nowSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, nowLbl.c_str()); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(plotRight - nowSz.x, chartBot - capFont->LegacySize - 2 * dp), + OnSurfaceDisabled(), nowLbl.c_str()); + } + + // Advance cursor past the card (stats/chart view only) + ImGui::Dummy(ImVec2(availWidth, totalCardH)); + } + + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // EARNINGS — Horizontal row card (Today | All Time | Est. Daily) + // ================================================================ + { + // Gather mining transactions from state + double minedToday = 0.0, minedAllTime = 0.0; + int minedTodayCount = 0, minedAllTimeCount = 0; + int64_t now = (int64_t)std::time(nullptr); + int64_t dayStart = now - 86400; + + struct MinedTx { + int64_t timestamp; + double amount; + int confirmations; + bool mature; + }; + std::vector recentMined; + + for (const auto& tx : state.transactions) { + if (tx.type == "generate" || tx.type == "immature" || tx.type == "mined") { + double amt = std::abs(tx.amount); + minedAllTime += amt; + minedAllTimeCount++; + if (tx.timestamp >= dayStart) { + minedToday += amt; + minedTodayCount++; + } + if (recentMined.size() < 4) { + recentMined.push_back({tx.timestamp, amt, tx.confirmations, tx.confirmations >= 100}); + } + } + } + + // Use pool hashrate for EST. DAILY when in pool mode + double estHashrate = s_pool_mode ? state.pool_mining.hashrate_10s : mining.localHashrate; + double est_hours_2 = EstimateHoursToBlock(estHashrate, mining.networkHashrate, mining.difficulty); + double estDailyBlocks = (est_hours_2 > 0) ? (24.0 / est_hours_2) : 0.0; + double blockReward = schema::UI().drawElement("business", "block-reward").size; + double estDaily = estDailyBlocks * blockReward; + bool estActive = isMiningActive && estDaily > 0; + + ImU32 greenCol2 = Success(); + + // --- Combined Earnings + Details card --- + float earningsRowH = ovFont->LegacySize + Layout::spacingXs() + sub1->LegacySize + pad * 1.5f; + float detailsContentH = pad * 0.5f + capFont->LegacySize + pad * 0.5f; + float barH_est = capFont->LegacySize + Layout::spacingMd() * 2.0f; + float combinedCardH = earningsRowH + detailsContentH + barH_est + pad; + combinedCardH = std::max(combinedCardH, + schema::UI().drawElement("tabs.mining", "details-card-min-height").size + earningsRowH); + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + ImVec2 cardMax(cardMin.x + availWidth, cardMin.y + combinedCardH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // === Earnings section (top of combined card) === + { + float colW = (availWidth - pad * 2) / 3.0f; + float ey = cardMin.y + pad * 0.5f; + char valBuf[64], subBuf2[64]; + + struct EarningsEntry { + const char* label; + const char* value; + const char* sub; + ImU32 col; + }; + + snprintf(valBuf, sizeof(valBuf), "+%.4f", minedToday); + snprintf(subBuf2, sizeof(subBuf2), "(%d blk)", minedTodayCount); + char todayVal[64], todaySub[64]; + strncpy(todayVal, valBuf, sizeof(todayVal)); + strncpy(todaySub, subBuf2, sizeof(todaySub)); + + char allVal[64], allSub[64]; + snprintf(allVal, sizeof(allVal), "+%.4f", minedAllTime); + snprintf(allSub, sizeof(allSub), "(%d blk)", minedAllTimeCount); + + char estVal[64]; + if (estActive) + snprintf(estVal, sizeof(estVal), "~%.4f", estDaily); + else + snprintf(estVal, sizeof(estVal), "N/A"); + + EarningsEntry entries[] = { + { "TODAY", todayVal, todaySub, greenCol2 }, + { "ALL TIME", allVal, allSub, OnSurface() }, + { "EST. DAILY", estVal, nullptr, estActive ? greenCol2 : OnSurfaceDisabled() }, + }; + + for (int ei = 0; ei < 3; ei++) { + float sx = cardMin.x + pad + ei * colW; + float centerX = sx + colW * 0.5f; + + // Overline label (centered) + ImVec2 lblSz = ovFont->CalcTextSizeA(ovFont->LegacySize, 10000, 0, entries[ei].label); + dl->AddText(ovFont, ovFont->LegacySize, + ImVec2(centerX - lblSz.x * 0.5f, ey), OnSurfaceMedium(), entries[ei].label); + + // Value (centered) + float valY = ey + ovFont->LegacySize + Layout::spacingXs(); + ImVec2 valSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, entries[ei].value); + + if (entries[ei].sub) { + // Value + sub annotation side by side, centered together + ImVec2 subSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, entries[ei].sub); + float totalW = valSz.x + 4 * dp + subSz.x; + float startX = centerX - totalW * 0.5f; + dl->AddText(sub1, sub1->LegacySize, ImVec2(startX, valY), entries[ei].col, entries[ei].value); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(startX + valSz.x + 4 * dp, valY + (sub1->LegacySize - capFont->LegacySize) * 0.5f), + OnSurfaceDisabled(), entries[ei].sub); + } else { + dl->AddText(sub1, sub1->LegacySize, + ImVec2(centerX - valSz.x * 0.5f, valY), entries[ei].col, entries[ei].value); + } + } + } + + // === Separator between earnings & details === + float earningsSepY = cardMin.y + earningsRowH; + { + float rnd = glassSpec.rounding; + dl->AddLine(ImVec2(cardMin.x + rnd * 0.5f, earningsSepY), + ImVec2(cardMax.x - rnd * 0.5f, earningsSepY), + WithAlpha(OnSurface(), 15), 1.0f * dp); + } + + // === Details section (below separator) === + { + float cx = cardMin.x + pad; + float cy = earningsSepY + pad * 0.5f; + + // Three equal columns: Difficulty | Block | Mining Address + float colW = availWidth / 3.0f; + float valOffX = availWidth * schema::UI().drawElement("tabs.mining", "stats-col1-value-x-ratio").size; + + float col1X = cx; + float col2X = cx + colW; + float col3X = cx + colW * 2.0f; + + // -- Difficulty -- + dl->AddText(capFont, capFont->LegacySize, ImVec2(col1X, cy), OnSurfaceMedium(), "Difficulty"); + if (mining.difficulty > 0) { + snprintf(buf, sizeof(buf), "%.4f", mining.difficulty); + dl->AddText(capFont, capFont->LegacySize, ImVec2(col1X + valOffX, cy), OnSurface(), buf); + ImVec2 diffSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + ImGui::SetCursorScreenPos(ImVec2(col1X + valOffX, cy)); + ImGui::InvisibleButton("##DiffCopy", ImVec2(diffSz.x + Layout::spacingMd(), capFont->LegacySize + 4 * dp)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy difficulty"); + dl->AddLine(ImVec2(col1X + valOffX, cy + capFont->LegacySize + 1 * dp), + ImVec2(col1X + valOffX + diffSz.x, cy + capFont->LegacySize + 1 * dp), + WithAlpha(OnSurface(), 60), 1.0f * dp); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(buf); + Notifications::instance().info("Difficulty copied"); + } + } + + // -- Block -- + dl->AddText(capFont, capFont->LegacySize, ImVec2(col2X, cy), OnSurfaceMedium(), "Block"); + if (mining.blocks > 0) { + snprintf(buf, sizeof(buf), "%d", mining.blocks); + dl->AddText(capFont, capFont->LegacySize, ImVec2(col2X + valOffX, cy), OnSurface(), buf); + ImVec2 blkSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + ImGui::SetCursorScreenPos(ImVec2(col2X + valOffX, cy)); + ImGui::InvisibleButton("##BlockCopy", ImVec2(blkSz.x + Layout::spacingMd(), capFont->LegacySize + 4 * dp)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy block height"); + dl->AddLine(ImVec2(col2X + valOffX, cy + capFont->LegacySize + 1 * dp), + ImVec2(col2X + valOffX + blkSz.x, cy + capFont->LegacySize + 1 * dp), + WithAlpha(OnSurface(), 60), 1.0f * dp); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(buf); + Notifications::instance().info("Block height copied"); + } + } + + // -- Mining Address -- + dl->AddText(capFont, capFont->LegacySize, ImVec2(col3X, cy), OnSurfaceMedium(), "Mining Addr"); + std::string mining_address = ""; + for (const auto& addr : state.addresses) { + if (addr.type == "transparent" && !addr.address.empty()) { + mining_address = addr.address; + break; + } + } + if (!mining_address.empty()) { + float addrAvailW = colW - pad - valOffX; + float charW = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, "M").x; + int maxChars = std::max(8, (int)(addrAvailW / charW)); + std::string truncAddr = mining_address; + if ((int)truncAddr.length() > maxChars) { + int half = (maxChars - 3) / 2; + truncAddr = truncAddr.substr(0, half) + "..." + truncAddr.substr(truncAddr.length() - half); + } + dl->AddText(capFont, capFont->LegacySize, ImVec2(col3X + valOffX, cy), OnSurface(), truncAddr.c_str()); + + ImVec2 addrTextSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, truncAddr.c_str()); + ImGui::SetCursorScreenPos(ImVec2(col3X + valOffX, cy)); + ImGui::InvisibleButton("##MiningAddrCopy", ImVec2(addrTextSz.x + Layout::spacingMd(), capFont->LegacySize + 4 * dp)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy mining address"); + dl->AddLine(ImVec2(col3X + valOffX, cy + capFont->LegacySize + 1 * dp), + ImVec2(col3X + valOffX + addrTextSz.x, cy + capFont->LegacySize + 1 * dp), + WithAlpha(OnSurface(), 60), 1.0f * dp); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(mining_address.c_str()); + Notifications::instance().info("Mining address copied"); + } + } + } + + // ---- Memory bar — centered in remaining space below details ---- + { + double totalRAM = dragonx::util::Platform::getTotalSystemRAM_MB(); + double usedRAM = dragonx::util::Platform::getUsedSystemRAM_MB(); + double selfRAM = dragonx::util::Platform::getSelfMemoryUsageMB(); + double daemonRAM = app->getDaemonMemoryUsageMB(); + // Include xmrig memory when pool mining + double xmrigRAM = state.pool_mining.memory_used / (1024.0 * 1024.0); // bytes -> MB + double appRAM = selfRAM + daemonRAM + xmrigRAM; // App + daemon + xmrig combined + + // Fixed bar height (text + padding) + float barH = capFont->LegacySize + Layout::spacingMd() * 2.0f; + float barRnd = barH * 0.5f; // fully rounded corners + + // Details content ends here + float detailsEndY = earningsSepY + detailsContentH; + + // Subtle top separator at the boundary + float rnd = glassSpec.rounding; + float stripY = detailsEndY; + dl->AddLine(ImVec2(cardMin.x + rnd * 0.5f, stripY), + ImVec2(cardMax.x - rnd * 0.5f, stripY), + WithAlpha(OnSurface(), 15), 1.0f * dp); + float remainingH = cardMax.y - stripY; + float barX = cardMin.x + pad; + float barW = cardMax.x - pad - barX; + float barY = stripY + (remainingH - barH) * 0.5f; + float textY = barY + (barH - capFont->LegacySize) * 0.5f; + float textPadX = Layout::spacingMd(); + + // Background track + dl->AddRectFilled(ImVec2(barX, barY), ImVec2(barX + barW, barY + barH), + WithAlpha(OnSurface(), 20), barRnd); + + float sysFrac = 0.0f, appFrac = 0.0f; + float sysFillW = 0.0f, appFillW = 0.0f; + + // Helper: draw a fill bar that perfectly matches the track's rounded + // left edge regardless of fill width. We draw a full-width rounded + // rect (same shape as the track) but clip it to just the fill portion. + auto drawFillBar = [&](float fillW, ImU32 col) { + if (fillW <= 1.0f) return; + dl->PushClipRect(ImVec2(barX, barY), ImVec2(barX + fillW, barY + barH), true); + dl->AddRectFilled(ImVec2(barX, barY), ImVec2(barX + barW, barY + barH), + col, barRnd); + dl->PopClipRect(); + }; + + if (usedRAM > 0 && totalRAM > 0) { + sysFrac = std::clamp((float)(usedRAM / totalRAM), 0.0f, 1.0f); + sysFillW = barW * sysFrac; + + // System memory bar (subtle fill) + ImU32 ramBarCol = schema::UI().resolveColor("var(--ram-bar-system)", + IsDarkTheme() ? IM_COL32(255, 255, 255, 46) : IM_COL32(0, 0, 0, 46)); + drawFillBar(sysFillW, ramBarCol); + + // App+daemon memory bar (saturated accent) + if (appRAM > 0) { + appFrac = std::clamp((float)(appRAM / totalRAM), 0.0f, sysFrac); + appFillW = barW * appFrac; + ImU32 appBarCol = schema::UI().resolveColor("var(--ram-bar-app)", + ImGui::ColorConvertFloat4ToU32(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive])); + drawFillBar(appFillW, appBarCol); + } + } + + // --- Text overlaying the bar --- + float accentEdge = barX + appFillW; + float whiteEdge = barX + sysFillW; + + // Determine text colors for bar segments + // On dark themes: white text on empty, dark on filled bars (both system and app) + // On light themes: dark text on empty/system, white on app accent bar + ImU32 barTextOnEmpty = IsDarkTheme() ? IM_COL32(255, 255, 255, 230) + : IM_COL32(30, 30, 30, 230); + ImU32 barTextOnFill = IsDarkTheme() ? IM_COL32(30, 30, 30, 230) + : IM_COL32(255, 255, 255, 230); + ImU32 barTextOnAccent = IsDarkTheme() ? IM_COL32(0, 0, 0, 210) + : IM_COL32(255, 255, 255, 230); + + // App usage on the left + char appBuf[64] = {}; + if (appRAM > 0) { + if (appRAM >= 1024.0) + snprintf(appBuf, sizeof(appBuf), "%.1f GB", appRAM / 1024.0); + else + snprintf(appBuf, sizeof(appBuf), "%.0f MB", appRAM); + + float appTextX = barX + textPadX; + float appTextW = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, appBuf).x; + float appTextEnd = appTextX + appTextW; + + // Inside accent bar: white | inside white bar: dark | outside: white + if (appTextEnd <= accentEdge) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(appTextX, textY), + barTextOnAccent, appBuf); + } else if (appTextX >= whiteEdge) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(appTextX, textY), + barTextOnEmpty, appBuf); + } else { + // Part in accent bar: white + if (accentEdge > appTextX) { + dl->PushClipRect(ImVec2(appTextX, barY), ImVec2(accentEdge, barY + barH)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(appTextX, textY), + barTextOnAccent, appBuf); + dl->PopClipRect(); + } + // Part in white bar (past accent): dark + float dkS = std::max(appTextX, accentEdge); + float dkE = std::min(appTextEnd, whiteEdge); + if (dkE > dkS) { + dl->PushClipRect(ImVec2(dkS, barY), ImVec2(dkE, barY + barH)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(appTextX, textY), + barTextOnFill, appBuf); + dl->PopClipRect(); + } + // Part outside white bar: white + if (appTextEnd > whiteEdge) { + dl->PushClipRect(ImVec2(whiteEdge, barY), ImVec2(appTextEnd + 1, barY + barH)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(appTextX, textY), + barTextOnEmpty, appBuf); + dl->PopClipRect(); + } + } + } + + // System usage on the right + char sysBuf[64] = {}; + if (usedRAM > 0 && totalRAM > 0) + snprintf(sysBuf, sizeof(sysBuf), "%.1f / %.0f GB", usedRAM / 1024.0, totalRAM / 1024.0); + else if (totalRAM > 0) + snprintf(sysBuf, sizeof(sysBuf), "-- / %.0f GB", totalRAM / 1024.0); + else + snprintf(sysBuf, sizeof(sysBuf), "N/A"); + + float sysTextW = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, sysBuf).x; + float sysTextX = barX + barW - textPadX - sysTextW; + + if (sysTextX >= whiteEdge) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(sysTextX, textY), + barTextOnEmpty, sysBuf); + } else if (sysTextX + sysTextW <= whiteEdge) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(sysTextX, textY), + barTextOnFill, sysBuf); + } else { + dl->PushClipRect(ImVec2(sysTextX, barY), ImVec2(whiteEdge, barY + barH)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(sysTextX, textY), + barTextOnFill, sysBuf); + dl->PopClipRect(); + dl->PushClipRect(ImVec2(whiteEdge, barY), ImVec2(sysTextX + sysTextW + 1, barY + barH)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(sysTextX, textY), + barTextOnEmpty, sysBuf); + dl->PopClipRect(); + } + + // Invisible button over the bar for tooltip interaction + ImGui::SetCursorScreenPos(ImVec2(barX, barY)); + ImGui::InvisibleButton("##rambar", ImVec2(barW, barH)); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + if (selfRAM >= 1024.0) + ImGui::Text("Wallet: %.1f GB", selfRAM / 1024.0); + else + ImGui::Text("Wallet: %.0f MB", selfRAM); + if (daemonRAM >= 1024.0) + ImGui::Text("Daemon: %.1f GB (%s)", daemonRAM / 1024.0, app->getDaemonMemDiag().c_str()); + else + ImGui::Text("Daemon: %.0f MB (%s)", daemonRAM, app->getDaemonMemDiag().c_str()); + ImGui::Separator(); + ImGui::Text("System: %.1f / %.0f GB", usedRAM / 1024.0, totalRAM / 1024.0); + ImGui::EndTooltip(); + } + } + + ImGui::SetCursorScreenPos(ImVec2(cardMin.x, cardMax.y)); + ImGui::Dummy(ImVec2(availWidth, 0)); + ImGui::Dummy(ImVec2(0, gap)); + + // ============================================================ + // RECENT BLOCKS — last 4 mined blocks + // ============================================================ + if (!recentMined.empty()) { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT BLOCKS"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + float rowH_blocks = std::max(schema::UI().drawElement("tabs.mining", "recent-row-min-height").size, schema::UI().drawElement("tabs.mining", "recent-row-height").size * vs); + // Size to remaining space — proportional budget ensures fit + float recentAvailH = ImGui::GetContentRegionAvail().y - sHdr - gapOver; + float contentH_blocks = rowH_blocks * (float)recentMined.size() + pad * 2.5f; + float recentH = std::clamp(contentH_blocks, 30.0f * dp, std::max(30.0f * dp, recentAvailH)); + + // Glass panel wrapping the list + scroll-edge mask state + ImVec2 recentPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 recentPanelMax(recentPanelMin.x + availWidth, recentPanelMin.y + recentH); + GlassPanelSpec recentGlass; + recentGlass.rounding = Layout::glassRounding(); + DrawGlassPanel(dl, recentPanelMin, recentPanelMax, recentGlass); + + float miningScrollY = 0.0f, miningScrollMaxY = 0.0f; + int miningParentVtx = dl->VtxBuffer.Size; + + ImGui::BeginChild("##RecentBlocks", ImVec2(availWidth, recentH), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar); + ImDrawList* miningChildDL = ImGui::GetWindowDrawList(); + int miningChildVtx = miningChildDL->VtxBuffer.Size; + + miningScrollY = ImGui::GetScrollY(); + miningScrollMaxY = ImGui::GetScrollMaxY(); + + // Top padding inside glass card + ImGui::Dummy(ImVec2(0, pad * 0.5f)); + + for (size_t mi = 0; mi < recentMined.size(); mi++) { + const auto& mtx = recentMined[mi]; + + ImVec2 rMin = ImGui::GetCursorScreenPos(); + float rH = std::max(schema::UI().drawElement("tabs.mining", "recent-row-min-height").size, schema::UI().drawElement("tabs.mining", "recent-row-height").size * vs); + ImVec2 rMax(rMin.x + availWidth, rMin.y + rH); + + // Subtle background on hover (inset from card edges) + bool hovered = material::IsRectHovered(rMin, rMax); + if (hovered) { + dl->AddRectFilled(ImVec2(rMin.x + pad * 0.5f, rMin.y), + ImVec2(rMax.x - pad * 0.5f, rMax.y), + IM_COL32(255, 255, 255, 8), 3.0f * dp); + } + + float rx = rMin.x + pad; + float ry = rMin.y + Layout::spacingXs(); + + // Mining icon — Material Design + ImFont* iconFont = Type().iconSmall(); + const char* mIcon = ICON_MD_CONSTRUCTION; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, mIcon); + float iconX = rx + 2 * dp, iconY = ry + 2 * dp; + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(iconX, iconY), + WithAlpha(Warning(), 200), mIcon); + + // Time + int64_t diff = now - mtx.timestamp; + if (diff < 60) + snprintf(buf, sizeof(buf), "%llds ago", (long long)diff); + else if (diff < 3600) + snprintf(buf, sizeof(buf), "%lldm ago", (long long)(diff / 60)); + else if (diff < 86400) + snprintf(buf, sizeof(buf), "%lldh ago", (long long)(diff / 3600)); + else + snprintf(buf, sizeof(buf), "%lldd ago", (long long)(diff / 86400)); + dl->AddText(capFont, capFont->LegacySize, ImVec2(rx + iSz.x + 8 * dp, ry), OnSurfaceDisabled(), buf); + + // Amount + snprintf(buf, sizeof(buf), "+%.8f %s", mtx.amount, DRAGONX_TICKER); + float amtX = rMin.x + pad + (availWidth - pad * 2) * 0.35f; + dl->AddText(capFont, capFont->LegacySize, ImVec2(amtX, ry), greenCol2, buf); + + // Maturity badge — inset from right edge + float badgeX = rMax.x - pad - Layout::spacingXl() * 3.5f; + if (mtx.mature) { + dl->AddText(capFont, capFont->LegacySize, ImVec2(badgeX, ry), + WithAlpha(Success(), 180), "Mature"); + } else { + snprintf(buf, sizeof(buf), "%d conf", mtx.confirmations); + dl->AddText(capFont, capFont->LegacySize, ImVec2(badgeX, ry), + WithAlpha(Warning(), 200), buf); + } + + ImGui::Dummy(ImVec2(availWidth, rH)); + } + + ImGui::EndChild(); // ##RecentBlocks + + // CSS-style clipping mask + { + float fadeZone = std::min(capFont->LegacySize * 3.0f, recentH * 0.18f); + ApplyScrollEdgeMask(dl, miningParentVtx, miningChildDL, miningChildVtx, + recentPanelMin.y, recentPanelMax.y, fadeZone, miningScrollY, miningScrollMaxY); + } + + ImGui::Dummy(ImVec2(0, gap)); + } + } + + // ================================================================ + // POOL CONNECTION STATUS — inline indicator (pool mode, no log) + // ================================================================ + if (s_pool_mode && state.pool_mining.log_lines.empty() && state.pool_mining.xmrig_running) { + ImFont* iconFont = Type().iconSmall(); + const char* dotIcon = ICON_MD_CIRCLE; + ImU32 dotCol = state.pool_mining.connected ? WithAlpha(Success(), 200) : WithAlpha(Error(), 200); + const char* statusText = state.pool_mining.connected + ? (state.pool_mining.pool_url.empty() ? "Connected" : state.pool_mining.pool_url.c_str()) + : "Connecting..."; + + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 dotSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, dotIcon); + dl->AddText(iconFont, iconFont->LegacySize, pos, dotCol, dotIcon); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(pos.x + dotSz.x + 4 * dp, pos.y + (dotSz.y - capFont->LegacySize) * 0.5f), + OnSurfaceMedium(), statusText); + ImGui::Dummy(ImVec2(availWidth, capFont->LegacySize + 4 * dp)); + } + + ImGui::EndChild(); // ##MiningScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/mining_tab.h b/src/ui/windows/mining_tab.h new file mode 100644 index 0000000..c8a6ef5 --- /dev/null +++ b/src/ui/windows/mining_tab.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Mining tab + * Controls for CPU mining with RandomX + */ +void RenderMiningTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/peers_tab.cpp b/src/ui/windows/peers_tab.cpp new file mode 100644 index 0000000..b8776c1 --- /dev/null +++ b/src/ui/windows/peers_tab.cpp @@ -0,0 +1,808 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "peers_tab.h" +#include "../../app.h" +#include "../../data/wallet_state.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../layout.h" +#include "../notifications.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// Track selected peer for ban action +static int s_selected_peer_idx = -1; +static int s_selected_banned_idx = -1; + +// Helper: Extract IP without port +static std::string ExtractIP(const std::string& addr) +{ + std::string ip = addr; + if (ip[0] == '[') { + auto pos = ip.rfind("]:"); + if (pos != std::string::npos) ip = ip.substr(1, pos - 1); + } else { + auto pos = ip.rfind(':'); + if (pos != std::string::npos) ip = ip.substr(0, pos); + } + return ip; +} + +void RenderPeersTab(App* app) +{ + auto& S = schema::UI(); + auto peerTable = S.table("tabs.peers", "peer-table"); + auto bannedTable = S.table("tabs.peers", "banned-table"); + const auto& state = app->getWalletState(); + + // Scrollable child to contain all content within available space + ImVec2 peersAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##PeersScroll", peersAvail, false, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar); + + // Responsive: scale factors per frame + float availWidth = ImGui::GetContentRegionAvail().x; + float hs = Layout::hScale(availWidth); + float pad = Layout::cardInnerPadding(); + float gap = Layout::cardGap(); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = Layout::glassRounding(); + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* body2 = Type().body2(); + + char buf[128]; + + // ================================================================ + // BLOCKCHAIN & PEERS CARDS — Side by side + // ================================================================ + float infoCardsH = 0; + { + const auto& mining = state.mining; + + // Compute peer stats + int totalPeers = (int)state.peers.size(); + int inboundCount = 0; + int outboundCount = 0; + double totalPing = 0; + int64_t totalBytesSent = 0, totalBytesRecv = 0; + int tlsCount = 0; + for (const auto& p : state.peers) { + if (p.inbound) inboundCount++; + else outboundCount++; + totalPing += p.pingtime; + totalBytesSent += p.bytessent; + totalBytesRecv += p.bytesrecv; + if (!p.tls_cipher.empty()) tlsCount++; + } + double avgPing = totalPeers > 0 ? (totalPing / totalPeers) * 1000.0 : 0; + + // Format bytes helper + auto fmtBytes = [](int64_t bytes) -> std::string { + char b[32]; + if (bytes >= 1073741824LL) + snprintf(b, sizeof(b), "%.1f GB", bytes / 1073741824.0); + else if (bytes >= 1048576LL) + snprintf(b, sizeof(b), "%.1f MB", bytes / 1048576.0); + else if (bytes >= 1024LL) + snprintf(b, sizeof(b), "%.0f KB", bytes / 1024.0); + else + snprintf(b, sizeof(b), "%lld B", (long long)bytes); + return b; + }; + + // Blockchain card: 5 rows, Peers card: 4 rows (2 cols per row) + float rowH = capFont->LegacySize + Layout::spacingXs() + sub1->LegacySize; + float headerH = ovFont->LegacySize + Layout::spacingSm(); + float dividerH = 1.0f * Layout::dpiScale(); + // Use 5 rows for blockchain card (peers card will have empty space at bottom) + float cardInnerH = pad * 0.5f + headerH + rowH * 5 + (Layout::spacingSm() + dividerH) * 4 + pad * 0.5f; + infoCardsH = cardInnerH; + + float cardW = (availWidth - gap) * 0.5f; + ImVec2 basePos = ImGui::GetCursorScreenPos(); + float dp = Layout::dpiScale(); + + // ================================================================ + // BLOCKCHAIN CARD (left) + // ================================================================ + { + ImVec2 cardMin = basePos; + ImVec2 cardMax(cardMin.x + cardW, cardMin.y + infoCardsH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // Card header + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cardMin.x + pad, cardMin.y + pad * 0.5f), Primary(), "BLOCKCHAIN"); + + float colW = (cardW - pad * 2) / 2.0f; + float ry = cardMin.y + pad * 0.5f + headerH; + + // Helper to draw a subtle horizontal divider + auto drawDivider = [&](float y) { + float rnd = glassSpec.rounding; + dl->AddLine(ImVec2(cardMin.x + rnd * 0.5f, y), + ImVec2(cardMax.x - rnd * 0.5f, y), + WithAlpha(OnSurface(), 15), 1.0f * dp); + }; + + // Row 1: Blocks | Longest Chain + { + // Blocks + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Blocks"); + int blocks = mining.blocks > 0 ? mining.blocks : state.sync.blocks; + if (blocks > 0) { + snprintf(buf, sizeof(buf), "%d", blocks); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Longest Chain + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Longest Chain"); + if (state.longestchain > 0) { + snprintf(buf, sizeof(buf), "%d", state.longestchain); + int localHeight = mining.blocks > 0 ? mining.blocks : state.sync.blocks; + ImU32 chainCol = (localHeight >= state.longestchain) ? Success() : Warning(); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), chainCol, buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 2: Hashrate | Difficulty + { + // Hashrate + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Hashrate"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (mining.networkHashrate > 0) { + if (mining.networkHashrate >= 1e12) + snprintf(buf, sizeof(buf), "%.2f TH/s", mining.networkHashrate / 1e12); + else if (mining.networkHashrate >= 1e9) + snprintf(buf, sizeof(buf), "%.2f GH/s", mining.networkHashrate / 1e9); + else if (mining.networkHashrate >= 1e6) + snprintf(buf, sizeof(buf), "%.2f MH/s", mining.networkHashrate / 1e6); + else if (mining.networkHashrate >= 1e3) + snprintf(buf, sizeof(buf), "%.2f KH/s", mining.networkHashrate / 1e3); + else + snprintf(buf, sizeof(buf), "%.2f H/s", mining.networkHashrate); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), Success(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Difficulty + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Difficulty"); + valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (mining.difficulty > 0) { + snprintf(buf, sizeof(buf), "%.4f", mining.difficulty); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 3: Notarized | Protocol + { + // Notarized + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Notarized"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (state.notarized > 0) { + snprintf(buf, sizeof(buf), "%d", state.notarized); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Protocol + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Protocol"); + valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (state.protocol_version > 0) { + snprintf(buf, sizeof(buf), "%d", state.protocol_version); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 4: Version | Memory + { + // Version + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Version"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (state.daemon_version > 0) { + int major = state.daemon_version / 1000000; + int minor = (state.daemon_version / 10000) % 100; + int patch = (state.daemon_version / 100) % 100; + snprintf(buf, sizeof(buf), "%d.%d.%d", major, minor, patch); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Memory + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Memory"); + valY = ry + capFont->LegacySize + Layout::spacingXs(); + double memMb = state.mining.daemon_memory_mb; + if (memMb > 0) { + if (memMb >= 1024.0) + snprintf(buf, sizeof(buf), "%.1f GB", memMb / 1024.0); + else + snprintf(buf, sizeof(buf), "%.0f MB", memMb); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 5: Longest Chain | Best Block + { + // Longest Chain + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Longest"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (state.longestchain > 0) { + snprintf(buf, sizeof(buf), "%d", state.longestchain); + // Color green if local matches longest, warning if behind + int localHeight = mining.blocks > 0 ? mining.blocks : state.sync.blocks; + ImU32 chainCol = (localHeight >= state.longestchain) ? Success() : Warning(); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), chainCol, buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Best Block (truncated hash) + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Best Block"); + valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (!state.sync.best_blockhash.empty()) { + // Truncate hash to fit: first 6 + "..." + last 6 + std::string hash = state.sync.best_blockhash; + std::string truncHash; + if (hash.length() > 15) { + truncHash = hash.substr(0, 6) + "..." + hash.substr(hash.length() - 6); + } else { + truncHash = hash; + } + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), truncHash.c_str()); + + // Click to copy full hash + ImVec2 hashSz = sub1->CalcTextSizeA(sub1->LegacySize, FLT_MAX, 0, truncHash.c_str()); + ImGui::SetCursorScreenPos(ImVec2(cx, valY)); + ImGui::InvisibleButton("##BestBlockCopy", ImVec2(hashSz.x + Layout::spacingSm(), sub1->LegacySize + 2 * dp)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy: %s", hash.c_str()); + dl->AddLine(ImVec2(cx, valY + sub1->LegacySize + 1 * dp), + ImVec2(cx + hashSz.x, valY + sub1->LegacySize + 1 * dp), + WithAlpha(OnSurface(), 60), 1.0f * dp); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(hash.c_str()); + ui::Notifications::instance().info("Block hash copied"); + } + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + } + } + + // ================================================================ + // PEERS CARD (right) + // ================================================================ + { + ImVec2 cardMin(basePos.x + cardW + gap, basePos.y); + ImVec2 cardMax(cardMin.x + cardW, cardMin.y + infoCardsH); + DrawGlassPanel(dl, cardMin, cardMax, glassSpec); + + // Card header + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(cardMin.x + pad, cardMin.y + pad * 0.5f), Primary(), "PEERS"); + + float colW = (cardW - pad * 2) / 2.0f; + float ry = cardMin.y + pad * 0.5f + headerH; + + // Helper to draw a subtle horizontal divider + auto drawPeerDivider = [&](float y) { + float rnd = glassSpec.rounding; + dl->AddLine(ImVec2(cardMin.x + rnd * 0.5f, y), + ImVec2(cardMax.x - rnd * 0.5f, y), + WithAlpha(OnSurface(), 15), 1.0f * dp); + }; + + // Row 1: Connected | In/Out + { + // Connected + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Connected"); + snprintf(buf, sizeof(buf), "%d", totalPeers); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurface(), buf); + + // In / Out + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "In / Out"); + snprintf(buf, sizeof(buf), "%d / %d", inboundCount, outboundCount); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurface(), buf); + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawPeerDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 2: TLS | Avg Ping + { + // TLS + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "TLS"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (totalPeers > 0) { + snprintf(buf, sizeof(buf), "%d / %d", tlsCount, totalPeers); + ImU32 tlsCol = (tlsCount == totalPeers) ? Success() : OnSurface(); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), tlsCol, buf); + if (tlsCount == totalPeers) { + ImFont* iconFont = Type().iconSmall(); + ImVec2 txtSize = sub1->CalcTextSizeA(sub1->LegacySize, FLT_MAX, 0, buf); + dl->AddText(iconFont, iconFont->LegacySize, ImVec2(cx + txtSize.x + 4, valY), Success(), ICON_MD_CHECK); + } + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + + // Avg Ping + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Avg Ping"); + ImU32 pingCol; + if (avgPing < 100) pingCol = Success(); + else if (avgPing < 500) pingCol = Warning(); + else pingCol = Error(); + snprintf(buf, sizeof(buf), "%.0f ms", avgPing); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), pingCol, buf); + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawPeerDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 3: Received | Sent + { + // Received + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Received"); + std::string recvStr = fmtBytes(totalBytesRecv); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurface(), recvStr.c_str()); + + // Sent + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Sent"); + std::string sentStr = fmtBytes(totalBytesSent); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, ry + capFont->LegacySize + Layout::spacingXs()), OnSurface(), sentStr.c_str()); + } + + ry += rowH + Layout::spacingSm() * 0.5f; + drawPeerDivider(ry); + ry += Layout::spacingSm() * 0.5f + dividerH; + + // Row 4: P2P Port | Banned + { + // P2P Port + float cx = cardMin.x + pad; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "P2P Port"); + float valY = ry + capFont->LegacySize + Layout::spacingXs(); + if (state.p2p_port > 0) { + snprintf(buf, sizeof(buf), "%d", state.p2p_port); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurface(), buf); + } else { + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), OnSurfaceDisabled(), "\xE2\x80\x94"); + } + // Banned count + cx = cardMin.x + pad + colW; + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, ry), OnSurfaceMedium(), "Banned"); + valY = ry + capFont->LegacySize + Layout::spacingXs(); + size_t bannedCount = state.bannedPeers.size(); + snprintf(buf, sizeof(buf), "%zu", bannedCount); + ImU32 bannedCol = (bannedCount > 0) ? Warning() : OnSurface(); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, valY), bannedCol, buf); } + } + + ImGui::Dummy(ImVec2(availWidth, infoCardsH)); + ImGui::Dummy(ImVec2(0, gap)); + } + + // ================================================================ + // Compute remaining space for peer list + footer + // ================================================================ + float footerH = ImGui::GetFrameHeight() + Layout::spacingSm(); + float toggleH = body2->LegacySize + Layout::spacingMd() * 2; + float remainForPeers = std::max(60.0f, peersAvail.y - (ImGui::GetCursorScreenPos().y - ImGui::GetWindowPos().y) - footerH - Layout::spacingSm()); + float peerPanelHeight = remainForPeers - toggleH; + peerPanelHeight = std::max(S.drawElement("tabs.peers", "peer-panel-min-height").size, peerPanelHeight); + + // ================================================================ + // PEERS — Single glass card with Connected / Banned toggle + // ================================================================ + static bool s_show_banned = false; + { + // Toggle header: "Connected (N)" / "Banned (N)" + float toggleY = ImGui::GetCursorScreenPos().y; + { + char connLabel[64], banLabel[64]; + snprintf(connLabel, sizeof(connLabel), "Connected (%zu)", state.peers.size()); + snprintf(banLabel, sizeof(banLabel), "Banned (%zu)", state.bannedPeers.size()); + + ImVec2 connSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, connLabel); + ImVec2 banSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, banLabel); + + float tabGap = Layout::spacingXl(); + float tabStartX = ImGui::GetCursorScreenPos().x + pad; + float dp = Layout::dpiScale(); + + // Connected tab + ImVec2 connPos(tabStartX, toggleY); + ImU32 connCol = s_show_banned ? OnSurfaceDisabled() : OnSurface(); + dl->AddText(body2, body2->LegacySize, ImVec2(connPos.x, connPos.y + Layout::spacingMd() * 0.5f), connCol, connLabel); + if (!s_show_banned) { + float underY = connPos.y + Layout::spacingMd() * 0.5f + body2->LegacySize + 3.0f * dp; + dl->AddRectFilled(ImVec2(connPos.x, underY), ImVec2(connPos.x + connSz.x, underY + 2.0f * dp), Primary(), 1.0f * dp); + } + ImGui::SetCursorScreenPos(connPos); + if (ImGui::InvisibleButton("##tabConn", ImVec2(connSz.x, toggleH))) { + s_show_banned = false; + } + if (ImGui::IsItemHovered()) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + // Banned tab + float banX = tabStartX + connSz.x + tabGap; + ImVec2 banPos(banX, toggleY); + ImU32 banCol = s_show_banned ? OnSurface() : OnSurfaceDisabled(); + dl->AddText(body2, body2->LegacySize, ImVec2(banPos.x, banPos.y + Layout::spacingMd() * 0.5f), banCol, banLabel); + if (s_show_banned) { + float underY = banPos.y + Layout::spacingMd() * 0.5f + body2->LegacySize + 3.0f * dp; + dl->AddRectFilled(ImVec2(banPos.x, underY), ImVec2(banPos.x + banSz.x, underY + 2.0f * dp), Primary(), 1.0f * dp); + } + ImGui::SetCursorScreenPos(banPos); + if (ImGui::InvisibleButton("##tabBan", ImVec2(banSz.x, toggleH))) { + s_show_banned = true; + } + if (ImGui::IsItemHovered()) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + ImGui::SetCursorScreenPos(ImVec2(ImGui::GetWindowPos().x, toggleY + toggleH)); + } + + // Glass panel background + ImVec2 panelMin = ImGui::GetCursorScreenPos(); + ImVec2 panelMax(panelMin.x + availWidth, panelMin.y + peerPanelHeight); + DrawGlassPanel(dl, panelMin, panelMax, glassSpec); + + // Scroll-edge mask state + float listScrollY = 0.0f, listScrollMaxY = 0.0f; + int listParentVtx = dl->VtxBuffer.Size; + + ImGui::BeginChild("##PeersList", ImVec2(availWidth, peerPanelHeight), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + ImDrawList* listChildDL = ImGui::GetWindowDrawList(); + int listChildVtx = listChildDL->VtxBuffer.Size; + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (!s_show_banned) { + // ---- Connected Peers ---- + if (!app->isConnected()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " Not connected to daemon..."); + } else if (state.peers.empty()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " No connected peers"); + } else { + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg(); + float rowInset = Layout::spacingLg(); + float innerW = ImGui::GetContentRegionAvail().x - rowInset * 2; + listScrollY = ImGui::GetScrollY(); + listScrollMaxY = ImGui::GetScrollMaxY(); + + for (size_t i = 0; i < state.peers.size(); i++) { + const auto& peer = state.peers[i]; + bool is_selected = (s_selected_peer_idx == static_cast(i)); + + ImGui::PushID(static_cast(i)); + ImVec2 rawRowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowPos(rawRowPos.x + rowInset, rawRowPos.y); + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + + if (is_selected) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 20), S.drawElement("tabs.peers", "row-selection-rounding").size); + dl->AddRectFilled(rowPos, ImVec2(rowPos.x + S.drawElement("tabs.peers", "row-accent-width").size, rowEnd.y), Primary(), S.drawElement("tabs.peers", "row-accent-rounding").size); + } + + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered && !is_selected) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), S.drawElement("tabs.peers", "row-selection-rounding").size); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + float cx = rowPos.x + pad; + float cy = rowPos.y + Layout::spacingSm(); + + double ping_ms = peer.pingtime * 1000.0; + ImU32 dotCol; + if (ping_ms < 100) dotCol = Success(); + else if (ping_ms < 500) dotCol = Warning(); + else dotCol = Error(); + float pingDotR = S.drawElement("tabs.peers", "ping-dot-radius-base").size + S.drawElement("tabs.peers", "ping-dot-radius-scale").size * hs; + dl->AddCircleFilled(ImVec2(cx + S.drawElement("tabs.peers", "ping-dot-x-offset").size, cy + body2->LegacySize * 0.5f), pingDotR, dotCol); + + dl->AddText(body2, body2->LegacySize, ImVec2(cx + S.drawElement("tabs.peers", "address-x-offset").size, cy), OnSurface(), peer.addr.c_str()); + + { + const char* dirLabel = peer.inbound ? "In" : "Out"; + ImU32 dirBg = peer.inbound ? WithAlpha(Success(), 30) : WithAlpha(Secondary(), 30); + ImU32 dirFg = peer.inbound ? WithAlpha(Success(), 200) : WithAlpha(Secondary(), 200); + ImVec2 dirSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, dirLabel); + float dirX = rowPos.x + innerW - dirSz.x - Layout::spacingXl(); + ImVec2 pillMin(dirX - S.drawElement("tabs.peers", "dir-pill-padding").size, cy + S.drawElement("tabs.peers", "dir-pill-y-offset").size); + ImVec2 pillMax(dirX + dirSz.x + S.drawElement("tabs.peers", "dir-pill-padding").size, cy + capFont->LegacySize + S.drawElement("tabs.peers", "dir-pill-y-bottom").size); + dl->AddRectFilled(pillMin, pillMax, dirBg, S.drawElement("tabs.peers", "dir-pill-rounding").size); + dl->AddText(capFont, capFont->LegacySize, ImVec2(dirX, cy + 2), dirFg, dirLabel); + } + + { + char pingBuf[32]; + snprintf(pingBuf, sizeof(pingBuf), "%.0fms", ping_ms); + ImVec2 pingSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, pingBuf); + float pingX = rowPos.x + innerW - pingSz.x - Layout::spacingXl() * 3; + dl->AddText(capFont, capFont->LegacySize, ImVec2(pingX, cy + 2), dotCol, pingBuf); + } + + float cy2 = cy + body2->LegacySize + Layout::spacingXs(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + S.drawElement("tabs.peers", "address-x-offset").size, cy2), + OnSurfaceDisabled(), peer.subver.c_str()); + + float verW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, peer.subver.c_str()).x; + float tlsBadgeW = std::max(S.drawElement("tabs.peers", "tls-badge-min-width").size, S.drawElement("tabs.peers", "tls-badge-width").size * hs); + if (!peer.tls_cipher.empty()) { + ImU32 tlsBg = WithAlpha(Success(), 25); + ImU32 tlsFg = WithAlpha(Success(), 200); + ImVec2 tlsMin(cx + S.drawElement("tabs.peers", "address-x-offset").size + verW + Layout::spacingSm(), cy2); + ImVec2 tlsMax(tlsMin.x + tlsBadgeW, tlsMin.y + capFont->LegacySize + 2); + dl->AddRectFilled(tlsMin, tlsMax, tlsBg, S.drawElement("tabs.peers", "tls-badge-rounding").size); + dl->AddText(capFont, capFont->LegacySize, ImVec2(tlsMin.x + 4, cy2 + 1), tlsFg, "TLS"); + } else { + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + S.drawElement("tabs.peers", "address-x-offset").size + verW + Layout::spacingSm(), cy2), + WithAlpha(Error(), 140), "No TLS"); + } + + if (peer.banscore > 0) { + char banBuf[16]; + snprintf(banBuf, sizeof(banBuf), "Ban: %d", peer.banscore); + ImU32 banCol = peer.banscore > 50 ? Error() : Warning(); + ImVec2 banSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, banBuf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowPos.x + innerW - banSz.x - Layout::spacingLg(), cy2), banCol, banBuf); + } + + ImGui::InvisibleButton("##peerRow", ImVec2(innerW, rowH)); + if (ImGui::IsItemClicked(0)) { + s_selected_peer_idx = static_cast(i); + } + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicContextItem(nullptr, 0, acrylicTheme.menu)) { + ImGui::Text("Peer: %s", peer.addr.c_str()); + ImGui::Separator(); + if (ImGui::MenuItem("Copy Address")) { + ImGui::SetClipboardText(peer.addr.c_str()); + } + if (ImGui::MenuItem("Copy IP")) { + ImGui::SetClipboardText(ExtractIP(peer.addr).c_str()); + } + ImGui::Separator(); + if (ImGui::MenuItem("Ban Peer (24h)")) { + app->banPeer(ExtractIP(peer.addr), 86400); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + } + + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(8, 3)); + if (ImGui::BeginTable("##PeerTT", 2, ImGuiTableFlags_SizingFixedFit)) { + auto TTRow = [](const char* label, const char* value) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextDisabled("%s", label); + ImGui::TableNextColumn(); + ImGui::Text("%s", value); + }; + char ttBuf[128]; + snprintf(ttBuf, sizeof(ttBuf), "%d", peer.id); + TTRow("ID", ttBuf); + TTRow("Services", peer.services.c_str()); + snprintf(ttBuf, sizeof(ttBuf), "%d", peer.startingheight); + TTRow("Start Height", ttBuf); + snprintf(ttBuf, sizeof(ttBuf), "%ld bytes", peer.bytessent); + TTRow("Sent", ttBuf); + snprintf(ttBuf, sizeof(ttBuf), "%ld bytes", peer.bytesrecv); + TTRow("Received", ttBuf); + snprintf(ttBuf, sizeof(ttBuf), "%d / %d", peer.synced_headers, peer.synced_blocks); + TTRow("Synced H/B", ttBuf); + if (!peer.tls_cipher.empty()) + TTRow("TLS Cipher", peer.tls_cipher.c_str()); + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + ImGui::EndTooltip(); + } + + if (i < state.peers.size() - 1) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(divStart.x + pad + 18, divStart.y), + ImVec2(divStart.x + innerW - pad, divStart.y), + IM_COL32(255, 255, 255, 15)); + } + + ImGui::PopID(); + } + } + } else { + // ---- Banned Peers ---- + if (!app->isConnected()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " Not connected to daemon..."); + } else if (state.bannedPeers.empty()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " No banned peers"); + } else { + float rowH = capFont->LegacySize + S.drawElement("tabs.peers", "banned-row-height-padding").size; + float rowInsetB = pad; + float innerW = ImGui::GetContentRegionAvail().x - rowInsetB * 2; + listScrollY = ImGui::GetScrollY(); + listScrollMaxY = ImGui::GetScrollMaxY(); + + for (size_t i = 0; i < state.bannedPeers.size(); i++) { + const auto& banned = state.bannedPeers[i]; + bool is_selected = (s_selected_banned_idx == static_cast(i)); + + ImGui::PushID(static_cast(i)); + ImVec2 rawRowPosB = ImGui::GetCursorScreenPos(); + ImVec2 rowPos(rawRowPosB.x + rowInsetB, rawRowPosB.y); + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + + if (is_selected) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 20), S.drawElement("tabs.peers", "banned-row-rounding").size); + dl->AddRectFilled(rowPos, ImVec2(rowPos.x + S.drawElement("tabs.peers", "row-accent-width").size, rowEnd.y), WithAlpha(Error(), 200), S.drawElement("tabs.peers", "banned-accent-rounding").size); + } + + if (material::IsRectHovered(rowPos, rowEnd) && !is_selected) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), S.drawElement("tabs.peers", "banned-row-rounding").size); + } + + float cx = rowPos.x + pad; + float cy = rowPos.y + Layout::spacingXs(); + + float banDotR = S.drawElement("tabs.peers", "ban-dot-radius-base").size + S.drawElement("tabs.peers", "ban-dot-radius-scale").size * hs; + dl->AddCircleFilled(ImVec2(cx + S.drawElement("tabs.peers", "ban-dot-x-offset").size, cy + capFont->LegacySize * 0.4f), banDotR, WithAlpha(Error(), 200)); + + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + S.drawElement("tabs.peers", "banned-address-x-offset").size, cy), + OnSurfaceDisabled(), banned.address.c_str()); + + std::string banUntil = banned.getBannedUntilString(); + ImVec2 banSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, banUntil.c_str()); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowPos.x + innerW - banSz.x - Layout::spacingXl() * 5, cy), + OnSurfaceDisabled(), banUntil.c_str()); + + float btnX = rowPos.x + innerW - Layout::spacingXl() * S.drawElement("tabs.peers", "unban-btn-right-offset-multiplier").size; + ImGui::SetCursorScreenPos(ImVec2(btnX, cy - 1)); + if (TactileSmallButton("Unban", S.resolveFont("button"))) { + app->unbanPeer(banned.address); + } + + ImGui::SetCursorScreenPos(rowPos); + ImGui::InvisibleButton("##bannedRow", ImVec2(innerW - S.drawElement("tabs.peers", "banned-row-btn-reserve").size, rowH)); + if (ImGui::IsItemClicked(0)) { + s_selected_banned_idx = static_cast(i); + } + + const auto& acrylicTheme2 = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicContextItem(nullptr, 0, acrylicTheme2.menu)) { + if (ImGui::MenuItem("Copy Address")) { + ImGui::SetClipboardText(banned.address.c_str()); + } + if (ImGui::MenuItem("Unban")) { + app->unbanPeer(banned.address); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + } + + ImGui::SetCursorScreenPos(ImVec2(rowPos.x, rowEnd.y)); + + if (i < state.bannedPeers.size() - 1) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(divStart.x + pad + 8, divStart.y), + ImVec2(divStart.x + innerW - pad, divStart.y), + IM_COL32(255, 255, 255, 15)); + } + + ImGui::PopID(); + } + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImGui::EndChild(); + + // CSS-style clipping mask + { + float fadeFont = s_show_banned ? capFont->LegacySize : body2->LegacySize; + float fadeZone = std::min(fadeFont * 3.0f, peerPanelHeight * 0.18f); + ApplyScrollEdgeMask(dl, listParentVtx, listChildDL, listChildVtx, + panelMin.y, panelMax.y, fadeZone, listScrollY, listScrollMaxY); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + // ================================================================ + // Footer — Refresh + Clear Bans (material styled) + // ================================================================ + { + ImGui::BeginDisabled(!app->isConnected()); + + if (TactileSmallButton("Refresh Peers", S.resolveFont("button"))) { + app->refreshPeerInfo(); + } + + if (s_show_banned && !state.bannedPeers.empty()) { + ImGui::SameLine(); + if (TactileSmallButton("Clear All Bans", S.resolveFont("button"))) { + app->clearBans(); + } + } + + ImGui::EndDisabled(); + } + + ImGui::EndChild(); // ##PeersScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/peers_tab.h b/src/ui/windows/peers_tab.h new file mode 100644 index 0000000..a3fd88c --- /dev/null +++ b/src/ui/windows/peers_tab.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Peers tab + * Shows connected peers and network info + */ +void RenderPeersTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/qr_popup_dialog.cpp b/src/ui/windows/qr_popup_dialog.cpp new file mode 100644 index 0000000..0871939 --- /dev/null +++ b/src/ui/windows/qr_popup_dialog.cpp @@ -0,0 +1,151 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "qr_popup_dialog.h" +#include "../../app.h" +#include "../widgets/qr_code.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +// Static member initialization +bool QRPopupDialog::s_open = false; +std::string QRPopupDialog::s_address; +std::string QRPopupDialog::s_label; +uintptr_t QRPopupDialog::s_qr_texture = 0; +int QRPopupDialog::s_qr_width = 0; +int QRPopupDialog::s_qr_height = 0; + +void QRPopupDialog::show(const std::string& address, const std::string& label) +{ + // Cleanup previous texture + if (s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } + + s_open = true; + s_address = address; + s_label = label; + + // Generate new QR texture + s_qr_texture = GenerateQRTexture(address.c_str(), &s_qr_width, &s_qr_height); +} + +bool QRPopupDialog::isOpen() +{ + return s_open; +} + +void QRPopupDialog::close() +{ + s_open = false; + if (s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } +} + +void QRPopupDialog::render(App* app) +{ + (void)app; // Unused for now + + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.qr-popup"); + auto qr = S.drawElement("dialogs.qr-popup", "qr-code"); + auto addrInput = S.input("dialogs.qr-popup", "address-input"); + auto actionBtn = S.button("dialogs.qr-popup", "action-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("QR Code"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("QR Code", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + + // Label if present + if (!s_label.empty()) { + ImGui::TextWrapped("%s", s_label.c_str()); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + } + + // Center the QR code + float qr_size = qr.size > 0 ? qr.size : 280; + float window_width = ImGui::GetWindowWidth(); + float padding = (window_width - qr_size) / 2.0f; + + ImGui::SetCursorPosX(padding); + + // Render QR code + if (s_qr_texture != 0) { + ImGui::Image((ImTextureID)s_qr_texture, ImVec2(qr_size, qr_size)); + } else { + // Fallback: show error + ImGui::BeginChild("QRPlaceholder", ImVec2(qr_size, qr_size), true); + ImGui::TextWrapped("Failed to generate QR code"); + ImGui::EndChild(); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Address display + ImGui::Text("Address:"); + + // Use multiline for z-addresses + if (s_address.length() > 50) { + char addr_buf[512]; + strncpy(addr_buf, s_address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##QRAddress", addr_buf, sizeof(addr_buf), + ImVec2(-1, addrInput.height > 0 ? addrInput.height : 60), ImGuiInputTextFlags_ReadOnly); + } else { + char addr_buf[128]; + strncpy(addr_buf, s_address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##QRAddress", addr_buf, sizeof(addr_buf), ImGuiInputTextFlags_ReadOnly); + } + + ImGui::Spacing(); + + // Buttons + float button_width = actionBtn.width; + float total_width = button_width * 2 + ImGui::GetStyle().ItemSpacing.x; + float start_x = (window_width - total_width) / 2.0f; + ImGui::SetCursorPosX(start_x); + + if (material::StyledButton("Copy Address", ImVec2(button_width, 0), S.resolveFont(actionBtn.font))) { + ImGui::SetClipboardText(s_address.c_str()); + } + + ImGui::SameLine(); + + if (material::StyledButton("Close", ImVec2(button_width, 0), S.resolveFont(actionBtn.font))) { + close(); + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + + // Handle window close button + if (!s_open && s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/qr_popup_dialog.h b/src/ui/windows/qr_popup_dialog.h new file mode 100644 index 0000000..334afe7 --- /dev/null +++ b/src/ui/windows/qr_popup_dialog.h @@ -0,0 +1,54 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog showing a large QR code for an address + */ +class QRPopupDialog { +public: + /** + * @brief Show the dialog for an address + * @param address The address to display as QR + * @param label Optional label for the address + */ + static void show(const std::string& address, const std::string& label = ""); + + /** + * @brief Render the dialog (call every frame) + * @param app Pointer to app instance + */ + static void render(App* app); + + /** + * @brief Check if dialog is currently open + */ + static bool isOpen(); + + /** + * @brief Close the dialog and cleanup + */ + static void close(); + +private: + static bool s_open; + static std::string s_address; + static std::string s_label; + static uintptr_t s_qr_texture; + static int s_qr_width; + static int s_qr_height; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/receive_tab.cpp b/src/ui/windows/receive_tab.cpp new file mode 100644 index 0000000..8155ded --- /dev/null +++ b/src/ui/windows/receive_tab.cpp @@ -0,0 +1,1019 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// Receive Tab — redesigned to match Send tab layout +// - Address dropdown at top (like Send's source selector) +// - Single glass card containing QR, address, payment request +// - Action buttons below the card +// - Recent received at bottom + +#include "receive_tab.h" +#include "send_tab.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../data/wallet_state.h" +#include "../../ui/widgets/qr_code.h" +#include "../sidebar.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../notifications.h" +#include "imgui.h" + +#include +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ============================================================================ +// State +// ============================================================================ +static int s_selected_address_idx = -1; +static double s_request_amount = 0.0; +static char s_request_memo[256] = ""; +static double s_request_usd_amount = 0.0; +static bool s_request_usd_mode = false; +static std::string s_cached_qr_data; +static uintptr_t s_qr_texture = 0; +static bool s_auto_selected = false; + +// Address type filter +static int s_addr_type_filter = 0; // 0=All, 1=Z, 2=T + +// Source dropdown preview string +static std::string s_source_preview; + +// Track newly created addresses for NEW badge +static std::map s_new_address_timestamps; +static size_t s_prev_address_count = 0; + +// Address labels (in-memory until persistent config) +static std::map s_address_labels; +static std::string s_pending_select_address; + +// ============================================================================ +// Helpers +// ============================================================================ +static std::string TruncateAddress(const std::string& addr, size_t maxLen = 40) { + if (addr.length() <= maxLen) return addr; + size_t halfLen = (maxLen - 3) / 2; + return addr.substr(0, halfLen) + "..." + addr.substr(addr.length() - halfLen); +} + +static void OpenExplorerURL(const std::string& address) { + std::string url = "https://explorer.dragonx.com/address/" + address; +#ifdef _WIN32 + std::string cmd = "start \"\" \"" + url + "\""; +#elif __APPLE__ + std::string cmd = "open \"" + url + "\""; +#else + std::string cmd = "xdg-open \"" + url + "\""; +#endif + system(cmd.c_str()); +} + +// ============================================================================ +// Track new addresses (detect creations) +// ============================================================================ +static void TrackNewAddresses(const WalletState& state) { + if (state.addresses.size() > s_prev_address_count && s_prev_address_count > 0) { + for (const auto& a : state.addresses) { + if (s_new_address_timestamps.find(a.address) == s_new_address_timestamps.end()) { + s_new_address_timestamps[a.address] = ImGui::GetTime(); + } + } + } else if (s_prev_address_count == 0) { + for (const auto& a : state.addresses) { + s_new_address_timestamps[a.address] = 0.0; + } + } + s_prev_address_count = state.addresses.size(); +} + +// ============================================================================ +// Sync banner +// ============================================================================ +static void RenderSyncBanner(const WalletState& state) { + if (!state.sync.syncing || state.sync.isSynced()) return; + + float syncPct = (state.sync.headers > 0) + ? (float)state.sync.blocks / state.sync.headers * 100.0f : 0.0f; + char syncBuf[128]; + snprintf(syncBuf, sizeof(syncBuf), + "Blockchain syncing (%.1f%%)... Balances may be inaccurate.", syncPct); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(schema::UI().resolveColor(schema::UI().drawElement("tabs.receive", "sync-banner-bg-color").color))); + float syncH = std::max(schema::UI().drawElement("tabs.receive", "sync-banner-min-height").size, schema::UI().drawElement("tabs.receive", "sync-banner-height").size * Layout::vScale()); + ImGui::BeginChild("##SyncBannerRecv", ImVec2(ImGui::GetContentRegionAvail().x, syncH), + false, ImGuiWindowFlags_NoScrollbar); + ImGui::SetCursorPos(ImVec2(Layout::spacingLg(), (syncH - Type().caption()->LegacySize) * 0.5f)); + Type().textColored(TypeStyle::Caption, Warning(), syncBuf); + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Address Dropdown — matches Send tab's source selector style +// ============================================================================ +static void RenderAddressDropdown(App* app, float width) { + const auto& state = app->getWalletState(); + char buf[256]; + + // Header row: label + address type toggle buttons + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "ADDRESS"); + + float toggleBtnW = std::max(schema::UI().drawElement("tabs.receive", "toggle-btn-min-width").size, schema::UI().drawElement("tabs.receive", "toggle-btn-width").size * Layout::hScale(width)); + float toggleGap = schema::UI().drawElement("tabs.receive", "toggle-gap").size; + float toggleTotalW = toggleBtnW * 3 + toggleGap * 2; + ImGui::SameLine(width - toggleTotalW); + const char* filterLabels[] = { "All", "Z", "T" }; + for (int i = 0; i < 3; i++) { + bool isActive = (s_addr_type_filter == i); + if (isActive) { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(PrimaryVariant())); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1)); + } else { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(1, 1, 1, 0.06f)); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium())); + } + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("tabs.receive", "toggle-rounding").size); + char toggleId[32]; + snprintf(toggleId, sizeof(toggleId), "%s##addrFilter", filterLabels[i]); + if (ImGui::Button(toggleId, ImVec2(toggleBtnW, 0))) { + s_addr_type_filter = i; + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); + if (i < 2) ImGui::SameLine(0, toggleGap); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + TrackNewAddresses(state); + + // Auto-select address with the largest balance on first load + if (!s_auto_selected && app->isConnected() && !state.addresses.empty()) { + int bestIdx = -1; + double bestBal = -1.0; + for (size_t i = 0; i < state.addresses.size(); i++) { + if (state.addresses[i].balance > bestBal) { + bestBal = state.addresses[i].balance; + bestIdx = static_cast(i); + } + } + if (bestIdx >= 0) { + s_selected_address_idx = bestIdx; + } + s_auto_selected = true; + } + + // Auto-select pending new address + if (!s_pending_select_address.empty()) { + for (size_t i = 0; i < state.addresses.size(); i++) { + if (state.addresses[i].address == s_pending_select_address) { + s_selected_address_idx = static_cast(i); + s_cached_qr_data.clear(); + s_pending_select_address.clear(); + break; + } + } + } + + // Build preview string + if (!app->isConnected()) { + s_source_preview = "Not connected to daemon"; + } else if (s_selected_address_idx >= 0 && + s_selected_address_idx < (int)state.addresses.size()) { + const auto& addr = state.addresses[s_selected_address_idx]; + bool isZ = addr.type == "shielded"; + const char* tag = isZ ? "[Z]" : "[T]"; + std::string trunc = TruncateAddress(addr.address, + static_cast(std::max(schema::UI().drawElement("tabs.receive", "addr-preview-trunc-min").size, width / schema::UI().drawElement("tabs.receive", "addr-preview-trunc-divisor").size))); + snprintf(buf, sizeof(buf), "%s %s \xe2\x80\x94 %.8f %s", + tag, trunc.c_str(), addr.balance, DRAGONX_TICKER); + s_source_preview = buf; + } else { + s_source_preview = "Select a receiving address..."; + } + + float copyBtnW = std::max(schema::UI().drawElement("tabs.receive", "copy-btn-min-width").size, schema::UI().drawElement("tabs.receive", "copy-btn-width").size * Layout::hScale(width)); + float newBtnW = std::max(schema::UI().drawElement("tabs.receive", "new-btn-min-width").size, schema::UI().drawElement("tabs.receive", "new-btn-width").size * Layout::hScale(width)); + float dropdownW = width - copyBtnW - newBtnW - Layout::spacingSm() * 2; + ImGui::SetNextItemWidth(dropdownW); + ImGui::PushFont(Type().getFont(TypeStyle::Body2)); + if (ImGui::BeginCombo("##RecvAddr", s_source_preview.c_str())) { + if (!app->isConnected() || state.addresses.empty()) { + ImGui::TextDisabled("No addresses available"); + } else { + // Build filtered and sorted list + std::vector sortedIdx; + sortedIdx.reserve(state.addresses.size()); + for (size_t i = 0; i < state.addresses.size(); i++) { + bool isZ = state.addresses[i].type == "shielded"; + if (s_addr_type_filter == 1 && !isZ) continue; + if (s_addr_type_filter == 2 && isZ) continue; + sortedIdx.push_back(i); + } + std::sort(sortedIdx.begin(), sortedIdx.end(), + [&](size_t a, size_t b) { + return state.addresses[a].balance > state.addresses[b].balance; + }); + + if (sortedIdx.empty()) { + ImGui::TextDisabled("No addresses match filter"); + } else { + size_t addrTruncLen = static_cast(std::max(schema::UI().drawElement("tabs.receive", "addr-dropdown-trunc-min").size, width / schema::UI().drawElement("tabs.receive", "addr-dropdown-trunc-divisor").size)); + double now = ImGui::GetTime(); + + for (size_t si = 0; si < sortedIdx.size(); si++) { + size_t i = sortedIdx[si]; + const auto& addr = state.addresses[i]; + bool isCurrent = (s_selected_address_idx == static_cast(i)); + bool isZ = addr.type == "shielded"; + const char* tag = isZ ? "[Z]" : "[T]"; + + // Check for NEW badge + bool isNew = false; + auto newIt = s_new_address_timestamps.find(addr.address); + if (newIt != s_new_address_timestamps.end() && newIt->second > 0.0) { + double age = now - newIt->second; + if (age < schema::UI().drawElement("tabs.receive", "new-badge-timeout").size) isNew = true; + } + + // Check for label + auto lblIt = s_address_labels.find(addr.address); + bool hasLabel = (lblIt != s_address_labels.end() && !lblIt->second.empty()); + + std::string trunc = TruncateAddress(addr.address, addrTruncLen); + if (hasLabel) { + snprintf(buf, sizeof(buf), "%s %s (%s) \xe2\x80\x94 %.8f %s%s", + tag, lblIt->second.c_str(), trunc.c_str(), + addr.balance, DRAGONX_TICKER, + isNew ? " [NEW]" : ""); + } else { + snprintf(buf, sizeof(buf), "%s %s \xe2\x80\x94 %.8f %s%s", + tag, trunc.c_str(), addr.balance, DRAGONX_TICKER, + isNew ? " [NEW]" : ""); + } + + ImGui::PushID(static_cast(i)); + if (ImGui::Selectable(buf, isCurrent)) { + s_selected_address_idx = static_cast(i); + s_cached_qr_data.clear(); // Force QR regeneration + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("%s\nBalance: %.8f %s%s", + addr.address.c_str(), addr.balance, DRAGONX_TICKER, + isCurrent ? "\n(selected)" : ""); + } + ImGui::PopID(); + } + } + } + ImGui::EndCombo(); + } + ImGui::PopFont(); + + // Copy address button + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::BeginDisabled(!app->isConnected() || s_selected_address_idx < 0 || + s_selected_address_idx >= (int)state.addresses.size()); + if (TactileButton("Copy##recvAddr", ImVec2(copyBtnW, 0), schema::UI().resolveFont("button"))) { + if (s_selected_address_idx >= 0 && s_selected_address_idx < (int)state.addresses.size()) { + ImGui::SetClipboardText(state.addresses[s_selected_address_idx].address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + } + ImGui::EndDisabled(); + + // New address button on same line + ImGui::SameLine(0, Layout::spacingSm()); + ImGui::BeginDisabled(!app->isConnected()); + if (TactileButton("+ New##recv", ImVec2(newBtnW, 0), schema::UI().resolveFont("button"))) { + if (s_addr_type_filter != 2) { + app->createNewZAddress([](const std::string& addr) { + if (addr.empty()) + Notifications::instance().error("Failed to create new shielded address"); + else { + s_pending_select_address = addr; + Notifications::instance().success("New shielded address created"); + } + }); + } else { + app->createNewTAddress([](const std::string& addr) { + if (addr.empty()) + Notifications::instance().error("Failed to create new transparent address"); + else { + s_pending_select_address = addr; + Notifications::instance().success("New transparent address created"); + } + }); + } + } + ImGui::EndDisabled(); +} + +// ============================================================================ +// Helpers: timeAgo / DrawRecvIcon (local copies — originals are static in send_tab) +// ============================================================================ +static std::string recvTimeAgo(int64_t timestamp) { + if (timestamp <= 0) return ""; + int64_t now = (int64_t)std::time(nullptr); + int64_t diff = now - timestamp; + if (diff < 0) diff = 0; + if (diff < 60) return std::to_string(diff) + "s ago"; + if (diff < 3600) return std::to_string(diff / 60) + "m ago"; + if (diff < 86400) return std::to_string(diff / 3600) + "h ago"; + return std::to_string(diff / 86400) + "d ago"; +} + +static void DrawRecvIcon(ImDrawList* dl, float cx, float cy, float s, ImU32 col) { + dl->AddTriangleFilled( + ImVec2(cx, cy + s), + ImVec2(cx - s * 0.65f, cy - s * 0.3f), + ImVec2(cx + s * 0.65f, cy - s * 0.3f), col); + dl->AddRectFilled( + ImVec2(cx - s * 0.2f, cy - s * 0.8f), + ImVec2(cx + s * 0.2f, cy - s * 0.3f), col); +} + +// ============================================================================ +// Recent received transactions — styled to match transactions list +// ============================================================================ +static void RenderRecentReceived(ImDrawList* dl, const AddressInfo& /* addr */, + const WalletState& state, float width, + ImFont* capFont, App* app) { + ImGui::Dummy(ImVec2(0, Layout::spacingLg())); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT RECEIVED"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + float hs = Layout::hScale(width); + float glassRound = Layout::glassRounding(); + + ImFont* body2 = Type().body2(); + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd(); + float iconSz = std::max(schema::UI().drawElement("tabs.receive", "recent-icon-min-size").size, schema::UI().drawElement("tabs.receive", "recent-icon-size").size * hs); + ImU32 recvCol = Success(); + ImU32 greenCol = WithAlpha(Success(), (int)schema::UI().drawElement("tabs.receive", "recent-green-alpha").size); + float rowPadLeft = Layout::spacingLg(); + + // Collect matching transactions + std::vector recvs; + for (const auto& tx : state.transactions) { + if (tx.type != "receive") continue; + recvs.push_back(&tx); + if (recvs.size() >= (size_t)schema::UI().drawElement("tabs.receive", "max-recent-receives").size) break; + } + + if (recvs.empty()) { + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), "No recent receives"); + return; + } + + // Outer glass panel wrapping all rows + float itemSpacingY = ImGui::GetStyle().ItemSpacing.y; + float listH = rowH * (float)recvs.size() + itemSpacingY * (float)(recvs.size() - 1); + ImVec2 listPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 listPanelMax(listPanelMin.x + width, listPanelMin.y + listH); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + DrawGlassPanel(dl, listPanelMin, listPanelMax, glassSpec); + + // Clip draw commands to panel bounds to prevent overflow + dl->PushClipRect(listPanelMin, listPanelMax, true); + + char buf[64]; + for (size_t ri = 0; ri < recvs.size(); ri++) { + const auto& tx = *recvs[ri]; + + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowEnd(rowPos.x + width, rowPos.y + rowH); + + // Hover glow + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.receive", "row-hover-alpha").size), schema::UI().drawElement("tabs.receive", "row-hover-rounding").size); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) { + app->setCurrentPage(ui::NavPage::History); + } + } + + float cx = rowPos.x + rowPadLeft; + float cy = rowPos.y + Layout::spacingMd(); + + // Icon + DrawRecvIcon(dl, cx + iconSz, cy + body2->LegacySize * 0.5f, iconSz, recvCol); + + // Type label (first line) + float labelX = cx + iconSz * 2.0f + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy), recvCol, "Received"); + + // Time (next to type) + std::string ago = recvTimeAgo(tx.timestamp); + float typeW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, "Received").x; + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX + typeW + Layout::spacingLg(), cy), + OnSurfaceDisabled(), ago.c_str()); + + // Address (second line) + std::string addr_display = TruncateAddress(tx.address, (int)schema::UI().drawElement("tabs.receive", "recent-addr-trunc-len").size); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceMedium(), addr_display.c_str()); + + // Amount (right-aligned, first line) + snprintf(buf, sizeof(buf), "+%.8f", tx.amount); + ImVec2 amtSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, buf); + float amtX = rowPos.x + width - amtSz.x - Layout::spacingLg(); + DrawTextShadow(dl, body2, body2->LegacySize, ImVec2(amtX, cy), recvCol, buf, + schema::UI().drawElement("tabs.receive", "text-shadow-offset-x").size, schema::UI().drawElement("tabs.receive", "text-shadow-offset-y").size, IM_COL32(0, 0, 0, (int)schema::UI().drawElement("tabs.receive", "text-shadow-alpha").size)); + + // USD equivalent (right-aligned, second line) + double priceUsd = state.market.price_usd; + if (priceUsd > 0.0) { + double usdVal = tx.amount * priceUsd; + if (usdVal >= 1.0) + snprintf(buf, sizeof(buf), "$%.2f", usdVal); + else if (usdVal >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", usdVal); + else + snprintf(buf, sizeof(buf), "$%.6f", usdVal); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowPos.x + width - usdSz.x - Layout::spacingLg(), cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceDisabled(), buf); + } + + // Status badge + { + const char* statusStr; + ImU32 statusCol; + if (tx.confirmations == 0) { + statusStr = "Pending"; statusCol = Warning(); + } else if (tx.confirmations < (int)schema::UI().drawElement("tabs.receive", "confirmed-threshold").size) { + snprintf(buf, sizeof(buf), "%d conf", tx.confirmations); + statusStr = buf; statusCol = Warning(); + } else { + statusStr = "Confirmed"; statusCol = greenCol; + } + ImVec2 sSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, statusStr); + float statusX = amtX - sSz.x - Layout::spacingXxl(); + float minStatusX = cx + width * schema::UI().drawElement("tabs.receive", "status-min-x-ratio").size; + if (statusX < minStatusX) statusX = minStatusX; + ImU32 pillBg = (statusCol & 0x00FFFFFFu) | (static_cast((int)schema::UI().drawElement("tabs.receive", "status-pill-bg-alpha").size) << 24); + ImVec2 pillMin(statusX - Layout::spacingSm(), cy + body2->LegacySize + (int)schema::UI().drawElement("tabs.receive", "status-pill-y-offset").size); + ImVec2 pillMax(statusX + sSz.x + Layout::spacingSm(), pillMin.y + capFont->LegacySize + Layout::spacingXs()); + dl->AddRectFilled(pillMin, pillMax, pillBg, schema::UI().drawElement("tabs.receive", "status-pill-rounding").size); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(statusX, cy + body2->LegacySize + Layout::spacingXs()), statusCol, statusStr); + } + + ImGui::Dummy(ImVec2(0, rowH)); + + // Subtle divider between rows + if (ri < recvs.size() - 1) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(divStart.x + rowPadLeft + iconSz * 2.0f, divStart.y), + ImVec2(divStart.x + width - Layout::spacingLg(), divStart.y), + IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.receive", "row-divider-alpha").size)); + } + } + + dl->PopClipRect(); +} + +// ============================================================================ +// MAIN: RenderReceiveTab +// ============================================================================ +void RenderReceiveTab(App* app) +{ + const auto& state = app->getWalletState(); + auto& S = schema::UI(); + + RenderSyncBanner(state); + + ImVec2 recvAvail = ImGui::GetContentRegionAvail(); + float hs = Layout::hScale(recvAvail.x); + float vScale = Layout::vScale(recvAvail.y); + float glassRound = Layout::glassRounding(); + + float availWidth = recvAvail.x; + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* body2 = Type().body2(); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + + float sectionGap = Layout::spacingXl() * vScale; + char buf[128]; + + // ================================================================ + // NON-SCROLLING CONTENT — resizes to fit available height + // ================================================================ + ImVec2 formAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##ReceiveScroll", formAvail, false, + ImGuiWindowFlags_NoBackground); + dl = ImGui::GetWindowDrawList(); + + // Top-aligned content — consistent vertical position across all tabs + static float s_recvContentH = 0; + float scrollAvailH = ImGui::GetContentRegionAvail().y; + float groupStartY = ImGui::GetCursorPosY(); + float contentStartY = ImGui::GetCursorPosY(); + + float formAvailW = ImGui::GetContentRegionAvail().x; + float formW = formAvailW; + ImGui::BeginGroup(); + + // ================================================================ + // Not connected / empty state + // ================================================================ + if (!app->isConnected()) { + ImVec2 emptyMin = ImGui::GetCursorScreenPos(); + float emptyH = std::max(schema::UI().drawElement("tabs.receive", "empty-state-min-height").size, schema::UI().drawElement("tabs.receive", "empty-state-height").size * Layout::vScale()); + ImVec2 emptyMax(emptyMin.x + formW, emptyMin.y + emptyH); + DrawGlassPanel(dl, emptyMin, emptyMax, glassSpec); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(emptyMin.x + Layout::spacingXl(), emptyMin.y + Layout::spacingXl()), + OnSurfaceDisabled(), "Waiting for daemon connection..."); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(emptyMin.x + Layout::spacingXl(), emptyMin.y + Layout::spacingXl() + sub1->LegacySize + S.drawElement("tabs.receive", "empty-state-subtitle-gap").size), + OnSurfaceDisabled(), "Your receiving addresses will appear here once connected."); + ImGui::Dummy(ImVec2(formW, emptyH)); + ImGui::EndGroup(); + ImGui::EndChild(); + return; + } + + if (state.addresses.empty()) { + ImVec2 emptyMin = ImGui::GetCursorScreenPos(); + float emptyH = S.drawElement("tabs.receive", "skeleton-height").size; + ImVec2 emptyMax(emptyMin.x + formW, emptyMin.y + emptyH); + DrawGlassPanel(dl, emptyMin, emptyMax, glassSpec); + float alpha = (float)(schema::UI().drawElement("animations", "skeleton-base").size + schema::UI().drawElement("animations", "skeleton-amp").size * std::sin(ImGui::GetTime() * schema::UI().drawElement("animations", "pulse-speed-slow").size)); + ImU32 skelCol = IM_COL32(255, 255, 255, (int)(alpha * 255)); + dl->AddRectFilled( + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + Layout::spacingLg()), + ImVec2(emptyMin.x + formW * S.drawElement("tabs.receive", "skeleton-bar1-width-ratio").size, emptyMin.y + Layout::spacingLg() + S.drawElement("tabs.receive", "skeleton-bar1-height").size), + skelCol, schema::UI().drawElement("tabs.receive", "skeleton-rounding").size); + dl->AddRectFilled( + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + Layout::spacingLg() + S.drawElement("tabs.receive", "skeleton-bar2-top").size), + ImVec2(emptyMin.x + formW * S.drawElement("tabs.receive", "skeleton-bar2-width-ratio").size, emptyMin.y + Layout::spacingLg() + S.drawElement("tabs.receive", "skeleton-bar2-bottom").size), + skelCol, schema::UI().drawElement("tabs.receive", "skeleton-rounding").size); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + emptyH - S.drawElement("tabs.receive", "skeleton-text-bottom-offset").size), + OnSurfaceDisabled(), "Loading addresses..."); + ImGui::Dummy(ImVec2(formW, emptyH)); + ImGui::EndGroup(); + ImGui::EndChild(); + return; + } + + // Ensure valid selection + if (s_selected_address_idx < 0 || + s_selected_address_idx >= (int)state.addresses.size()) { + s_selected_address_idx = 0; + } + + const AddressInfo& selected = state.addresses[s_selected_address_idx]; + bool isZ = selected.type == "shielded"; + + // Generate QR data + std::string qr_data = selected.address; + if (s_request_amount > 0) { + qr_data = std::string("dragonx:") + selected.address + + "?amount=" + std::to_string(s_request_amount); + if (s_request_memo[0] && isZ) { + qr_data += "&memo=" + std::string(s_request_memo); + } + } + if (qr_data != s_cached_qr_data) { + if (s_qr_texture) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } + int w, h; + s_qr_texture = GenerateQRTexture(qr_data.c_str(), &w, &h); + s_cached_qr_data = qr_data; + } + + // ================================================================ + // MAIN CARD — single glass panel (channel split like Send tab) + // ================================================================ + { + ImVec2 containerMin = ImGui::GetCursorScreenPos(); + float pad = Layout::spacingLg(); + float innerW = formW - pad * 2; + float innerGap = Layout::spacingLg(); + + // Channel split: content on ch1, glass background on ch0 + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + + ImGui::Indent(pad); + ImGui::Dummy(ImVec2(0, pad)); // top padding + + // ---- ADDRESS DROPDOWN + QR CODE — side by side ---- + { + float qrColW = innerW * schema::UI().drawElement("tabs.receive", "qr-col-width-ratio").size; + float colGap = Layout::spacingLg(); + float addrColW = innerW - qrColW - colGap; + float qrColX = containerMin.x + pad + addrColW + colGap; + ImVec2 sectionTop = ImGui::GetCursorScreenPos(); + + // LEFT: ADDRESS DROPDOWN + PAYMENT REQUEST + { + // Address dropdown replaces the old address display panel + RenderAddressDropdown(app, addrColW); + + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + + // ---- PAYMENT REQUEST ---- + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "PAYMENT REQUEST"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Amount input with currency toggle + float toggleW = S.drawElement("tabs.receive", "currency-toggle-width").size; + float amtInputW = addrColW - toggleW - Layout::spacingMd(); + if (amtInputW < S.drawElement("tabs.receive", "amount-input-min-width").size) amtInputW = S.drawElement("tabs.receive", "amount-input-min-width").size; + double usd_price = state.market.price_usd; + + ImGui::PushFont(body2); + if (s_request_usd_mode && usd_price > 0) { + ImGui::PushItemWidth(amtInputW); + if (ImGui::InputDouble("##RequestAmountUSD", &s_request_usd_amount, 0, 0, "$%.2f")) { + s_request_amount = s_request_usd_amount / usd_price; + } + { + ImVec2 iMin = ImGui::GetItemRectMin(); + ImVec2 iMax = ImGui::GetItemRectMax(); + snprintf(buf, sizeof(buf), "\xe2\x89\x88 %.4f %s", s_request_amount, DRAGONX_TICKER); + ImVec2 sz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float tx = iMax.x - sz.x - ImGui::GetStyle().FramePadding.x; + float ty = iMin.y + (iMax.y - iMin.y - sz.y) * 0.5f; + dl->AddText(capFont, capFont->LegacySize, ImVec2(tx, ty), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "input-overlay-text-alpha").size), buf); + } + ImGui::PopItemWidth(); + } else { + ImGui::PushItemWidth(amtInputW); + if (ImGui::InputDouble("##RequestAmount", &s_request_amount, 0, 0, "%.8f")) { + if (usd_price > 0) + s_request_usd_amount = s_request_amount * usd_price; + } + if (usd_price > 0 && s_request_amount > 0) { + ImVec2 iMin = ImGui::GetItemRectMin(); + ImVec2 iMax = ImGui::GetItemRectMax(); + double usd_value = s_request_amount * usd_price; + if (usd_value >= 0.01) + snprintf(buf, sizeof(buf), "\xe2\x89\x88 $%.2f", usd_value); + else + snprintf(buf, sizeof(buf), "\xe2\x89\x88 $%.6f", usd_value); + ImVec2 sz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float tx = iMax.x - sz.x - ImGui::GetStyle().FramePadding.x; + float ty = iMin.y + (iMax.y - iMin.y - sz.y) * 0.5f; + dl->AddText(capFont, capFont->LegacySize, ImVec2(tx, ty), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "input-overlay-text-alpha").size), buf); + } + ImGui::PopItemWidth(); + } + + // Toggle button + ImGui::SameLine(0, Layout::spacingMd()); + { + const char* currLabel = s_request_usd_mode ? "DRGX" : "USD"; + bool canToggle = (usd_price > 0); + ImGui::BeginDisabled(!canToggle); + if (TactileButton("##ToggleCurrencyRecv", ImVec2(toggleW, 0), S.resolveFont("button"))) { + s_request_usd_mode = !s_request_usd_mode; + if (s_request_usd_mode && usd_price > 0) + s_request_usd_amount = s_request_amount * usd_price; + } + { + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + float bH = bMax.y - bMin.y; + ImFont* font = ImGui::GetFont(); + ImVec2 textSz = font->CalcTextSizeA(font->LegacySize, 10000, 0, currLabel); + float iconW = schema::UI().drawElement("tabs.receive", "currency-icon-width").size; + float iconGap2 = schema::UI().drawElement("tabs.receive", "currency-icon-gap").size; + float totalW2 = iconW + iconGap2 + textSz.x; + float startX = bMin.x + ((bMax.x - bMin.x) - totalW2) * 0.5f; + float cy = bMin.y + bH * 0.5f; + ImU32 iconCol = ImGui::GetColorU32(ImGuiCol_Text); + float ss = iconW * 0.5f; + float cx = startX + ss; + float ag = S.drawElement("tabs.receive", "swap-icon-arrow-gap").size; + float al = ss * S.drawElement("tabs.receive", "swap-icon-arrow-length-ratio").size; + float hss = S.drawElement("tabs.receive", "swap-icon-arrowhead-size").size; + float ay1 = cy - ag; + dl->AddLine(ImVec2(cx - al, ay1), ImVec2(cx + al, ay1), iconCol, S.drawElement("tabs.receive", "swap-icon-line-thickness").size); + dl->AddTriangleFilled( + ImVec2(cx + al, ay1), + ImVec2(cx + al - hss, ay1 - hss), + ImVec2(cx + al - hss, ay1 + hss), iconCol); + float ay2 = cy + ag; + dl->AddLine(ImVec2(cx + al, ay2), ImVec2(cx - al, ay2), iconCol, S.drawElement("tabs.receive", "swap-icon-line-thickness").size); + dl->AddTriangleFilled( + ImVec2(cx - al, ay2), + ImVec2(cx - al + hss, ay2 - hss), + ImVec2(cx - al + hss, ay2 + hss), iconCol); + float tx = startX + iconW + iconGap2; + float ty = cy - textSz.y * 0.5f; + dl->AddText(font, font->LegacySize, ImVec2(tx, ty), iconCol, currLabel); + } + ImGui::EndDisabled(); + } + ImGui::PopFont(); + + // Preset amount chips + { + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + float chipRound = schema::UI().drawElement("tabs.receive", "chip-rounding").size; + float chipGap = schema::UI().drawElement("tabs.receive", "chip-gap").size; + float chipH = schema::UI().drawElement("tabs.receive", "chip-height").size; + + struct Preset { const char* label; double amount; }; + Preset presets[] = { + { "0.1", 0.1 }, + { "1", 1.0 }, + { "10", 10.0 }, + { "100", 100.0 }, + { "1K", 1000.0 }, + { "10K", 10000.0 }, + { "50K", 50000.0 }, + { "100K", 100000.0 }, + }; + constexpr int presetCount = 8; + + // Calculate equal chip widths to span full addrColW + float totalGap = chipGap * (presetCount - 1); + float chipW = (addrColW - totalGap) / presetCount; + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, chipRound); + + ImFont* chipFont = S.resolveFont("button"); + + for (int ci = 0; ci < presetCount; ci++) { + if (ci > 0) ImGui::SameLine(0, chipGap); + + bool active = false; + if (s_request_usd_mode) { + active = (usd_price > 0 && std::abs(s_request_usd_amount - presets[ci].amount) < 0.001); + } else { + active = (std::abs(s_request_amount - presets[ci].amount) < 1e-8); + } + + if (active) { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "chip-active-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(Primary())); + } + + char chipId[32]; + snprintf(chipId, sizeof(chipId), "%s##presetAmt%d", presets[ci].label, ci); + if (TactileButton(chipId, ImVec2(chipW, chipH), chipFont)) { + if (s_request_usd_mode) { + s_request_usd_amount = presets[ci].amount; + if (usd_price > 0) + s_request_amount = s_request_usd_amount / usd_price; + } else { + s_request_amount = presets[ci].amount; + if (usd_price > 0) + s_request_usd_amount = s_request_amount * usd_price; + } + } + + if (active) ImGui::PopStyleColor(2); + } + + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + } + + // Memo (z-addresses only) + if (isZ) { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MEMO (OPTIONAL)"); + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.receive", "memo-label-gap").size)); + + float memoInputH = std::max(schema::UI().drawElement("tabs.receive", "memo-input-min-height").size, schema::UI().drawElement("tabs.receive", "memo-input-height").size * vScale); + ImGui::PushItemWidth(addrColW); + ImGui::InputTextMultiline("##RequestMemo", s_request_memo, sizeof(s_request_memo), + ImVec2(addrColW, memoInputH)); + ImGui::PopItemWidth(); + + size_t memo_len = strlen(s_request_memo); + snprintf(buf, sizeof(buf), "%zu / %d", memo_len, (int)S.drawElement("tabs.receive", "memo-max-display-chars").size); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + + // URI preview + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + if (s_request_amount > 0 && !s_cached_qr_data.empty()) { + float uriWrapW = addrColW; + dl->AddText(capFont, capFont->LegacySize, ImGui::GetCursorScreenPos(), + OnSurfaceDisabled(), s_cached_qr_data.c_str(), nullptr, uriWrapW); + ImVec2 uriSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, + uriWrapW, s_cached_qr_data.c_str()); + ImGui::Dummy(ImVec2(addrColW, uriSz.y + Layout::spacingSm())); + } else { + ImGui::Dummy(ImVec2(addrColW, capFont->LegacySize + Layout::spacingSm())); + } + + // Clear button + { + bool hasData = (s_request_amount > 0 || s_request_memo[0]); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "clear-btn-hover-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, + ImGui::ColorConvertU32ToFloat4(hasData ? OnSurfaceMedium() : OnSurfaceDisabled())); + ImGui::BeginDisabled(!hasData); + if (TactileSmallButton("Clear Request##recv", S.resolveFont("button"))) { + s_request_amount = 0.0; + s_request_usd_amount = 0.0; + s_request_memo[0] = '\0'; + } + ImGui::EndDisabled(); + ImGui::PopStyleColor(3); + } + } + float leftBottom = ImGui::GetCursorScreenPos().y; + + // RIGHT: QR CODE + { + float qrAvailW = qrColW; + float rx = qrColX; + float ry = sectionTop.y; + + float maxQrSize = std::min(qrAvailW - Layout::spacingMd() * 2, S.drawElement("tabs.receive", "qr-max-size").size); + float qrSize = std::max(S.drawElement("tabs.receive", "qr-min-size").size, maxQrSize); + float qrPadding = Layout::spacingMd(); + float totalQrSize = qrSize + qrPadding * 2; + float qrOffsetX = std::max(0.0f, (qrAvailW - totalQrSize) * 0.5f); + ImVec2 qrPanelMin(rx + qrOffsetX, ry); + ImVec2 qrPanelMax(qrPanelMin.x + totalQrSize, qrPanelMin.y + totalQrSize); + + GlassPanelSpec qrGlass; + qrGlass.rounding = glassRound * S.drawElement("tabs.receive", "qr-glass-rounding-ratio").size; + qrGlass.fillAlpha = (int)S.drawElement("tabs.receive", "qr-glass-fill-alpha").size; + qrGlass.borderAlpha = (int)S.drawElement("tabs.receive", "qr-glass-border-alpha").size; + DrawGlassPanel(dl, qrPanelMin, qrPanelMax, qrGlass); + + ImGui::SetCursorScreenPos(ImVec2(qrPanelMin.x + qrPadding, qrPanelMin.y + qrPadding)); + if (s_qr_texture) { + RenderQRCode(s_qr_texture, qrSize); + } else { + ImGui::Dummy(ImVec2(qrSize, qrSize)); + ImVec2 textPos(qrPanelMin.x + totalQrSize * 0.5f - S.drawElement("tabs.receive", "qr-unavailable-text-offset").size, + qrPanelMin.y + totalQrSize * 0.5f); + dl->AddText(capFont, capFont->LegacySize, textPos, + OnSurfaceDisabled(), "QR unavailable"); + } + + ImGui::SetCursorScreenPos(qrPanelMin); + ImGui::InvisibleButton("##QRClickCopy", ImVec2(totalQrSize, totalQrSize)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy %s", + s_request_amount > 0 ? "payment URI" : "address"); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(qr_data.c_str()); + Notifications::instance().info(s_request_amount > 0 + ? "Payment URI copied" : "Address copied"); + } + + ImGui::SetCursorScreenPos(ImVec2(rx, qrPanelMax.y)); + ImGui::Dummy(ImVec2(qrAvailW, 0)); + } + float rightBottom = ImGui::GetCursorScreenPos().y; + float sectionBottom = std::max(leftBottom, rightBottom); + ImGui::SetCursorScreenPos(ImVec2(containerMin.x + pad, sectionBottom)); + ImGui::Dummy(ImVec2(innerW, 0)); + } + + // Divider before action buttons + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + { + ImVec2 divPos = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(containerMin.x + pad, divPos.y), + ImVec2(containerMin.x + formW - pad, divPos.y), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.receive", "divider-thickness").size); + } + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + + // ---- ACTION BUTTONS (inside card) ---- + { + float btnGap = Layout::spacingMd(); + float btnH = std::max(schema::UI().drawElement("tabs.receive", "action-btn-min-height").size, schema::UI().drawElement("tabs.receive", "action-btn-height").size * vScale); + float otherBtnW = std::max(S.drawElement("tabs.receive", "action-btn-min-width").size, innerW * S.drawElement("tabs.receive", "action-btn-width-ratio").size); + + bool firstBtn = true; + + if (s_request_amount > 0) { + if (!firstBtn) ImGui::SameLine(0, btnGap); + firstBtn = false; + if (TactileButton("Copy URI##recv", ImVec2(otherBtnW, btnH), S.resolveFont("button"))) { + ImGui::SetClipboardText(s_cached_qr_data.c_str()); + Notifications::instance().info("Payment URI copied"); + } + } + + if (s_request_amount > 0) { + if (!firstBtn) ImGui::SameLine(0, btnGap); + firstBtn = false; + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "btn-hover-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(PrimaryLight())); + if (TactileButton("Share##recv", ImVec2(otherBtnW, btnH), S.resolveFont("button"))) { + char shareBuf[1024]; + snprintf(shareBuf, sizeof(shareBuf), + "Payment Request\nAmount: %.8f %s\nAddress: %s\nURI: %s", + s_request_amount, DRAGONX_TICKER, + selected.address.c_str(), s_cached_qr_data.c_str()); + ImGui::SetClipboardText(shareBuf); + Notifications::instance().info("Payment request copied"); + } + ImGui::PopStyleColor(3); + } + + if (!firstBtn) ImGui::SameLine(0, btnGap); + firstBtn = false; + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "btn-hover-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Border, ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, S.drawElement("tabs.receive", "explorer-btn-border-size").size); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(PrimaryLight())); + if (TactileButton("Explorer##recv", ImVec2(otherBtnW, btnH), S.resolveFont("button"))) { + OpenExplorerURL(selected.address); + } + ImGui::PopStyleVar(); // FrameBorderSize + ImGui::PopStyleColor(4); + + if (selected.balance > 0) { + if (!firstBtn) ImGui::SameLine(0, btnGap); + firstBtn = false; + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.receive", "btn-hover-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium())); + if (TactileButton("Send \xe2\x86\x97##recv", ImVec2(otherBtnW, btnH), S.resolveFont("button"))) { + SetSendFromAddress(selected.address); + app->setCurrentPage(NavPage::Send); + } + ImGui::PopStyleColor(3); + } + + } + + // Bottom padding + ImGui::Dummy(ImVec2(0, pad)); + ImGui::Unindent(pad); + + // Enforce shared card height (matches QR-driven target) + { + float currentCardH = ImGui::GetCursorScreenPos().y - containerMin.y; + float targetCardH = Layout::mainCardTargetH(formW, vScale); + if (currentCardH < targetCardH) + ImGui::Dummy(ImVec2(0, targetCardH - currentCardH)); + } + + // Draw glass panel background on channel 0 + ImVec2 containerMax(containerMin.x + formW, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, containerMin, containerMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(containerMin.x, containerMax.y)); + ImGui::Dummy(ImVec2(formW, 0)); + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + } + + // ================================================================ + // RECENT RECEIVED + // ================================================================ + RenderRecentReceived(dl, selected, state, formW, capFont, app); + + ImGui::EndGroup(); + float measuredH = ImGui::GetCursorPosY() - contentStartY; + s_recvContentH = std::round(measuredH); + ImGui::EndChild(); // ##ReceiveScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/receive_tab.cpp.bak3 b/src/ui/windows/receive_tab.cpp.bak3 new file mode 100644 index 0000000..3a344c0 --- /dev/null +++ b/src/ui/windows/receive_tab.cpp.bak3 @@ -0,0 +1,934 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// Layout G: QR-Centered Hero +// - QR code dominates center as hero element +// - Address info wraps around the QR +// - Payment request section below QR +// - Horizontal address strip at bottom for fast switching + +#include "receive_tab.h" +#include "send_tab.h" +#include "../../app.h" +#include "../../version.h" +#include "../../wallet_state.h" +#include "../../ui/widgets/qr_code.h" +#include "../sidebar.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../notifications.h" +#include "imgui.h" + +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ============================================================================ +// State +// ============================================================================ +static int s_selected_address_idx = -1; +static double s_request_amount = 0.0; +static char s_request_memo[256] = ""; +static std::string s_cached_qr_data; +static uintptr_t s_qr_texture = 0; +static bool s_payment_request_open = false; + +// Track newly created addresses for NEW badge +static std::map s_new_address_timestamps; +static size_t s_prev_address_count = 0; + +// Address labels (in-memory until persistent config) +static std::map s_address_labels; +static char s_label_edit_buf[64] = ""; + +// Address type filter +static int s_addr_type_filter = 0; // 0=All, 1=Z, 2=T + +// ============================================================================ +// Helpers +// ============================================================================ +static std::string TruncateAddress(const std::string& addr, size_t maxLen = 35) { + if (addr.length() <= maxLen) return addr; + size_t halfLen = (maxLen - 3) / 2; + return addr.substr(0, halfLen) + "..." + addr.substr(addr.length() - halfLen); +} + +static void OpenExplorerURL(const std::string& address) { + std::string url = "https://explorer.dragonx.com/address/" + address; +#ifdef _WIN32 + std::string cmd = "start \"\" \"" + url + "\""; +#elif __APPLE__ + std::string cmd = "open \"" + url + "\""; +#else + std::string cmd = "xdg-open \"" + url + "\""; +#endif + system(cmd.c_str()); +} + +// ============================================================================ +// Sync banner +// ============================================================================ +static void RenderSyncBanner(const WalletState& state) { + if (!state.sync.syncing || state.sync.isSynced()) return; + + float syncPct = (state.sync.headers > 0) + ? (float)state.sync.blocks / state.sync.headers * 100.0f : 0.0f; + char syncBuf[128]; + snprintf(syncBuf, sizeof(syncBuf), + "Blockchain syncing (%.1f%%)... Balances may be inaccurate.", syncPct); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.6f, 0.4f, 0.0f, 0.15f)); + ImGui::BeginChild("##SyncBannerRecv", ImVec2(ImGui::GetContentRegionAvail().x, 28), + false, ImGuiWindowFlags_NoScrollbar); + ImGui::SetCursorPos(ImVec2(Layout::spacingLg(), 6)); + Type().textColored(TypeStyle::Caption, Warning(), syncBuf); + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Track new addresses (detect creations) +// ============================================================================ +static void TrackNewAddresses(const WalletState& state) { + if (state.addresses.size() > s_prev_address_count && s_prev_address_count > 0) { + for (const auto& a : state.addresses) { + if (s_new_address_timestamps.find(a.address) == s_new_address_timestamps.end()) { + s_new_address_timestamps[a.address] = ImGui::GetTime(); + } + } + } else if (s_prev_address_count == 0) { + for (const auto& a : state.addresses) { + s_new_address_timestamps[a.address] = 0.0; + } + } + s_prev_address_count = state.addresses.size(); +} + +// ============================================================================ +// Build sorted address groups +// ============================================================================ +struct AddressGroups { + std::vector shielded; + std::vector transparent; +}; + +static AddressGroups BuildSortedAddressGroups(const WalletState& state) { + AddressGroups groups; + for (int i = 0; i < (int)state.addresses.size(); i++) { + if (state.addresses[i].type == "shielded") + groups.shielded.push_back(i); + else + groups.transparent.push_back(i); + } + std::sort(groups.shielded.begin(), groups.shielded.end(), [&](int a, int b) { + return state.addresses[a].balance > state.addresses[b].balance; + }); + std::sort(groups.transparent.begin(), groups.transparent.end(), [&](int a, int b) { + return state.addresses[a].balance > state.addresses[b].balance; + }); + return groups; +} + +// ============================================================================ +// QR Hero — the centerpiece of Layout G +// ============================================================================ +static void RenderQRHero(App* app, ImDrawList* dl, const AddressInfo& addr, + float width, float qrSize, + const std::string& qr_data, + const GlassPanelSpec& glassSpec, + const WalletState& state, + ImFont* sub1, ImFont* /*body2*/, ImFont* capFont) { + char buf[128]; + bool isZ = addr.type == "shielded"; + ImU32 typeCol = isZ ? IM_COL32(77, 204, 77, 255) : IM_COL32(204, 170, 51, 255); + const char* typeBadge = isZ ? "Shielded" : "Transparent"; + + float qrPadding = Layout::spacingLg(); + float totalQrSize = qrSize + qrPadding * 2; + float heroH = totalQrSize + 80.0f; // QR + info below + + ImVec2 heroMin = ImGui::GetCursorScreenPos(); + ImVec2 heroMax(heroMin.x + width, heroMin.y + heroH); + GlassPanelSpec heroGlass = glassSpec; + heroGlass.fillAlpha = 16; + heroGlass.borderAlpha = 35; + DrawGlassPanel(dl, heroMin, heroMax, heroGlass); + + // --- Address info bar above QR --- + float infoBarH = 32.0f; + float cx = heroMin.x + Layout::spacingLg(); + float cy = heroMin.y + Layout::spacingSm(); + + // Type badge circle + label + dl->AddCircleFilled(ImVec2(cx + 8, cy + 10), 8.0f, IM_COL32(255, 255, 255, 20)); + const char* typeChar = isZ ? "Z" : "T"; + ImVec2 tcSz = sub1->CalcTextSizeA(sub1->LegacySize, 100, 0, typeChar); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(cx + 8 - tcSz.x * 0.5f, cy + 10 - tcSz.y * 0.5f), + typeCol, typeChar); + + // Education tooltip on badge + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + ImGui::InvisibleButton("##TypeBadgeHero", ImVec2(22, 22)); + if (ImGui::IsItemHovered()) { + if (isZ) { + ImGui::SetTooltip( + "Shielded Address (Z)\n" + "- Full transaction privacy\n" + "- Encrypted sender, receiver, amount\n" + "- Supports encrypted memos\n" + "- Recommended for privacy"); + } else { + ImGui::SetTooltip( + "Transparent Address (T)\n" + "- Publicly visible on blockchain\n" + "- Similar to Bitcoin addresses\n" + "- No memo support\n" + "- Use Z addresses for privacy"); + } + } + + // Type label text + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx + 24, cy + 4), typeCol, typeBadge); + + // Balance right-aligned + snprintf(buf, sizeof(buf), "%.8f %s", addr.balance, DRAGONX_TICKER); + ImVec2 balSz = sub1->CalcTextSizeA(sub1->LegacySize, 10000, 0, buf); + float balX = heroMax.x - balSz.x - Layout::spacingLg(); + DrawTextShadow(dl, sub1, sub1->LegacySize, ImVec2(balX, cy + 2), typeCol, buf); + + // USD value + if (state.market.price_usd > 0 && addr.balance > 0) { + double usd = addr.balance * state.market.price_usd; + snprintf(buf, sizeof(buf), "\xe2\x89\x88 $%.2f", usd); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(heroMax.x - usdSz.x - Layout::spacingLg(), cy + sub1->LegacySize + 4), + OnSurfaceDisabled(), buf); + } + + // --- QR Code centered --- + float qrOffset = (width - totalQrSize) * 0.5f; + ImVec2 qrPanelMin(heroMin.x + qrOffset, heroMin.y + infoBarH + Layout::spacingSm()); + ImVec2 qrPanelMax(qrPanelMin.x + totalQrSize, qrPanelMin.y + totalQrSize); + + // Subtle inner panel for QR + GlassPanelSpec qrGlass; + qrGlass.rounding = glassSpec.rounding * 0.75f; + qrGlass.fillAlpha = 12; + qrGlass.borderAlpha = 25; + DrawGlassPanel(dl, qrPanelMin, qrPanelMax, qrGlass); + + ImGui::SetCursorScreenPos(ImVec2(qrPanelMin.x + qrPadding, qrPanelMin.y + qrPadding)); + if (s_qr_texture) { + RenderQRCode(s_qr_texture, qrSize); + } else { + ImGui::Dummy(ImVec2(qrSize, qrSize)); + ImVec2 textPos(qrPanelMin.x + totalQrSize * 0.5f - 50, + qrPanelMin.y + totalQrSize * 0.5f); + dl->AddText(capFont, capFont->LegacySize, textPos, + OnSurfaceDisabled(), "QR unavailable"); + } + + // Click QR to copy + ImGui::SetCursorScreenPos(qrPanelMin); + ImGui::InvisibleButton("##QRClickCopy", ImVec2(totalQrSize, totalQrSize)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy %s", + s_request_amount > 0 ? "payment URI" : "address"); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(qr_data.c_str()); + Notifications::instance().info(s_request_amount > 0 + ? "Payment URI copied to clipboard" + : "Address copied to clipboard"); + } + + // --- Address strip below QR --- + float addrStripY = qrPanelMax.y + Layout::spacingMd(); + float addrStripX = heroMin.x + Layout::spacingLg(); + float addrStripW = width - Layout::spacingXxl(); + + // Full address (word-wrapped) + ImVec2 fullAddrPos(addrStripX, addrStripY); + float wrapWidth = addrStripW; + ImVec2 addrSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, + wrapWidth, addr.address.c_str()); + dl->AddText(capFont, capFont->LegacySize, fullAddrPos, + OnSurface(), addr.address.c_str(), nullptr, wrapWidth); + + // Address click-to-copy overlay + ImGui::SetCursorScreenPos(fullAddrPos); + ImGui::InvisibleButton("##addrCopyHero", ImVec2(wrapWidth, addrSz.y)); + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Click to copy address"); + } + if (ImGui::IsItemClicked()) { + ImGui::SetClipboardText(addr.address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + + // Action buttons row + float btnRowY = addrStripY + addrSz.y + Layout::spacingMd(); + ImGui::SetCursorScreenPos(ImVec2(addrStripX, btnRowY)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, Layout::spacingSm()); + { + // Copy — primary (uses global glass style) + if (TactileSmallButton("Copy Address##hero", schema::UI().resolveFont("button"))) { + ImGui::SetClipboardText(addr.address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + + ImGui::SameLine(); + + // Explorer + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 15))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(PrimaryLight())); + if (TactileSmallButton("Explorer##hero", schema::UI().resolveFont("button"))) { + OpenExplorerURL(addr.address); + } + ImGui::PopStyleColor(3); + + // Send From + if (addr.balance > 0) { + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, + ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 15))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurfaceMedium())); + if (TactileSmallButton("Send \xe2\x86\x97##hero", schema::UI().resolveFont("button"))) { + SetSendFromAddress(addr.address); + app->setCurrentPage(NavPage::Send); + } + ImGui::PopStyleColor(3); + } + + // Label editor (inline) + ImGui::SameLine(0, Layout::spacingXl()); + auto lblIt = s_address_labels.find(addr.address); + std::string currentLabel = (lblIt != s_address_labels.end()) ? lblIt->second : ""; + snprintf(s_label_edit_buf, sizeof(s_label_edit_buf), "%s", currentLabel.c_str()); + ImGui::SetNextItemWidth(std::min(200.0f, addrStripW * 0.3f)); + if (ImGui::InputTextWithHint("##LabelHero", "Add label...", + s_label_edit_buf, sizeof(s_label_edit_buf))) { + s_address_labels[addr.address] = std::string(s_label_edit_buf); + } + } + ImGui::PopStyleVar(); + + // Update hero height based on actual content + float actualBottom = btnRowY + 24; + heroH = actualBottom - heroMin.y + Layout::spacingMd(); + heroMax.y = heroMin.y + heroH; + + ImGui::SetCursorScreenPos(ImVec2(heroMin.x, heroMax.y)); + ImGui::Dummy(ImVec2(width, 0)); +} + +// ============================================================================ +// Payment request section (below QR hero) +// ============================================================================ +static void RenderPaymentRequest(ImDrawList* dl, const AddressInfo& addr, + float innerW, const GlassPanelSpec& glassSpec, + const char* suffix) { + auto& S = schema::UI(); + const float kLabelPos = S.label("tabs.receive", "label-column").position; + bool hasMemo = (addr.type == "shielded"); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "PAYMENT REQUEST"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Compute card height + float prCardH = 16.0f + 24.0f + 8.0f + 12.0f; + if (hasMemo) prCardH += 24.0f; + if (s_request_amount > 0 && !s_cached_qr_data.empty()) { + ImFont* capF = Type().caption(); + ImVec2 uriSz = capF->CalcTextSizeA(capF->LegacySize, FLT_MAX, + innerW - 24, s_cached_qr_data.c_str()); + prCardH += uriSz.y + 8.0f; + } + if (s_request_amount > 0) prCardH += 32.0f; + if (s_request_amount > 0 || s_request_memo[0]) prCardH += 4.0f; + + ImVec2 prMin = ImGui::GetCursorScreenPos(); + ImVec2 prMax(prMin.x + innerW, prMin.y + prCardH); + DrawGlassPanel(dl, prMin, prMax, glassSpec); + + ImGui::SetCursorScreenPos(ImVec2(prMin.x + Layout::spacingLg(), prMin.y + Layout::spacingMd())); + ImGui::Dummy(ImVec2(0, 0)); + + ImGui::Text("Amount:"); + ImGui::SameLine(kLabelPos); + ImGui::SetNextItemWidth(std::max(S.input("tabs.receive", "amount-input").width, innerW * 0.4f)); + char amtId[32]; + snprintf(amtId, sizeof(amtId), "##RequestAmount%s", suffix); + ImGui::InputDouble(amtId, &s_request_amount, 0.01, 1.0, "%.8f"); + ImGui::SameLine(); + ImGui::Text("%s", DRAGONX_TICKER); + + if (hasMemo) { + ImGui::Text("Memo:"); + ImGui::SameLine(kLabelPos); + ImGui::SetNextItemWidth(innerW - kLabelPos - Layout::spacingXxl()); + char memoId[32]; + snprintf(memoId, sizeof(memoId), "##RequestMemo%s", suffix); + ImGui::InputText(memoId, s_request_memo, sizeof(s_request_memo)); + } + + // Live URI preview + if (s_request_amount > 0 && !s_cached_qr_data.empty()) { + ImGui::Spacing(); + ImFont* capF = Type().caption(); + ImVec2 uriPos = ImGui::GetCursorScreenPos(); + float uriWrapW = innerW - Layout::spacingXxl(); + ImVec2 uriSz = capF->CalcTextSizeA(capF->LegacySize, FLT_MAX, + uriWrapW, s_cached_qr_data.c_str()); + dl->AddText(capF, capF->LegacySize, uriPos, + OnSurfaceDisabled(), s_cached_qr_data.c_str(), nullptr, uriWrapW); + ImGui::Dummy(ImVec2(uriWrapW, uriSz.y + Layout::spacingSm())); + } + + ImGui::Spacing(); + if (s_request_amount > 0) { + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, Layout::spacingSm()); + char copyUriId[64]; + snprintf(copyUriId, sizeof(copyUriId), "Copy Payment URI%s", suffix); + if (TactileButton(copyUriId, ImVec2(innerW - Layout::spacingXxl(), 0), S.resolveFont("button"))) { + ImGui::SetClipboardText(s_cached_qr_data.c_str()); + Notifications::instance().info("Payment URI copied to clipboard"); + } + ImGui::PopStyleVar(); + + // Share as text + char shareId[32]; + snprintf(shareId, sizeof(shareId), "Share as Text%s", suffix); + if (TactileSmallButton(shareId, S.resolveFont("button"))) { + char shareBuf[1024]; + snprintf(shareBuf, sizeof(shareBuf), + "Payment Request\nAmount: %.8f %s\nAddress: %s\nURI: %s", + s_request_amount, DRAGONX_TICKER, + addr.address.c_str(), s_cached_qr_data.c_str()); + ImGui::SetClipboardText(shareBuf); + Notifications::instance().info("Payment request copied to clipboard"); + } + } + if (s_request_amount > 0 || s_request_memo[0]) { + ImGui::SameLine(); + char clearId[32]; + snprintf(clearId, sizeof(clearId), "Clear%s", suffix); + if (TactileSmallButton(clearId, S.resolveFont("button"))) { + s_request_amount = 0.0; + s_request_memo[0] = '\0'; + } + } + + ImGui::SetCursorScreenPos(ImVec2(prMin.x, prMax.y)); + ImGui::Dummy(ImVec2(innerW, 0)); +} + +// ============================================================================ +// Recent received transactions for selected address +// ============================================================================ +static void RenderRecentReceived(ImDrawList* dl, const AddressInfo& addr, + const WalletState& state, float width, + ImFont* capFont) { + char buf[128]; + int recvCount = 0; + for (const auto& tx : state.transactions) { + if (tx.address == addr.address && tx.type == "receive") recvCount++; + } + if (recvCount == 0) return; + + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + snprintf(buf, sizeof(buf), "RECENT RECEIVED (%d)", std::min(recvCount, 3)); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), buf); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + int shown = 0; + for (const auto& tx : state.transactions) { + if (tx.address != addr.address || tx.type != "receive") continue; + if (shown >= 3) break; + + ImVec2 rMin = ImGui::GetCursorScreenPos(); + float rH = 22.0f; + ImVec2 rMax(rMin.x + width, rMin.y + rH); + GlassPanelSpec rsGlass; + rsGlass.rounding = Layout::glassRounding() * 0.5f; + rsGlass.fillAlpha = 8; + DrawGlassPanel(dl, rMin, rMax, rsGlass); + + float rx = rMin.x + Layout::spacingMd(); + float ry = rMin.y + (rH - capFont->LegacySize) * 0.5f; + + // Arrow indicator + dl->AddText(capFont, capFont->LegacySize, ImVec2(rx, ry), + Success(), "\xe2\x86\x90"); + + snprintf(buf, sizeof(buf), "+%.8f %s %s %s", + tx.amount, DRAGONX_TICKER, + tx.getTimeString().c_str(), + tx.confirmations < 1 ? "(unconfirmed)" : ""); + dl->AddText(capFont, capFont->LegacySize, ImVec2(rx + 16, ry), + tx.confirmations >= 1 ? Success() : Warning(), buf); + + ImGui::Dummy(ImVec2(width, rH)); + ImGui::Dummy(ImVec2(0, 2)); + shown++; + } +} + +// ============================================================================ +// Horizontal Address Strip — bottom switching bar (Layout G signature) +// ============================================================================ +static void RenderAddressStrip(App* app, ImDrawList* dl, const WalletState& state, + float width, float hs, + ImFont* /*sub1*/, ImFont* capFont) { + char buf[128]; + + // Header row with filter and + New button + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "YOUR ADDRESSES"); + + float btnW = std::max(70.0f, 85.0f * hs); + float comboW = std::max(48.0f, 58.0f * hs); + ImGui::SameLine(width - btnW - comboW - Layout::spacingMd()); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, Layout::spacingSm()); + const char* types[] = { "All", "Z", "T" }; + ImGui::SetNextItemWidth(comboW); + ImGui::Combo("##AddrTypeStrip", &s_addr_type_filter, types, 3); + + ImGui::SameLine(); + ImGui::BeginDisabled(!app->isConnected()); + if (TactileButton("+ New##strip", ImVec2(btnW, 0), schema::UI().resolveFont("button"))) { + if (s_addr_type_filter != 2) { + app->createNewZAddress([](const std::string& addr) { + if (addr.empty()) + Notifications::instance().error("Failed to create new shielded address"); + else + Notifications::instance().success("New shielded address created"); + }); + } else { + app->createNewTAddress([](const std::string& addr) { + if (addr.empty()) + Notifications::instance().error("Failed to create new transparent address"); + else + Notifications::instance().success("New transparent address created"); + }); + } + } + ImGui::EndDisabled(); + ImGui::PopStyleVar(); + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (!app->isConnected()) { + Type().textColored(TypeStyle::Caption, Warning(), "Waiting for connection..."); + return; + } + + if (state.addresses.empty()) { + // Loading skeleton + ImVec2 skelPos = ImGui::GetCursorScreenPos(); + float alpha = (float)(0.3 + 0.15 * std::sin(ImGui::GetTime() * 2.0)); + ImU32 skelCol = IM_COL32(255, 255, 255, (int)(alpha * 255)); + for (int sk = 0; sk < 3; sk++) { + dl->AddRectFilled( + ImVec2(skelPos.x + sk * (130 + 8), skelPos.y), + ImVec2(skelPos.x + sk * (130 + 8) + 120, skelPos.y + 56), + skelCol, 6.0f); + } + ImGui::Dummy(ImVec2(width, 60)); + return; + } + + TrackNewAddresses(state); + AddressGroups groups = BuildSortedAddressGroups(state); + + // Build filtered list + std::vector filteredIdxs; + if (s_addr_type_filter != 2) + for (int idx : groups.shielded) filteredIdxs.push_back(idx); + if (s_addr_type_filter != 1) + for (int idx : groups.transparent) filteredIdxs.push_back(idx); + + // Horizontal scrolling strip + float cardW = std::max(140.0f, std::min(200.0f, width * 0.22f)); + float cardH = std::max(52.0f, 64.0f * hs); + float stripH = cardH + 8; + + ImGui::BeginChild("##AddrStrip", ImVec2(width, stripH), false, + ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoBackground); + ImDrawList* sdl = ImGui::GetWindowDrawList(); + + for (size_t fi = 0; fi < filteredIdxs.size(); fi++) { + int i = filteredIdxs[fi]; + const auto& addr = state.addresses[i]; + bool isCurrent = (i == s_selected_address_idx); + bool isZ = addr.type == "shielded"; + ImU32 typeCol = isZ ? IM_COL32(77, 204, 77, 255) : IM_COL32(204, 170, 51, 255); + bool hasBalance = addr.balance > 0; + + ImVec2 cardMin = ImGui::GetCursorScreenPos(); + ImVec2 cardMax(cardMin.x + cardW, cardMin.y + cardH); + + // Card background + GlassPanelSpec cardGlass; + cardGlass.rounding = Layout::glassRounding() * 0.75f; + cardGlass.fillAlpha = isCurrent ? 28 : 14; + cardGlass.borderAlpha = isCurrent ? 50 : 25; + DrawGlassPanel(sdl, cardMin, cardMax, cardGlass); + + // Selected indicator — top accent bar + if (isCurrent) { + sdl->AddRectFilled(cardMin, ImVec2(cardMax.x, cardMin.y + 3), Primary(), + cardGlass.rounding); + } + + float ix = cardMin.x + Layout::spacingMd(); + float iy = cardMin.y + Layout::spacingSm() + (isCurrent ? 4 : 0); + + // Type dot + sdl->AddCircleFilled(ImVec2(ix + 4, iy + 6), 3.5f, typeCol); + + // Address label or truncated address + auto lblIt = s_address_labels.find(addr.address); + bool hasLabel = (lblIt != s_address_labels.end() && !lblIt->second.empty()); + size_t addrTruncLen = static_cast(std::max(8.0f, (cardW - 30) / 9.0f)); + + if (hasLabel) { + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(ix + 14, iy), + isCurrent ? PrimaryLight() : OnSurfaceMedium(), + lblIt->second.c_str()); + std::string shortAddr = TruncateAddress(addr.address, std::max((size_t)6, addrTruncLen / 2)); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(ix + 14, iy + capFont->LegacySize + 2), + OnSurfaceDisabled(), shortAddr.c_str()); + } else { + std::string dispAddr = TruncateAddress(addr.address, addrTruncLen); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(ix + 14, iy), + isCurrent ? OnSurface() : OnSurfaceDisabled(), + dispAddr.c_str()); + } + + // Balance + snprintf(buf, sizeof(buf), "%.4f %s", addr.balance, DRAGONX_TICKER); + ImVec2 balSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + float balY = cardMax.y - balSz.y - Layout::spacingSm(); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(ix + 14, balY), + hasBalance ? typeCol : OnSurfaceDisabled(), buf); + + // NEW badge + double now = ImGui::GetTime(); + auto newIt = s_new_address_timestamps.find(addr.address); + if (newIt != s_new_address_timestamps.end() && newIt->second > 0.0) { + double age = now - newIt->second; + if (age < 10.0) { + float alpha = (float)std::max(0.0, 1.0 - age / 10.0); + int a = (int)(alpha * 220); + ImVec2 badgePos(cardMax.x - 32, cardMin.y + 4); + sdl->AddRectFilled(badgePos, ImVec2(badgePos.x + 28, badgePos.y + 14), + IM_COL32(77, 204, 255, a / 4), 3.0f); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(badgePos.x + 4, badgePos.y + 1), + IM_COL32(77, 204, 255, a), "NEW"); + } + } + + // Click interaction + ImGui::SetCursorScreenPos(cardMin); + ImGui::PushID(i); + ImGui::InvisibleButton("##addrCard", ImVec2(cardW, cardH)); + if (ImGui::IsItemHovered()) { + if (!isCurrent) + sdl->AddRectFilled(cardMin, cardMax, IM_COL32(255, 255, 255, 10), + cardGlass.rounding); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("%s\nBalance: %.8f %s%s\nDouble-click to copy | Right-click for options", + addr.address.c_str(), addr.balance, DRAGONX_TICKER, + isCurrent ? " (selected)" : ""); + } + if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) { + s_selected_address_idx = i; + s_cached_qr_data.clear(); + } + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { + ImGui::SetClipboardText(addr.address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + + // Context menu + if (ImGui::BeginPopupContextItem("##addrStripCtx")) { + if (ImGui::MenuItem("Copy Address")) { + ImGui::SetClipboardText(addr.address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + if (ImGui::MenuItem("View on Explorer")) { + OpenExplorerURL(addr.address); + } + if (addr.balance > 0) { + if (ImGui::MenuItem("Send From This Address")) { + SetSendFromAddress(addr.address); + app->setCurrentPage(NavPage::Send); + } + } + ImGui::EndPopup(); + } + ImGui::PopID(); + + ImGui::SameLine(0, Layout::spacingSm()); + } + + // Total balance at end of strip + { + double totalBal = 0; + for (const auto& a : state.addresses) totalBal += a.balance; + ImVec2 totPos = ImGui::GetCursorScreenPos(); + float totCardW = std::max(100.0f, cardW * 0.6f); + ImVec2 totMax(totPos.x + totCardW, totPos.y + cardH); + + GlassPanelSpec totGlass; + totGlass.rounding = Layout::glassRounding() * 0.75f; + totGlass.fillAlpha = 8; + totGlass.borderAlpha = 15; + DrawGlassPanel(sdl, totPos, totMax, totGlass); + + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(totPos.x + Layout::spacingMd(), totPos.y + Layout::spacingSm()), + OnSurfaceMedium(), "TOTAL"); + snprintf(buf, sizeof(buf), "%.8f", totalBal); + ImVec2 totSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, buf); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(totPos.x + Layout::spacingMd(), + totMax.y - totSz.y - Layout::spacingSm()), + OnSurface(), buf); + snprintf(buf, sizeof(buf), "%s", DRAGONX_TICKER); + sdl->AddText(capFont, capFont->LegacySize, + ImVec2(totPos.x + Layout::spacingMd(), + totMax.y - totSz.y - Layout::spacingSm() - capFont->LegacySize - 2), + OnSurfaceDisabled(), buf); + ImGui::Dummy(ImVec2(totCardW, cardH)); + } + + // Keyboard navigation + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)) { + if (ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { + int next = s_selected_address_idx + 1; + if (next < (int)state.addresses.size()) { + s_selected_address_idx = next; + s_cached_qr_data.clear(); + } + } + if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { + int prev = s_selected_address_idx - 1; + if (prev >= 0) { + s_selected_address_idx = prev; + s_cached_qr_data.clear(); + } + } + if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) { + if (s_selected_address_idx >= 0 && s_selected_address_idx < (int)state.addresses.size()) { + ImGui::SetClipboardText(state.addresses[s_selected_address_idx].address.c_str()); + Notifications::instance().info("Address copied to clipboard"); + } + } + } + + ImGui::EndChild(); // ##AddrStrip +} + +// ============================================================================ +// MAIN: RenderReceiveTab — Layout G: QR-Centered Hero +// ============================================================================ +void RenderReceiveTab(App* app) +{ + const auto& state = app->getWalletState(); + + RenderSyncBanner(state); + + ImVec2 recvAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##ReceiveScroll", recvAvail, false, ImGuiWindowFlags_NoBackground); + + float hs = Layout::hScale(recvAvail.x); + float vScale = Layout::vScale(recvAvail.y); + float glassRound = Layout::glassRounding(); + + float availWidth = ImGui::GetContentRegionAvail().x; + float contentWidth = std::min(availWidth * 0.92f, 1200.0f * hs); + float offsetX = (availWidth - contentWidth) * 0.5f; + if (offsetX > 0) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX); + + float sectionGap = Layout::spacingXl() * vScale; + + ImGui::BeginGroup(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* body2 = Type().body2(); + + // Auto-select first address + if (!state.addresses.empty() && + (s_selected_address_idx < 0 || + s_selected_address_idx >= (int)state.addresses.size())) { + s_selected_address_idx = 0; + } + + const AddressInfo* selected = nullptr; + if (s_selected_address_idx >= 0 && + s_selected_address_idx < (int)state.addresses.size()) { + selected = &state.addresses[s_selected_address_idx]; + } + + // Generate QR data + std::string qr_data; + if (selected) { + qr_data = selected->address; + if (s_request_amount > 0) { + qr_data = std::string("dragonx:") + selected->address + + "?amount=" + std::to_string(s_request_amount); + if (s_request_memo[0] && selected->type == "shielded") { + qr_data += "&memo=" + std::string(s_request_memo); + } + } + if (qr_data != s_cached_qr_data) { + if (s_qr_texture) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } + int w, h; + s_qr_texture = GenerateQRTexture(qr_data.c_str(), &w, &h); + s_cached_qr_data = qr_data; + } + } + + // ================================================================ + // Not connected / empty state + // ================================================================ + if (!app->isConnected()) { + ImVec2 emptyMin = ImGui::GetCursorScreenPos(); + float emptyH = 120.0f; + ImVec2 emptyMax(emptyMin.x + contentWidth, emptyMin.y + emptyH); + DrawGlassPanel(dl, emptyMin, emptyMax, glassSpec); + dl->AddText(sub1, sub1->LegacySize, + ImVec2(emptyMin.x + Layout::spacingXl(), emptyMin.y + Layout::spacingXl()), + OnSurfaceDisabled(), "Waiting for daemon connection..."); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(emptyMin.x + Layout::spacingXl(), emptyMin.y + Layout::spacingXl() + sub1->LegacySize + 8), + OnSurfaceDisabled(), "Your receiving addresses will appear here once connected."); + ImGui::Dummy(ImVec2(contentWidth, emptyH)); + ImGui::EndGroup(); + ImGui::EndChild(); + return; + } + + if (state.addresses.empty()) { + ImVec2 emptyMin = ImGui::GetCursorScreenPos(); + float emptyH = 100.0f; + ImVec2 emptyMax(emptyMin.x + contentWidth, emptyMin.y + emptyH); + DrawGlassPanel(dl, emptyMin, emptyMax, glassSpec); + float alpha = (float)(0.3 + 0.15 * std::sin(ImGui::GetTime() * 2.0)); + ImU32 skelCol = IM_COL32(255, 255, 255, (int)(alpha * 255)); + dl->AddRectFilled( + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + Layout::spacingLg()), + ImVec2(emptyMin.x + contentWidth * 0.6f, emptyMin.y + Layout::spacingLg() + 16), + skelCol, 4.0f); + dl->AddRectFilled( + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + Layout::spacingLg() + 24), + ImVec2(emptyMin.x + contentWidth * 0.4f, emptyMin.y + Layout::spacingLg() + 36), + skelCol, 4.0f); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(emptyMin.x + Layout::spacingLg(), emptyMin.y + emptyH - 24), + OnSurfaceDisabled(), "Loading addresses..."); + ImGui::Dummy(ImVec2(contentWidth, emptyH)); + ImGui::EndGroup(); + ImGui::EndChild(); + return; + } + + // ================================================================ + // QR HERO — dominates center (Layout G signature) + // ================================================================ + if (selected) { + // Calculate QR size based on available space + float maxQrForWidth = std::min(contentWidth * 0.6f, 400.0f); + float maxQrForHeight = std::min(recvAvail.y * 0.45f, 400.0f); + float qrSize = std::max(140.0f, std::min(maxQrForWidth, maxQrForHeight)); + + // Center the hero horizontally + float heroW = std::min(contentWidth, 700.0f * hs); + float heroOffsetX = (contentWidth - heroW) * 0.5f; + if (heroOffsetX > 4) { + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + heroOffsetX); + } + + RenderQRHero(app, dl, *selected, heroW, qrSize, qr_data, + glassSpec, state, sub1, body2, capFont); + ImGui::Dummy(ImVec2(0, sectionGap)); + + // ---- PAYMENT REQUEST (collapsible on narrow) ---- + constexpr float kTwoColumnThreshold = 800.0f; + bool isNarrow = contentWidth < kTwoColumnThreshold; + + if (isNarrow) { + ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(1, 1, 1, 0.05f)); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(1, 1, 1, 0.08f)); + ImGui::PushFont(Type().overline()); + s_payment_request_open = ImGui::CollapsingHeader( + "PAYMENT REQUEST (OPTIONAL)", + s_payment_request_open ? ImGuiTreeNodeFlags_DefaultOpen : 0); + ImGui::PopFont(); + ImGui::PopStyleColor(3); + + if (s_payment_request_open) { + float prW = std::min(contentWidth, 600.0f * hs); + float prOffX = (contentWidth - prW) * 0.5f; + if (prOffX > 4) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + prOffX); + RenderPaymentRequest(dl, *selected, prW, glassSpec, "##hero"); + } + } else { + float prW = std::min(contentWidth, 600.0f * hs); + float prOffX = (contentWidth - prW) * 0.5f; + if (prOffX > 4) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + prOffX); + RenderPaymentRequest(dl, *selected, prW, glassSpec, "##hero"); + } + ImGui::Dummy(ImVec2(0, sectionGap)); + + // ---- RECENT RECEIVED ---- + { + float rcvW = std::min(contentWidth, 600.0f * hs); + float rcvOffX = (contentWidth - rcvW) * 0.5f; + if (rcvOffX > 4) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + rcvOffX); + RenderRecentReceived(dl, *selected, state, rcvW, capFont); + } + ImGui::Dummy(ImVec2(0, sectionGap)); + } + + // ================================================================ + // ADDRESS STRIP — horizontal switching bar at bottom + // ================================================================ + RenderAddressStrip(app, dl, state, contentWidth, hs, sub1, capFont); + + ImGui::EndGroup(); + ImGui::EndChild(); // ##ReceiveScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/receive_tab.h b/src/ui/windows/receive_tab.h new file mode 100644 index 0000000..ac2fa0f --- /dev/null +++ b/src/ui/windows/receive_tab.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Receive tab + * Shows addresses for receiving funds with QR codes + */ +void RenderReceiveTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/request_payment_dialog.cpp b/src/ui/windows/request_payment_dialog.cpp new file mode 100644 index 0000000..f6a3c2a --- /dev/null +++ b/src/ui/windows/request_payment_dialog.cpp @@ -0,0 +1,298 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "request_payment_dialog.h" +#include "../../app.h" +#include "../../util/i18n.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../widgets/qr_code.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +#include +#include +#include + +namespace dragonx { +namespace ui { + +// Static state +static bool s_open = false; +static char s_address[512] = ""; +static double s_amount = 0.0; +static char s_memo[512] = ""; +static char s_label[128] = ""; +static int s_selected_addr_idx = -1; +static std::string s_payment_uri; +static uintptr_t s_qr_texture = 0; +static int s_qr_width = 0; +static int s_qr_height = 0; +static bool s_uri_dirty = true; + +// Helper to build payment URI +static std::string buildPaymentUri() +{ + if (s_address[0] == '\0') return ""; + + std::ostringstream uri; + uri << "drgx:" << s_address; + + bool hasParams = false; + auto addParam = [&](const char* key, const std::string& value) { + if (value.empty()) return; + uri << (hasParams ? "&" : "?") << key << "=" << value; + hasParams = true; + }; + + if (s_amount > 0) { + std::ostringstream amt; + amt << std::fixed << std::setprecision(8) << s_amount; + addParam("amount", amt.str()); + } + + if (s_label[0] != '\0') { + // URL encode label + std::string encoded; + for (char c : std::string(s_label)) { + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + encoded += c; + } else if (c == ' ') { + encoded += "%20"; + } else { + char hex[4]; + snprintf(hex, sizeof(hex), "%%%02X", (unsigned char)c); + encoded += hex; + } + } + addParam("label", encoded); + } + + if (s_memo[0] != '\0') { + // URL encode memo + std::string encoded; + for (char c : std::string(s_memo)) { + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + encoded += c; + } else if (c == ' ') { + encoded += "%20"; + } else { + char hex[4]; + snprintf(hex, sizeof(hex), "%%%02X", (unsigned char)c); + encoded += hex; + } + } + addParam("memo", encoded); + } + + return uri.str(); +} + +void RequestPaymentDialog::show(const std::string& address) +{ + s_open = true; + s_amount = 0.0; + s_memo[0] = '\0'; + s_label[0] = '\0'; + s_selected_addr_idx = -1; + s_uri_dirty = true; + + if (!address.empty()) { + strncpy(s_address, address.c_str(), sizeof(s_address) - 1); + } else { + s_address[0] = '\0'; + } + + // Free old QR texture + if (s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } +} + +void RequestPaymentDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.request-payment"); + auto zAddrLbl = S.label("dialogs.request-payment", "z-addr-label"); + auto zAddrFrontLbl = S.label("dialogs.request-payment", "z-addr-front-label"); + auto zAddrBackLbl = S.label("dialogs.request-payment", "z-addr-back-label"); + auto tAddrLbl = S.label("dialogs.request-payment", "t-addr-label"); + auto tAddrFrontLbl = S.label("dialogs.request-payment", "t-addr-front-label"); + auto tAddrBackLbl = S.label("dialogs.request-payment", "t-addr-back-label"); + auto amountInput = S.input("dialogs.request-payment", "amount-input"); + auto memoInput = S.input("dialogs.request-payment", "memo-input"); + auto qr = S.drawElement("dialogs.request-payment", "qr-code"); + auto actionBtn = S.button("dialogs.request-payment", "action-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Request Payment"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Request Payment", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + const auto& state = app->getWalletState(); + + ImGui::TextWrapped( + "Generate a payment request that others can scan or copy. " + "The QR code contains your address and optional amount/memo." + ); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Address selection + ImGui::Text("Receive Address:"); + + std::string addr_display = s_address[0] ? s_address : "Select address..."; + if (addr_display.length() > static_cast(zAddrLbl.truncate)) { + addr_display = addr_display.substr(0, zAddrFrontLbl.truncate) + "..." + addr_display.substr(addr_display.length() - zAddrBackLbl.truncate); + } + + ImGui::SetNextItemWidth(-1); + if (ImGui::BeginCombo("##Address", addr_display.c_str())) { + // Z-addresses + if (!state.z_addresses.empty()) { + ImGui::TextDisabled("-- Shielded Addresses --"); + for (size_t i = 0; i < state.z_addresses.size(); i++) { + const auto& addr = state.z_addresses[i]; + std::string label = addr.address; + if (label.length() > static_cast(zAddrLbl.truncate)) { + label = label.substr(0, zAddrFrontLbl.truncate) + "..." + label.substr(label.length() - zAddrBackLbl.truncate); + } + + if (ImGui::Selectable(label.c_str(), s_address == addr.address)) { + strncpy(s_address, addr.address.c_str(), sizeof(s_address) - 1); + s_uri_dirty = true; + } + } + } + + // T-addresses + if (!state.t_addresses.empty()) { + ImGui::TextDisabled("-- Transparent Addresses --"); + for (size_t i = 0; i < state.t_addresses.size(); i++) { + const auto& addr = state.t_addresses[i]; + std::string label = addr.address; + if (label.length() > static_cast(tAddrLbl.truncate)) { + label = label.substr(0, tAddrFrontLbl.truncate) + "..." + label.substr(label.length() - tAddrBackLbl.truncate); + } + + if (ImGui::Selectable(label.c_str(), s_address == addr.address)) { + strncpy(s_address, addr.address.c_str(), sizeof(s_address) - 1); + s_uri_dirty = true; + } + } + } + ImGui::EndCombo(); + } + + ImGui::Spacing(); + + // Amount (optional) + ImGui::Text("Amount (optional):"); + ImGui::SetNextItemWidth(amountInput.width); + if (ImGui::InputDouble("##Amount", &s_amount, 0.1, 1.0, "%.8f")) { + s_uri_dirty = true; + } + ImGui::SameLine(); + ImGui::TextDisabled("DRGX"); + + ImGui::Spacing(); + + // Label (optional) + ImGui::Text("Label (optional):"); + ImGui::SetNextItemWidth(-1); + if (ImGui::InputText("##Label", s_label, sizeof(s_label))) { + s_uri_dirty = true; + } + + ImGui::Spacing(); + + // Memo (optional, only for z-addr) + bool is_zaddr = (s_address[0] == 'z'); + if (is_zaddr) { + ImGui::Text("Memo (optional):"); + ImGui::SetNextItemWidth(-1); + if (ImGui::InputTextMultiline("##Memo", s_memo, sizeof(s_memo), ImVec2(-1, memoInput.height > 0 ? memoInput.height : 60))) { + s_uri_dirty = true; + } + } else { + s_memo[0] = '\0'; // Clear memo for t-addr + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Build and display payment URI + if (s_uri_dirty && s_address[0] != '\0') { + s_payment_uri = buildPaymentUri(); + + // Generate new QR code + if (s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + } + s_qr_texture = GenerateQRTexture(s_payment_uri.c_str(), &s_qr_width, &s_qr_height); + s_uri_dirty = false; + } + + // QR Code display + if (s_qr_texture != 0) { + RenderQRCode(s_qr_texture, qr.size > 0 ? qr.size : 200); + } + + ImGui::Spacing(); + + // Payment URI display + if (!s_payment_uri.empty()) { + ImGui::Text("Payment URI:"); + ImGui::SetNextItemWidth(-1); + + // Use a selectable text area for the URI + char uri_buf[1024]; + strncpy(uri_buf, s_payment_uri.c_str(), sizeof(uri_buf) - 1); + ImGui::InputText("##URI", uri_buf, sizeof(uri_buf), ImGuiInputTextFlags_ReadOnly); + + ImGui::Spacing(); + + // Copy button + if (material::StyledButton("Copy URI", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + ImGui::SetClipboardText(s_payment_uri.c_str()); + Notifications::instance().success("Payment URI copied to clipboard"); + } + + ImGui::SameLine(); + + if (material::StyledButton("Copy Address", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + ImGui::SetClipboardText(s_address); + Notifications::instance().success("Address copied to clipboard"); + } + } + + ImGui::Spacing(); + + // Close button + if (material::StyledButton("Close", ImVec2(actionBtn.width, 0), S.resolveFont(actionBtn.font))) { + s_open = false; + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + + // Cleanup on close + if (!s_open && s_qr_texture != 0) { + FreeQRTexture(s_qr_texture); + s_qr_texture = 0; + } +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/request_payment_dialog.h b/src/ui/windows/request_payment_dialog.h new file mode 100644 index 0000000..a71edc7 --- /dev/null +++ b/src/ui/windows/request_payment_dialog.h @@ -0,0 +1,32 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Dialog for generating payment requests with QR codes + */ +class RequestPaymentDialog { +public: + /** + * @brief Show the request payment dialog + * @param address Pre-fill with this address (optional) + */ + static void show(const std::string& address = ""); + + /** + * @brief Render the dialog (call each frame) + */ + static void render(App* app); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/send_tab.cpp b/src/ui/windows/send_tab.cpp new file mode 100644 index 0000000..e77d680 --- /dev/null +++ b/src/ui/windows/send_tab.cpp @@ -0,0 +1,1556 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 +// +// Layout E: Top Bar Source + Bottom Form +// - Persistent source address bar at top (always visible) +// - Centered compose form below +// - Recent sends at bottom + +#include "send_tab.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../data/wallet_state.h" +#include "../../util/i18n.h" +#include "../notifications.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" + +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// ============================================================================ +// Form state +// ============================================================================ +static char s_from_address[512] = ""; +static char s_to_address[512] = ""; +static double s_amount = 0.0; +static char s_memo[512] = ""; +static double s_fee = DRAGONX_DEFAULT_FEE; +static bool s_send_max = false; +static int s_selected_from_idx = -1; +static std::string s_tx_status = ""; +static bool s_sending = false; + +// Transaction progress state +static double s_status_timestamp = 0.0; +static bool s_status_success = false; +static std::string s_result_txid = ""; + +static double s_send_start_time = 0.0; + +// Undo buffer for clear action +struct FormSnapshot { + char from_address[512]; + char to_address[512]; + double amount; + char memo[512]; + double fee; + bool send_max; + int selected_from_idx; +}; +static FormSnapshot s_undo_snapshot; +static double s_undo_timestamp = 0.0; +static constexpr double UNDO_TIMEOUT = 8.0; + +// Fee selection +static int s_fee_tier = 1; // 0=low, 1=normal, 2=high +static constexpr double FEE_LOW = DRAGONX_DEFAULT_FEE * 0.5; +static constexpr double FEE_NORMAL = DRAGONX_DEFAULT_FEE; +static constexpr double FEE_HIGH = DRAGONX_DEFAULT_FEE * 2.0; + +static bool s_clear_confirm_pending = false; + +// Source dropdown preview string +static std::string s_source_preview; + +// Amount input mode: false = DRGX, true = USD +static bool s_input_usd = false; +static double s_usd_amount = 0.0; // tracks USD input when in USD mode +static bool s_auto_selected = false; // tracks if auto-selection has been done +static bool s_show_confirm = false; // persistent: keeps popup open at top-level scope + +// ============================================================================ +// Helpers +// ============================================================================ +static bool FormHasData() { + return (s_to_address[0] != '\0' || s_amount > 0.0 || s_memo[0] != '\0'); +} + +static void SaveFormSnapshot() { + snprintf(s_undo_snapshot.from_address, sizeof(s_undo_snapshot.from_address), "%s", s_from_address); + snprintf(s_undo_snapshot.to_address, sizeof(s_undo_snapshot.to_address), "%s", s_to_address); + s_undo_snapshot.amount = s_amount; + snprintf(s_undo_snapshot.memo, sizeof(s_undo_snapshot.memo), "%s", s_memo); + s_undo_snapshot.fee = s_fee; + s_undo_snapshot.send_max = s_send_max; + s_undo_snapshot.selected_from_idx = s_selected_from_idx; + s_undo_timestamp = ImGui::GetTime(); +} + +static void RestoreFormSnapshot() { + snprintf(s_from_address, sizeof(s_from_address), "%s", s_undo_snapshot.from_address); + snprintf(s_to_address, sizeof(s_to_address), "%s", s_undo_snapshot.to_address); + s_amount = s_undo_snapshot.amount; + snprintf(s_memo, sizeof(s_memo), "%s", s_undo_snapshot.memo); + s_fee = s_undo_snapshot.fee; + s_send_max = s_undo_snapshot.send_max; + s_selected_from_idx = s_undo_snapshot.selected_from_idx; + s_undo_timestamp = 0.0; +} + +static void ClearFormWithUndo() { + SaveFormSnapshot(); + s_from_address[0] = '\0'; + s_to_address[0] = '\0'; + s_amount = 0.0; + s_memo[0] = '\0'; + s_fee = DRAGONX_DEFAULT_FEE; + s_send_max = false; + s_selected_from_idx = -1; + s_auto_selected = false; + s_tx_status = ""; + s_fee_tier = 1; +} + +static double GetAvailableBalance(App* app) { + const auto& state = app->getWalletState(); + if (s_selected_from_idx >= 0 && s_selected_from_idx < static_cast(state.addresses.size())) { + return state.addresses[s_selected_from_idx].balance; + } + return 0.0; +} + +static std::string TruncateAddress(const std::string& addr, size_t maxLen = 40) { + if (addr.length() <= maxLen) return addr; + size_t halfLen = (maxLen - 3) / 2; + return addr.substr(0, halfLen) + "..." + addr.substr(addr.length() - halfLen); +} + +static std::string timeAgo(int64_t timestamp) { + if (timestamp <= 0) return ""; + int64_t now = (int64_t)std::time(nullptr); + int64_t diff = now - timestamp; + if (diff < 0) diff = 0; + if (diff < 60) return std::to_string(diff) + "s ago"; + if (diff < 3600) return std::to_string(diff / 60) + "m ago"; + if (diff < 86400) return std::to_string(diff / 3600) + "h ago"; + return std::to_string(diff / 86400) + "d ago"; +} + +static void DrawTxIcon(ImDrawList* dl, const std::string& type, + float cx, float cy, float /*s*/, ImU32 col) +{ + using namespace material; + ImFont* iconFont = Type().iconSmall(); + const char* icon; + if (type == "send") { + icon = ICON_MD_CALL_MADE; + } else if (type == "receive") { + icon = ICON_MD_CALL_RECEIVED; + } else { + icon = ICON_MD_CONSTRUCTION; // mined + } + ImVec2 sz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - sz.x * 0.5f, cy - sz.y * 0.5f), col, icon); +} + +static void PasteClipboardToAddress() { + const char* clipboard = ImGui::GetClipboardText(); + if (clipboard) { + std::string trimmed(clipboard); + while (!trimmed.empty() && (trimmed.front() == ' ' || trimmed.front() == '\t' || + trimmed.front() == '\n' || trimmed.front() == '\r')) + trimmed.erase(trimmed.begin()); + while (!trimmed.empty() && (trimmed.back() == ' ' || trimmed.back() == '\t' || + trimmed.back() == '\n' || trimmed.back() == '\r')) + trimmed.pop_back(); + snprintf(s_to_address, sizeof(s_to_address), "%s", trimmed.c_str()); + } +} + +// ============================================================================ +// Sync banner +// ============================================================================ +static void RenderSyncBanner(const WalletState& state) { + if (!state.sync.syncing || state.sync.isSynced()) return; + + float syncPct = (state.sync.headers > 0) + ? (float)state.sync.blocks / state.sync.headers * 100.0f : 0.0f; + char syncBuf[128]; + snprintf(syncBuf, sizeof(syncBuf), + "Blockchain syncing (%.1f%%)... Balances may be inaccurate.", syncPct); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(schema::UI().resolveColor(schema::UI().drawElement("tabs.send", "sync-banner-bg-color").color))); + float syncH = std::max(schema::UI().drawElement("tabs.send", "sync-banner-min-height").size, schema::UI().drawElement("tabs.send", "sync-banner-height").size * Layout::vScale()); + ImGui::BeginChild("##SyncBanner", ImVec2(ImGui::GetContentRegionAvail().x, syncH), + false, ImGuiWindowFlags_NoScrollbar); + ImGui::SetCursorPos(ImVec2(Layout::spacingLg(), (syncH - Type().caption()->LegacySize) * 0.5f)); + Type().textColored(TypeStyle::Caption, Warning(), syncBuf); + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Source Address Dropdown — simple combo selector +// ============================================================================ +static void RenderSourceDropdown(App* app, float width) { + const auto& state = app->getWalletState(); + auto& S = schema::UI(); + char buf[256]; + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "SENDING FROM"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Auto-select the address with the largest balance on first load + if (!s_auto_selected && app->isConnected() && !state.addresses.empty()) { + int bestIdx = -1; + double bestBal = 0.0; + for (size_t i = 0; i < state.addresses.size(); i++) { + if (state.addresses[i].balance > bestBal) { + bestBal = state.addresses[i].balance; + bestIdx = static_cast(i); + } + } + if (bestIdx >= 0) { + s_selected_from_idx = bestIdx; + snprintf(s_from_address, sizeof(s_from_address), "%s", + state.addresses[bestIdx].address.c_str()); + } + s_auto_selected = true; + } + + // Build preview string for selected address + if (!app->isConnected()) { + s_source_preview = "Not connected to daemon"; + } else if (s_selected_from_idx >= 0 && + s_selected_from_idx < (int)state.addresses.size()) { + const auto& addr = state.addresses[s_selected_from_idx]; + bool isZ = addr.type == "shielded"; + const char* tag = isZ ? "[Z]" : "[T]"; + std::string trunc = TruncateAddress(addr.address, + static_cast(std::max(S.drawElement("tabs.send", "addr-preview-trunc-min").size, width / S.drawElement("tabs.send", "addr-preview-trunc-divisor").size))); + snprintf(buf, sizeof(buf), "%s %s — %.8f %s", + tag, trunc.c_str(), addr.balance, DRAGONX_TICKER); + s_source_preview = buf; + } else { + s_source_preview = "Select a source address..."; + } + + ImGui::SetNextItemWidth(width); + + ImGui::PushFont(Type().getFont(TypeStyle::Body2)); + if (ImGui::BeginCombo("##SendFrom", s_source_preview.c_str())) { + if (!app->isConnected() || state.addresses.empty()) { + ImGui::TextDisabled("No addresses available"); + } else { + // Sort by balance descending, only show addresses with balance + std::vector sortedIdx; + sortedIdx.reserve(state.addresses.size()); + for (size_t i = 0; i < state.addresses.size(); i++) { + if (state.addresses[i].balance > 0) + sortedIdx.push_back(i); + } + std::sort(sortedIdx.begin(), sortedIdx.end(), + [&](size_t a, size_t b) { + return state.addresses[a].balance > state.addresses[b].balance; + }); + + if (sortedIdx.empty()) { + ImGui::TextDisabled("No addresses with balance"); + } else { + size_t addrTruncLen = static_cast(std::max(S.drawElement("tabs.send", "addr-dropdown-trunc-min").size, width / S.drawElement("tabs.send", "addr-dropdown-trunc-divisor").size)); + + for (size_t si = 0; si < sortedIdx.size(); si++) { + size_t i = sortedIdx[si]; + const auto& addr = state.addresses[i]; + bool isCurrent = (s_selected_from_idx == static_cast(i)); + bool isZ = addr.type == "shielded"; + const char* tag = isZ ? "[Z]" : "[T]"; + + std::string trunc = TruncateAddress(addr.address, addrTruncLen); + snprintf(buf, sizeof(buf), "%s %s — %.8f %s", + tag, trunc.c_str(), addr.balance, DRAGONX_TICKER); + + ImGui::PushID(static_cast(i)); + if (ImGui::Selectable(buf, isCurrent)) { + s_selected_from_idx = static_cast(i); + snprintf(s_from_address, sizeof(s_from_address), "%s", + addr.address.c_str()); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("%s\nBalance: %.8f %s", + addr.address.c_str(), addr.balance, DRAGONX_TICKER); + } + ImGui::PopID(); + } + } + } + ImGui::EndCombo(); + } + ImGui::PopFont(); +} + +// ============================================================================ +// Address suggestions dropdown +// ============================================================================ +static void RenderAddressSuggestions(const WalletState& state, float width, const char* childId) { + std::string partial(s_to_address); + if (partial.length() < 2) return; + bool is_valid_z = (s_to_address[0] == 'z' && s_to_address[1] == 's' && strlen(s_to_address) > 60); + bool is_valid_t = (s_to_address[0] == 'R' && strlen(s_to_address) >= 34); + if (is_valid_z || is_valid_t) return; + + std::vector suggestions; + for (const auto& tx : state.transactions) { + if (tx.type != "send" || tx.address.empty()) continue; + if (tx.address.find(partial) != std::string::npos) { + bool dup = false; + for (const auto& s : suggestions) { if (s == tx.address) { dup = true; break; } } + if (!dup) suggestions.push_back(tx.address); + if (suggestions.size() >= (size_t)schema::UI().drawElement("tabs.send", "max-suggestions").size) break; + } + } + if (suggestions.empty()) return; + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(schema::UI().resolveColor(schema::UI().drawElement("tabs.send", "suggestion-bg-color").color))); + float sugH = std::min((float)suggestions.size() * schema::UI().drawElement("tabs.send", "suggestion-row-height").size + schema::UI().drawElement("tabs.send", "suggestion-list-padding").size, schema::UI().drawElement("tabs.send", "suggestion-max-height").size); + ImGui::BeginChild(childId, ImVec2(width, sugH), true); + for (size_t si = 0; si < suggestions.size(); si++) { + int sugTrunc = (int)schema::UI().drawElement("tabs.send", "suggestion-trunc-len").size; + std::string dispSug = TruncateAddress(suggestions[si], sugTrunc > 0 ? sugTrunc : 50); + ImGui::PushID((int)si); + if (ImGui::Selectable(dispSug.c_str())) { + snprintf(s_to_address, sizeof(s_to_address), "%s", suggestions[si].c_str()); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("%s", suggestions[si].c_str()); + } + ImGui::PopID(); + } + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Fee tier selector +// ============================================================================ +static void RenderFeeTierSelector(const char* suffix = "") { + auto& S = schema::UI(); + const char* feeLabels[] = { "Low", "Normal", "High" }; + const double feeValues[] = { FEE_LOW, FEE_NORMAL, FEE_HIGH }; + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("tabs.send", "fee-rounding").size); + for (int fi = 0; fi < 3; fi++) { + if (fi > 0) ImGui::SameLine(0, S.drawElement("tabs.send", "fee-tier-gap").size); + bool active = (s_fee_tier == fi); + if (active) { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "fee-tier-active-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(Primary())); + } + char feeId[32]; + snprintf(feeId, sizeof(feeId), "%s%s", feeLabels[fi], suffix); + if (TactileSmallButton(feeId, S.resolveFont("button"))) { + s_fee_tier = fi; + s_fee = feeValues[fi]; + } + if (active) ImGui::PopStyleColor(2); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); +} + +// ============================================================================ +// Combined amount slider + usage bar +// ============================================================================ +static void RenderAmountBar(ImDrawList* dl, double available, float innerW, + ImFont* capFont, double usd_price = 0.0, + const char* suffix = "") { + double maxAmount = available - s_fee; + if (maxAmount < 0) maxAmount = 0; + + float progress = (available > 0) + ? std::clamp((float)((s_amount + s_fee) / available), 0.0f, 1.0f) + : 0.0f; + + float maxBtnW = schema::UI().drawElement("tabs.send", "amount-bar-max-btn-width").size; + float gap = Layout::spacingMd(); + float barW = innerW - maxBtnW - gap; + if (barW < schema::UI().drawElement("tabs.send", "progress-bar-min-width").size) barW = schema::UI().drawElement("tabs.send", "progress-bar-min-width").size; + float barH = schema::UI().drawElement("tabs.send", "amount-bar-height").size; + float barRound = barH * 0.5f; + + ImVec2 barMin = ImGui::GetCursorScreenPos(); + ImVec2 barMax(barMin.x + barW, barMin.y + barH); + + // Track background + dl->AddRectFilled(barMin, barMax, IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "amount-bar-track-alpha").size), barRound); + + // Color-coded fill + int fillAlpha = (int)schema::UI().drawElement("tabs.send", "progress-fill-alpha").size; + ImU32 fillCol; + if (progress < schema::UI().drawElement("tabs.send", "progress-threshold-ok").size) fillCol = WithAlpha(Success(), fillAlpha); + else if (progress < schema::UI().drawElement("tabs.send", "progress-threshold-warn").size) fillCol = WithAlpha(Warning(), fillAlpha); + else fillCol = WithAlpha(Error(), fillAlpha); + + // Map fill so its right-side rounding matches the thumb circle exactly + float thumbR = barH * 0.5f; + float usableW = barW - thumbR * 2.0f; + float thumbCenterX = barMin.x + thumbR + usableW * progress; + // Extend fill to the right edge of the thumb circle so the rounded + // corner (radius = barRound = thumbR) produces the same semicircle + float fillRight = thumbCenterX + thumbR; + if (fillRight > barMin.x + barRound * 2.0f) { + dl->AddRectFilled(barMin, ImVec2(fillRight, barMax.y), + fillCol, barRound); + } else if (progress > 0.0f) { + // Very small fill — just draw a circle at the thumb position + dl->AddCircleFilled(ImVec2(thumbCenterX, barMin.y + barH * 0.5f), + thumbR, fillCol, 24); + } + + // Percentage label centered on bar + char pctBuf[32]; + snprintf(pctBuf, sizeof(pctBuf), "%.0f%%", progress * 100.0f); + ImVec2 textSz = capFont->CalcTextSizeA(capFont->LegacySize, 10000, 0, pctBuf); + float textX = barMin.x + (barW - textSz.x) * 0.5f; + float textY = barMin.y + (barH - textSz.y) * 0.5f; + dl->AddText(capFont, capFont->LegacySize, ImVec2(textX, textY), + IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "progress-pct-text-alpha").size), pctBuf); + + // Invisible button for click-to-set interaction + char barId[32]; + snprintf(barId, sizeof(barId), "##AmtBar%s", suffix); + ImGui::InvisibleButton(barId, ImVec2(barW, barH)); + bool barActive = ImGui::IsItemActive(); + bool barHovered = ImGui::IsItemHovered(); + if (barActive) { + float mouseX = ImGui::GetIO().MousePos.x; + float clickPct = std::clamp((mouseX - barMin.x) / barW, 0.0f, 1.0f); + s_amount = maxAmount * clickPct; + if (s_amount < 0) s_amount = 0; + s_send_max = (clickPct >= 1.0f); + // Sync USD amount so the USD input field stays in sync + if (usd_price > 0.0) + s_usd_amount = s_amount * usd_price; + // Recalculate fill position for the thumb while dragging + progress = (available > 0) + ? std::clamp((float)((s_amount + s_fee) / available), 0.0f, 1.0f) + : 0.0f; + } + if (barHovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + char tipBuf[128]; + snprintf(tipBuf, sizeof(tipBuf), "%.8f / %.8f %s (%.1f%%)", + s_amount, maxAmount > 0 ? maxAmount : 0.0, DRAGONX_TICKER, + progress * 100.0f); + ImGui::SetTooltip("%s", tipBuf); + } + + // Glass thumb circle at the fill edge + { + // thumbCenterX already computed above + float thumbY = barMin.y + barH * 0.5f; + + // Glass circle body — translucent fill with border + dl->AddCircleFilled(ImVec2(thumbCenterX, thumbY), thumbR, + IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "thumb-fill-alpha").size), 24); + dl->AddCircle(ImVec2(thumbCenterX, thumbY), thumbR, + IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "thumb-border-alpha").size), 24, schema::UI().drawElement("tabs.send", "thumb-border-thickness").size); + } + + // Max button — use caption font to fit bar height + ImGui::SameLine(0, gap); + char maxId[32]; + snprintf(maxId, sizeof(maxId), "Max%s", suffix); + if (TactileButton(maxId, ImVec2(maxBtnW, barH), capFont)) { + s_amount = maxAmount; + s_send_max = true; + if (usd_price > 0.0) + s_usd_amount = s_amount * usd_price; + } +} + +// ============================================================================ +// Transaction progress indicator +// ============================================================================ +static void RenderTxProgress(ImDrawList* dl, float x, float y, float w, + ImFont* body2, ImFont* capFont, + float cardBottomY = -1.0f) { + // Auto-clear old success status + if (!s_tx_status.empty() && s_status_success && s_status_timestamp > 0.0 && + (ImGui::GetTime() - s_status_timestamp) > schema::UI().drawElement("tabs.send", "tx-success-timeout").size) { + s_tx_status.clear(); + s_result_txid.clear(); + s_status_timestamp = 0.0; + } + if (s_tx_status.empty() && !s_sending) return; + + bool is_error = !s_sending && (s_tx_status.find("Error") != std::string::npos || + s_tx_status.find("Failed") != std::string::npos || + s_tx_status.find("error") != std::string::npos); + + // ---- ERROR: absolute-positioned overlay, does not displace layout ---- + if (is_error) { + float pad = Layout::spacingLg(); + float btnH = std::max(schema::UI().drawElement("tabs.send", "error-btn-min-height").size, schema::UI().drawElement("tabs.send", "error-btn-height").size); + float textWrapW = w - pad * 2 - schema::UI().drawElement("tabs.send", "error-icon-inset").size; // icon space + ImVec2 textSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, textWrapW, s_tx_status.c_str()); + float contentH = textSz.y + Layout::spacingMd() + btnH + pad * 2; + + // Anchor to bottom of compose card, overlapping upward (position: absolute) + float anchorY = (cardBottomY > 0) ? cardBottomY : y; + float overlayY = anchorY - contentH - Layout::spacingMd(); + ImVec2 pMin(x, overlayY); + ImVec2 pMax(x + w, overlayY + contentH); + + // Save cursor — this overlay must not displace layout + ImVec2 savedCursor = ImGui::GetCursorScreenPos(); + + // Glass card background — matches compose form card style + GlassPanelSpec errGlass; + errGlass.rounding = Layout::glassRounding(); + + // Use foreground draw list so overlay renders on top of everything + ImDrawList* fgDl = ImGui::GetForegroundDrawList(); + + // Glass panel background + DrawGlassPanel(fgDl, pMin, pMax, errGlass); + + // Red accent bar on left + fgDl->AddRectFilled(pMin, ImVec2(pMin.x + schema::UI().drawElement("tabs.send", "error-accent-bar-width").size, pMax.y), Error(), errGlass.rounding); + + float ix = pMin.x + pad; + float iy = pMin.y + pad; + + // Error icon (Material Design) + { + ImFont* iconFont = material::Type().iconMed(); + const char* errIcon = ICON_MD_ERROR; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, errIcon); + fgDl->AddText(iconFont, iconFont->LegacySize, + ImVec2(ix + schema::UI().drawElement("tabs.send", "error-icon-x-offset").size, iy + body2->LegacySize * 0.5f - iSz.y * 0.5f), + Error(), errIcon); + } + + // Error text (wrapped) + fgDl->AddText(body2, body2->LegacySize, ImVec2(ix + schema::UI().drawElement("tabs.send", "error-text-x-offset").size, iy), Error(), + s_tx_status.c_str(), s_tx_status.c_str() + s_tx_status.size(), textWrapW); + + // Buttons row — use invisible window for interactive widgets on top of overlay + float btnY = iy + textSz.y + Layout::spacingMd(); + ImGui::SetNextWindowPos(ImVec2(ix, btnY)); + ImGui::SetNextWindowSize(ImVec2(w - pad * 2, btnH + schema::UI().drawElement("tabs.send", "error-btn-area-padding").size)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + ImGui::Begin("##ErrOverlayBtns", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoFocusOnAppearing | + ImGuiWindowFlags_NoBringToFrontOnFocus); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "error-btn-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)schema::UI().drawElement("tabs.send", "error-btn-hover-alpha").size))); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("tabs.send", "error-btn-rounding").size); + if (TactileSmallButton("Copy Error##txErr", schema::UI().resolveFont("button"))) { + ImGui::SetClipboardText(s_tx_status.c_str()); + Notifications::instance().info("Error copied to clipboard"); + } + ImGui::SameLine(); + if (TactileSmallButton("Dismiss##txErr", schema::UI().resolveFont("button"))) { + s_tx_status.clear(); + s_result_txid.clear(); + s_status_success = false; + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); + ImGui::End(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); + + // Restore cursor — no layout displacement + ImGui::SetCursorScreenPos(savedCursor); + return; + } + + // ---- SENDING / SUCCESS: inline progress card ---- + float progCardH = schema::UI().drawElement("tabs.send", "progress-card-height").size; + float progCardHTxid = schema::UI().drawElement("tabs.send", "progress-card-height-txid").size; + float progH = s_result_txid.empty() ? progCardH : progCardHTxid; + ImVec2 pMin(x, y); + ImVec2 pMax(x + w, y + progH); + + GlassPanelSpec progGlass; + progGlass.rounding = Layout::glassRounding() * schema::UI().drawElement("tabs.send", "progress-glass-rounding-ratio").size; + DrawGlassPanel(dl, pMin, pMax, progGlass); + + float progPadX = schema::UI().drawElement("tabs.send", "progress-card-pad-x").size; + float progPadY = schema::UI().drawElement("tabs.send", "progress-card-pad-y").size; + float ix = pMin.x + progPadX; + float iy = pMin.y + progPadY; + char buf[128]; + + if (s_sending) { + // Spinning refresh icon + ImFont* iconFont = material::Type().iconMed(); + const char* spinIcon = ICON_MD_REFRESH; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, spinIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(ix, iy), Primary(), spinIcon); + double elapsed = ImGui::GetTime() - s_send_start_time; + snprintf(buf, sizeof(buf), "Submitting transaction... (%.0fs)", elapsed); + dl->AddText(body2, body2->LegacySize, ImVec2(ix + iSz.x + schema::UI().drawElement("tabs.send", "progress-icon-text-gap").size, iy), OnSurface(), buf); + } else { + // Success checkmark + ImFont* iconFont = material::Type().iconMed(); + const char* checkIcon = ICON_MD_CHECK; + ImVec2 iSz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, checkIcon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(ix, iy), Success(), checkIcon); + dl->AddText(body2, body2->LegacySize, ImVec2(ix + iSz.x + schema::UI().drawElement("tabs.send", "progress-icon-text-gap").size, iy), Success(), "Transaction sent!"); + + if (!s_result_txid.empty()) { + float txY = iy + body2->LegacySize + schema::UI().drawElement("tabs.send", "txid-y-offset").size; + int txidThreshold = (int)schema::UI().drawElement("tabs.send", "txid-display-threshold").size; + int txidTruncLen = (int)schema::UI().drawElement("tabs.send", "txid-trunc-len").size; + std::string dispTxid = (int)s_result_txid.length() > txidThreshold + ? s_result_txid.substr(0, txidTruncLen) + "..." + s_result_txid.substr(s_result_txid.length() - txidTruncLen) + : s_result_txid; + snprintf(buf, sizeof(buf), "TxID: %s", dispTxid.c_str()); + dl->AddText(capFont, capFont->LegacySize, ImVec2(ix + schema::UI().drawElement("tabs.send", "txid-label-x-offset").size, txY), + OnSurfaceDisabled(), buf); + ImGui::SetCursorScreenPos(ImVec2(pMax.x - schema::UI().drawElement("tabs.send", "txid-copy-btn-right-offset").size, txY - schema::UI().drawElement("tabs.send", "txid-copy-btn-y-offset").size)); + if (TactileSmallButton("Copy##TxID", schema::UI().resolveFont("button"))) { + ImGui::SetClipboardText(s_result_txid.c_str()); + Notifications::instance().info("TxID copied to clipboard"); + } + } + } + + ImGui::SetCursorScreenPos(ImVec2(pMin.x, pMax.y)); + ImGui::Dummy(ImVec2(w, 0)); +} + +// ============================================================================ +// Confirmation dialog +// ============================================================================ +void RenderSendConfirmPopup(App* app) { + if (!s_show_confirm) return; + + // Called every frame while the popup should be visible. + // OpenPopup is idempotent when the popup is already open. + ImGui::OpenPopup(TR("confirm_send")); + bool is_valid_z = (s_to_address[0] == 'z' && s_to_address[1] == 's' && strlen(s_to_address) > 60); + auto& S = schema::UI(); + const auto& state = app->getWalletState(); + const auto& market = state.market; + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* body2 = Type().body2(); + char buf[128]; + + double total = s_amount + s_fee; + + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + float popupAvailW = ImGui::GetMainViewport()->Size.x * S.drawElement("tabs.send", "confirm-popup-width-ratio").size; + float popupW = std::min(schema::UI().drawElement("tabs.send", "confirm-popup-max-width").size, popupAvailW); + float popVs = Layout::vScale(); + ImGui::SetNextWindowSize(ImVec2(popupW, 0), ImGuiCond_Always); + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(Layout::spacingXl(), Layout::spacingLg())); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal(TR("confirm_send"), nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize, acrylicTheme.popup)) { + + if (ImGui::IsKeyPressed(ImGuiKey_Escape) && !s_sending) { + s_show_confirm = false; + ImGui::CloseCurrentPopup(); + } + + float popW = ImGui::GetContentRegionAvail().x; + ImDrawList* popDl = ImGui::GetWindowDrawList(); + + Type().text(TypeStyle::H6, TR("confirm_transaction")); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + float addrCardH = std::max(schema::UI().drawElement("tabs.send", "confirm-addr-card-min-height").size, schema::UI().drawElement("tabs.send", "confirm-addr-card-height").size * popVs); + float popGlassRound = Layout::glassRounding() * S.drawElement("tabs.send", "confirm-glass-rounding-ratio").size; + + // FROM card + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "FROM"); + ImVec2 cMin = ImGui::GetCursorScreenPos(); + ImVec2 cMax(cMin.x + popW, cMin.y + addrCardH); + GlassPanelSpec gs; gs.rounding = popGlassRound; + DrawGlassPanel(popDl, cMin, cMax, gs); + popDl->AddText(body2, body2->LegacySize, + ImVec2(cMin.x + Layout::spacingMd(), cMin.y + Layout::spacingSm()), + Success(), TruncateAddress(s_from_address, (size_t)S.drawElement("tabs.send", "confirm-addr-trunc-len").size).c_str()); + ImGui::Dummy(ImVec2(popW, addrCardH)); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + // TO card + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TO"); + ImVec2 cMin = ImGui::GetCursorScreenPos(); + ImVec2 cMax(cMin.x + popW, cMin.y + addrCardH); + GlassPanelSpec gs; gs.rounding = popGlassRound; + DrawGlassPanel(popDl, cMin, cMax, gs); + popDl->AddText(body2, body2->LegacySize, + ImVec2(cMin.x + Layout::spacingMd(), cMin.y + Layout::spacingSm()), + Success(), TruncateAddress(s_to_address, (size_t)S.drawElement("tabs.send", "confirm-addr-trunc-len").size).c_str()); + ImGui::Dummy(ImVec2(popW, addrCardH)); + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + } + + // Fee tier selector + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "NETWORK FEE"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + RenderFeeTierSelector("##confirm"); + // Recalculate total after potential fee change + total = s_amount + s_fee; + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + } + + // Amount / Fee / Total summary + { + float valX = std::max(schema::UI().drawElement("tabs.send", "confirm-val-col-min-x").size, schema::UI().drawElement("tabs.send", "confirm-val-col-x").size * popVs); + float usdX = popW - std::max(schema::UI().drawElement("tabs.send", "confirm-usd-col-min-x").size, schema::UI().drawElement("tabs.send", "confirm-usd-col-x").size * popVs); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "AMOUNT DETAILS"); + ImVec2 cMin = ImGui::GetCursorScreenPos(); + float cH = std::max(schema::UI().drawElement("tabs.send", "confirm-amount-card-min-height").size, schema::UI().drawElement("tabs.send", "confirm-amount-card-height").size * popVs); + ImVec2 cMax(cMin.x + popW, cMin.y + cH); + GlassPanelSpec gs; gs.rounding = popGlassRound; + DrawGlassPanel(popDl, cMin, cMax, gs); + + float cx = cMin.x + Layout::spacingMd() + Layout::spacingXs(); + float cy = cMin.y + Layout::spacingSm() + Layout::spacingXs(); + float rowStep = std::max(schema::UI().drawElement("tabs.send", "confirm-row-step-min").size, schema::UI().drawElement("tabs.send", "confirm-row-step").size * popVs); + + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), "Amount"); + snprintf(buf, sizeof(buf), "%.8f %s", s_amount, DRAGONX_TICKER); + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx + valX, cy), OnSurface(), buf); + if (market.price_usd > 0) { + snprintf(buf, sizeof(buf), "$%.4f", s_amount * market.price_usd); + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx + usdX, cy), OnSurfaceDisabled(), buf); + } + cy += rowStep; + + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), "Fee"); + snprintf(buf, sizeof(buf), "%.8f %s", s_fee, DRAGONX_TICKER); + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx + valX, cy), OnSurface(), buf); + if (market.price_usd > 0) { + snprintf(buf, sizeof(buf), "$%.6f", s_fee * market.price_usd); + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx + usdX, cy), OnSurfaceDisabled(), buf); + } + cy += Layout::spacingSm(); + popDl->AddLine(ImVec2(cx, cy + Layout::spacingMd()), + ImVec2(cx + popW - Layout::spacingXl(), cy + Layout::spacingMd()), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.send", "confirm-divider-thickness").size); + cy += rowStep; + + popDl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), "Total"); + snprintf(buf, sizeof(buf), "%.8f %s", total, DRAGONX_TICKER); + DrawTextShadow(popDl, sub1, sub1->LegacySize, ImVec2(cx + valX, cy), Primary(), buf); + if (market.price_usd > 0) { + snprintf(buf, sizeof(buf), "$%.4f", total * market.price_usd); + popDl->AddText(capFont, capFont->LegacySize, ImVec2(cx + usdX, cy + S.drawElement("tabs.send", "confirm-usd-y-offset").size), OnSurfaceDisabled(), buf); + } + ImGui::Dummy(ImVec2(popW, cH)); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + if (s_memo[0] != '\0' && is_valid_z) { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MEMO"); + Type().textColored(TypeStyle::Caption, OnSurface(), s_memo); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + if (s_sending) { + Type().text(TypeStyle::Body2, "Sending..."); + } else { + if (TactileButton(TR("confirm_and_send"), ImVec2(S.button("tabs.send", "confirm-button").width, std::max(schema::UI().drawElement("tabs.send", "confirm-btn-min-height").size, schema::UI().drawElement("tabs.send", "confirm-btn-base-height").size * popVs)), S.resolveFont(S.button("tabs.send", "confirm-button").font))) { + s_sending = true; + s_send_start_time = ImGui::GetTime(); + s_tx_status = std::string(TR("sending")) + "..."; + + std::string memo_str = (is_valid_z && s_memo[0]) ? s_memo : ""; + + app->sendTransaction( + s_from_address, + s_to_address, + s_amount, + s_fee, + memo_str, + [](bool success, const std::string& result) { + s_sending = false; + s_status_timestamp = ImGui::GetTime(); + if (success) { + s_tx_status = "Transaction sent!"; + s_result_txid = result; + s_status_success = true; + Notifications::instance().success("Transaction sent successfully!"); + s_to_address[0] = '\0'; + s_amount = 0.0; + s_memo[0] = '\0'; + s_send_max = false; + } else { + s_tx_status = "Error: " + result; + s_result_txid.clear(); + s_status_success = false; + Notifications::instance().error("Transaction failed: " + result); + } + } + ); + s_show_confirm = false; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (TactileButton("Cancel", ImVec2(S.button("tabs.send", "cancel-button").width, std::max(schema::UI().drawElement("tabs.send", "confirm-btn-min-height").size, schema::UI().drawElement("tabs.send", "confirm-btn-base-height").size * popVs)), S.resolveFont(S.button("tabs.send", "cancel-button").font))) { + s_show_confirm = false; + ImGui::CloseCurrentPopup(); + } + } + + effects::ImGuiAcrylic::EndAcrylicPopup(); + } else { + // BeginPopupModal returned false — popup was closed externally + s_show_confirm = false; + } + ImGui::PopStyleVar(); +} + +// ============================================================================ +// Zero balance CTA +// ============================================================================ +static bool RenderZeroBalanceCTA(App* app, ImDrawList* dl, float width) { + const auto& state = app->getWalletState(); + double totalBal = 0.0; + for (const auto& a : state.addresses) totalBal += a.balance; + if (!app->isConnected() || state.addresses.empty() || totalBal > 0.0) + return false; + + ImFont* sub1 = Type().subtitle1(); + ImFont* capFont = Type().caption(); + + ImVec2 ctaMin = ImGui::GetCursorScreenPos(); + float ctaH = schema::UI().drawElement("tabs.send", "cta-height").size; + ImVec2 ctaMax(ctaMin.x + width, ctaMin.y + ctaH); + GlassPanelSpec ctaGlass; + ctaGlass.rounding = Layout::glassRounding(); + DrawGlassPanel(dl, ctaMin, ctaMax, ctaGlass); + + float cx = ctaMin.x + Layout::spacingXl(); + float cy = ctaMin.y + Layout::spacingLg(); + dl->AddText(sub1, sub1->LegacySize, ImVec2(cx, cy), OnSurface(), "Your wallet is empty"); + cy += sub1->LegacySize + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceMedium(), + "Switch to Receive to get your address and start receiving funds."); + cy += capFont->LegacySize + Layout::spacingMd(); + ImGui::SetCursorScreenPos(ImVec2(cx, cy)); + if (TactileButton("Go to Receive", ImVec2(schema::UI().drawElement("tabs.send", "cta-button-width").size, schema::UI().drawElement("tabs.send", "cta-button-height").size), schema::UI().resolveFont("button"))) { + app->setCurrentPage(NavPage::Receive); + } + ImGui::SetCursorScreenPos(ImVec2(ctaMin.x, ctaMax.y + Layout::spacingLg())); + ImGui::Dummy(ImVec2(width, 0)); + return true; +} + +// ============================================================================ +// Action buttons (Send + Clear + Undo) +// ============================================================================ +static void RenderActionButtons(App* app, float width, float vScale, + bool is_valid_address, double available, + const char* suffix = "") { + auto& S = schema::UI(); + const auto& state = app->getWalletState(); + double total = s_amount + s_fee; + bool can_send = app->isConnected() && + !state.sync.syncing && + is_valid_address && + s_amount > 0 && + s_from_address[0] != '\0' && + total <= available && + !s_sending; + + float btnGap = Layout::spacingMd(); + float cancelBtnW = std::max(schema::UI().drawElement("tabs.send", "cancel-btn-min-width").size, width * S.drawElement("tabs.send", "cancel-btn-width-ratio").size); + float sendBtnW = width - cancelBtnW - btnGap; + float btnH = std::max(schema::UI().drawElement("tabs.send", "action-btn-min-height").size, schema::UI().drawElement("tabs.send", "action-btn-height").size * vScale); + + // ---- Send button ---- + if (!can_send) { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "disabled-btn-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "disabled-btn-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled())); + } + + ImGui::BeginDisabled(!can_send); + char sendId[64]; + snprintf(sendId, sizeof(sendId), "Review Send%s", suffix); + if (TactileButton(sendId, ImVec2(sendBtnW, btnH), S.resolveFont(S.button("tabs.send", "send-button").font))) { + s_show_confirm = true; + } + ImGui::EndDisabled(); + + if (!can_send && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + if (!app->isConnected()) + ImGui::SetTooltip("Not connected to daemon"); + else if (state.sync.syncing) + ImGui::SetTooltip("Blockchain is still syncing"); + else if (s_from_address[0] == '\0') + ImGui::SetTooltip("Select a source address above"); + else if (!is_valid_address) + ImGui::SetTooltip("Enter a valid recipient address"); + else if (s_amount <= 0) + ImGui::SetTooltip("Enter an amount to send"); + else if (total > available) + ImGui::SetTooltip("Amount exceeds available balance"); + else if (s_sending) + ImGui::SetTooltip("Transaction in progress..."); + } + if (!can_send) ImGui::PopStyleColor(3); + + // ---- Cancel button (same line) ---- + ImGui::SameLine(0, btnGap); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "cancel-btn-hover-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_Border, ImGui::ColorConvertU32ToFloat4(OnSurfaceDisabled())); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, S.drawElement("tabs.send", "cancel-btn-border-size").size); + char clearId[64]; + snprintf(clearId, sizeof(clearId), "Cancel%s", suffix); + if (TactileButton(clearId, ImVec2(cancelBtnW, btnH), S.resolveFont(S.button("tabs.send", "clear-button").font))) { + if (FormHasData()) { + s_clear_confirm_pending = true; + } else { + ClearFormWithUndo(); + } + } + ImGui::PopStyleVar(); // FrameBorderSize + ImGui::PopStyleColor(3); + + // Clear confirmation popup + char confirmClearId[32]; + snprintf(confirmClearId, sizeof(confirmClearId), "##ConfirmClear%s", suffix); + if (s_clear_confirm_pending) { + ImGui::OpenPopup(confirmClearId); + s_clear_confirm_pending = false; + } + if (ImGui::BeginPopup(confirmClearId)) { + ImGui::Text("Clear all form fields?"); + ImGui::Spacing(); + if (TactileButton("Yes, Clear", ImVec2(schema::UI().drawElement("tabs.send", "clear-confirm-yes-width").size, 0), S.resolveFont("button"))) { + ClearFormWithUndo(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (TactileButton("Keep", ImVec2(schema::UI().drawElement("tabs.send", "clear-confirm-keep-width").size, 0), S.resolveFont("button"))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + + // Undo button (shown briefly after clear) + if (s_undo_timestamp > 0.0) { + double undoElapsed = ImGui::GetTime() - s_undo_timestamp; + if (undoElapsed < UNDO_TIMEOUT) { + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + float undoAlpha = (float)std::max(0.0, 1.0 - undoElapsed / UNDO_TIMEOUT); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, undoAlpha); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(WithAlpha(Warning(), (int)S.drawElement("tabs.send", "undo-btn-bg-alpha").size))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(WithAlpha(Warning(), (int)S.drawElement("tabs.send", "undo-btn-hover-alpha").size))); + char undoId[32]; + snprintf(undoId, sizeof(undoId), "Undo Clear%s", suffix); + if (TactileButton(undoId, ImVec2(width, btnH), S.resolveFont("button"))) { + RestoreFormSnapshot(); + Notifications::instance().info("Form restored"); + } + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(); + } else { + s_undo_timestamp = 0.0; + } + } +} + +// ============================================================================ +// Recent Sends section — styled to match transactions list +// ============================================================================ +static void RenderRecentSends(ImDrawList* dl, const WalletState& state, + float width, ImFont* capFont, App* app) { + auto& S = schema::UI(); + ImGui::Dummy(ImVec2(0, Layout::spacingLg())); + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECENT SENDS"); + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + ImVec2 avail = ImGui::GetContentRegionAvail(); + float hs = Layout::hScale(avail.x); + float glassRound = Layout::glassRounding(); + + ImFont* body2 = Type().body2(); + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd(); + float iconSz = std::max(schema::UI().drawElement("tabs.send", "recent-icon-min-size").size, schema::UI().drawElement("tabs.send", "recent-icon-size").size * hs); + ImU32 sendCol = Error(); + ImU32 greenCol = WithAlpha(Success(), (int)S.drawElement("tabs.send", "recent-green-alpha").size); + float rowPadLeft = Layout::spacingLg(); + + // Collect matching transactions + std::vector sends; + for (const auto& tx : state.transactions) { + if (tx.type != "send") continue; + sends.push_back(&tx); + if (sends.size() >= (size_t)S.drawElement("tabs.send", "max-recent-sends").size) break; + } + + if (sends.empty()) { + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), "No recent sends"); + return; + } + + // Outer glass panel wrapping all rows + float itemSpacingY = ImGui::GetStyle().ItemSpacing.y; + float listH = rowH * (float)sends.size() + itemSpacingY * (float)(sends.size() - 1); + ImVec2 listPanelMin = ImGui::GetCursorScreenPos(); + float listW = width; + ImVec2 listPanelMax(listPanelMin.x + listW, listPanelMin.y + listH); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + DrawGlassPanel(dl, listPanelMin, listPanelMax, glassSpec); + + // Clip draw commands to panel bounds to prevent overflow + dl->PushClipRect(listPanelMin, listPanelMax, true); + + char buf[64]; + for (size_t si = 0; si < sends.size(); si++) { + const auto& tx = *sends[si]; + + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + float innerW = listW; + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + + // Hover glow + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "row-hover-alpha").size), schema::UI().drawElement("tabs.send", "row-hover-rounding").size); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) { + app->setCurrentPage(ui::NavPage::History); + } + } + + float cx = rowPos.x + rowPadLeft; + float cy = rowPos.y + Layout::spacingMd(); + + // Icon + DrawTxIcon(dl, tx.type, cx + iconSz, cy + body2->LegacySize * 0.5f, iconSz, sendCol); + + // Type label (first line) + float labelX = cx + iconSz * 2.0f + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy), sendCol, "Sent"); + + // Time (next to type) + std::string ago = timeAgo(tx.timestamp); + float typeW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, "Sent").x; + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX + typeW + Layout::spacingLg(), cy), + OnSurfaceDisabled(), ago.c_str()); + + // Address (second line) + std::string addr_display = TruncateAddress(tx.address, (int)S.drawElement("tabs.send", "recent-addr-trunc-len").size); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceMedium(), addr_display.c_str()); + + // Amount (right-aligned, first line) + snprintf(buf, sizeof(buf), "-%.8f", std::abs(tx.amount)); + ImVec2 amtSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, buf); + float amtX = rowPos.x + innerW - amtSz.x - Layout::spacingLg(); + DrawTextShadow(dl, body2, body2->LegacySize, ImVec2(amtX, cy), sendCol, buf, + S.drawElement("tabs.send", "text-shadow-offset-x").size, S.drawElement("tabs.send", "text-shadow-offset-y").size, IM_COL32(0, 0, 0, (int)S.drawElement("tabs.send", "text-shadow-alpha").size)); + + // USD equivalent (right-aligned, second line) + double priceUsd = state.market.price_usd; + if (priceUsd > 0.0) { + double usdVal = std::abs(tx.amount) * priceUsd; + if (usdVal >= 1.0) + snprintf(buf, sizeof(buf), "$%.2f", usdVal); + else if (usdVal >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", usdVal); + else + snprintf(buf, sizeof(buf), "$%.6f", usdVal); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowPos.x + innerW - usdSz.x - Layout::spacingLg(), cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceDisabled(), buf); + } + + // Status badge + { + const char* statusStr; + ImU32 statusCol; + if (tx.confirmations == 0) { + statusStr = "Pending"; statusCol = Warning(); + } else if (tx.confirmations < (int)S.drawElement("tabs.send", "confirmed-threshold").size) { + snprintf(buf, sizeof(buf), "%d conf", tx.confirmations); + statusStr = buf; statusCol = Warning(); + } else { + statusStr = "Confirmed"; statusCol = greenCol; + } + ImVec2 sSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, statusStr); + float statusX = amtX - sSz.x - Layout::spacingXxl(); + float minStatusX = cx + innerW * S.drawElement("tabs.send", "status-min-x-ratio").size; + if (statusX < minStatusX) statusX = minStatusX; + ImU32 pillBg = (statusCol & 0x00FFFFFFu) | (static_cast((int)S.drawElement("tabs.send", "status-pill-bg-alpha").size) << 24); + ImVec2 pillMin(statusX - Layout::spacingSm(), cy + body2->LegacySize + (int)S.drawElement("tabs.send", "status-pill-y-offset").size); + ImVec2 pillMax(statusX + sSz.x + Layout::spacingSm(), pillMin.y + capFont->LegacySize + Layout::spacingXs()); + dl->AddRectFilled(pillMin, pillMax, pillBg, schema::UI().drawElement("tabs.send", "status-pill-rounding").size); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(statusX, cy + body2->LegacySize + Layout::spacingXs()), statusCol, statusStr); + } + + ImGui::Dummy(ImVec2(0, rowH)); + + // Subtle divider between rows + if (si < sends.size() - 1) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(divStart.x + rowPadLeft + iconSz * 2.0f, divStart.y), + ImVec2(divStart.x + innerW - Layout::spacingLg(), divStart.y), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "row-divider-alpha").size)); + } + } + + dl->PopClipRect(); +} + +// ============================================================================ +// MAIN: RenderSendTab — Layout E: Top Bar Source + Bottom Form +// ============================================================================ +void RenderSendTab(App* app) +{ + const auto& state = app->getWalletState(); + const auto& market = state.market; + auto& S = schema::UI(); + + // Handle pending payment from URI + if (app->hasPendingPayment()) { + strncpy(s_to_address, app->getPendingToAddress().c_str(), sizeof(s_to_address) - 1); + s_amount = app->getPendingAmount(); + strncpy(s_memo, app->getPendingMemo().c_str(), sizeof(s_memo) - 1); + app->clearPendingPayment(); + } + + RenderSyncBanner(state); + + bool sendSyncing = state.sync.syncing && !state.sync.isSynced(); + ImGui::BeginDisabled(sendSyncing); + + ImVec2 sendAvail = ImGui::GetContentRegionAvail(); + float hs = Layout::hScale(sendAvail.x); + float vScale = Layout::vScale(sendAvail.y); + float glassRound = Layout::glassRounding(); + + float availWidth = sendAvail.x; + + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImFont* capFont = Type().caption(); + ImFont* sub1 = Type().subtitle1(); + ImFont* body2 = Type().body2(); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + + double available = GetAvailableBalance(app); + bool is_valid_z = (s_to_address[0] == 'z' && s_to_address[1] == 's' && strlen(s_to_address) > 60); + bool is_valid_t = (s_to_address[0] == 'R' && strlen(s_to_address) >= 34); + bool is_valid_address = is_valid_z || is_valid_t; + float sectionGap = Layout::spacingXl() * vScale; + + char buf[128]; + + // ================================================================ + // SCROLLABLE CONTENT + // ================================================================ + ImVec2 formAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##SendFormScroll", formAvail, false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + dl = ImGui::GetWindowDrawList(); + + // Top-aligned content — consistent vertical position across all tabs + static float s_sendContentH = 0; + float scrollAvailH = ImGui::GetContentRegionAvail().y; + float groupStartY = ImGui::GetCursorPosY(); + float contentStartY = ImGui::GetCursorPosY(); + + float formAvailW = ImGui::GetContentRegionAvail().x; + float formW = formAvailW; + ImGui::BeginGroup(); + + // Zero balance CTA + if (RenderZeroBalanceCTA(app, dl, formW)) { + ImGui::EndGroup(); + ImGui::EndDisabled(); // sendSyncing guard + ImGui::EndChild(); + return; + } + + // ================================================================ + // COMPOSE FORM — single container for all fields + // ================================================================ + { + ImVec2 containerMin = ImGui::GetCursorScreenPos(); + float pad = Layout::spacingLg(); + float innerW = formW - pad * 2; + float innerGap = Layout::spacingMd() * vScale; + + // Single-column layout + float colW = innerW; + + // Channel split: content on ch1, glass background on ch0 + dl->ChannelsSplit(2); + dl->ChannelsSetCurrent(1); + + // Indent content by pad so every line is inset from the card edges + ImGui::Indent(pad); + ImGui::Dummy(ImVec2(0, pad * vScale)); // top padding + + // ---- SOURCE ADDRESS ---- + RenderSourceDropdown(app, colW); + + // Divider between source and recipient + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + { + ImVec2 divPos = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(containerMin.x + pad, divPos.y), + ImVec2(containerMin.x + pad + colW, divPos.y), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.send", "divider-thickness").size); + } + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + + // ---- RECIPIENT ---- + { + // Static preview state (declared early for title indicator) + static bool s_paste_previewing = false; + static std::string s_preview_text; + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "RECIPIENT"); + + // Validation indicator — inline next to title (no height change) + // Check the preview text during hover, otherwise check actual address + const char* validAddr = s_to_address; + bool checkPreview = false; + if (s_paste_previewing && !s_preview_text.empty()) { + validAddr = s_preview_text.c_str(); + checkPreview = true; + } + if (validAddr[0] != '\0') { + bool vz = (validAddr[0] == 'z' && validAddr[1] == 's' && strlen(validAddr) > 60); + bool vt = (validAddr[0] == 'R' && strlen(validAddr) >= 34); + if (vz || vt) { + ImGui::SameLine(); + if (vz) + Type().textColored(TypeStyle::Caption, Success(), "Valid shielded address"); + else + Type().textColored(TypeStyle::Caption, Warning(), "Valid transparent address"); + } else if (!checkPreview) { + ImGui::SameLine(); + Type().textColored(TypeStyle::Caption, Error(), TR("invalid_address")); + } + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + float pasteW = std::max(schema::UI().drawElement("tabs.send", "paste-btn-min-width").size, colW * schema::UI().drawElement("tabs.send", "paste-btn-width-ratio").size); + ImGui::PushItemWidth(colW - pasteW - Layout::spacingSm()); + + // Show clipboard preview as transparent overlay when paste button is hovered + bool paste_hovered = false; + + ImGui::InputText("##ToAddr", s_to_address, sizeof(s_to_address)); + // Capture input rect for preview overlay + ImVec2 inputMin = ImGui::GetItemRectMin(); + ImGui::PopItemWidth(); + ImGui::SameLine(); + + // Detect hover BEFORE the button click + ImVec2 pasteBtnPos = ImGui::GetCursorScreenPos(); + ImVec2 pasteBtnSize(pasteW, ImGui::GetFrameHeight()); + paste_hovered = material::IsRectHovered(pasteBtnPos, + ImVec2(pasteBtnPos.x + pasteBtnSize.x, pasteBtnPos.y + pasteBtnSize.y)); + + // Handle preview state — don't modify s_to_address, just store preview text + if (paste_hovered && !s_paste_previewing) { + const char* clip = ImGui::GetClipboardText(); + if (clip && clip[0] != '\0') { + std::string trimmed(clip); + while (!trimmed.empty() && (trimmed.front() == ' ' || trimmed.front() == '\n' || trimmed.front() == '\r' || trimmed.front() == '\t')) + trimmed.erase(trimmed.begin()); + while (!trimmed.empty() && (trimmed.back() == ' ' || trimmed.back() == '\n' || trimmed.back() == '\r' || trimmed.back() == '\t')) + trimmed.pop_back(); + bool looksValid = (trimmed.size() > 30 && + ((trimmed[0] == 'z' && trimmed[1] == 's') || trimmed[0] == 'R')); + if (looksValid && s_to_address[0] == '\0') { + s_preview_text = trimmed; + s_paste_previewing = true; + } + } + } else if (!paste_hovered && s_paste_previewing) { + s_paste_previewing = false; + s_preview_text.clear(); + } + + // Draw transparent preview text overlay on the input field + if (s_paste_previewing && !s_preview_text.empty()) { + ImVec2 textPos(inputMin.x + ImGui::GetStyle().FramePadding.x, + inputMin.y + ImGui::GetStyle().FramePadding.y); + ImVec4 previewCol = ImGui::GetStyleColorVec4(ImGuiCol_Text); + previewCol.w = S.drawElement("tabs.send", "paste-preview-alpha").size; + ImGui::GetWindowDrawList()->AddText(textPos, ImGui::ColorConvertFloat4ToU32(previewCol), + s_preview_text.c_str(), s_preview_text.c_str() + std::min(s_preview_text.size(), (size_t)S.drawElement("tabs.send", "paste-preview-max-chars").size)); + } + + if (TactileButton("Paste##to", ImVec2(pasteW, 0), S.resolveFont(S.button("tabs.send", "paste-button").font))) { + if (s_paste_previewing) { + // Commit the preview + snprintf(s_to_address, sizeof(s_to_address), "%s", s_preview_text.c_str()); + s_paste_previewing = false; + s_preview_text.clear(); + } else { + PasteClipboardToAddress(); + } + } + + // Recently sent-to suggestions + RenderAddressSuggestions(state, colW, "##AddrSugForm"); + } + + // Divider + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + { + ImVec2 divPos = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(containerMin.x + pad, divPos.y), + ImVec2(containerMin.x + pad + colW, divPos.y), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.send", "divider-thickness").size); + } + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + + // ---- AMOUNT ---- + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "AMOUNT"); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Toggle between DRGX and USD input + float toggleW = schema::UI().drawElement("tabs.send", "toggle-currency-width").size; + float amtInputW = colW - toggleW - Layout::spacingMd(); + if (amtInputW < schema::UI().drawElement("tabs.send", "amount-input-min-width").size) amtInputW = schema::UI().drawElement("tabs.send", "amount-input-min-width").size; + + if (s_input_usd && market.price_usd > 0) { + // USD input mode — no step buttons (step=0) + ImGui::PushItemWidth(amtInputW); + if (ImGui::InputDouble("##AmountUSD", &s_usd_amount, 0, 0, "$%.2f")) { + s_amount = s_usd_amount / market.price_usd; + } + // Draw DRGX equivalent inside the input field (right-aligned overlay) + { + ImVec2 iMin = ImGui::GetItemRectMin(); + ImVec2 iMax = ImGui::GetItemRectMax(); + snprintf(buf, sizeof(buf), "\xe2\x89\x88 %.4f %s", s_amount, DRAGONX_TICKER); + ImFont* font = capFont; + ImVec2 sz = font->CalcTextSizeA(font->LegacySize, 10000, 0, buf); + float tx = iMax.x - sz.x - ImGui::GetStyle().FramePadding.x; + float ty = iMin.y + (iMax.y - iMin.y - sz.y) * 0.5f; + dl->AddText(font, font->LegacySize, ImVec2(tx, ty), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "input-overlay-text-alpha").size), buf); + } + ImGui::PopItemWidth(); + } else { + // DRGX input mode — no step buttons (step=0) + ImGui::PushItemWidth(amtInputW); + if (ImGui::InputDouble("##Amount", &s_amount, 0, 0, "%.8f")) { + if (market.price_usd > 0) + s_usd_amount = s_amount * market.price_usd; + } + // Draw USD equivalent inside the input field (right-aligned overlay) + if (market.price_usd > 0 && s_amount > 0) { + ImVec2 iMin = ImGui::GetItemRectMin(); + ImVec2 iMax = ImGui::GetItemRectMax(); + double usd_value = s_amount * market.price_usd; + if (usd_value >= 0.01) + snprintf(buf, sizeof(buf), "\xe2\x89\x88 $%.2f", usd_value); + else + snprintf(buf, sizeof(buf), "\xe2\x89\x88 $%.6f", usd_value); + ImFont* font = capFont; + ImVec2 sz = font->CalcTextSizeA(font->LegacySize, 10000, 0, buf); + float tx = iMax.x - sz.x - ImGui::GetStyle().FramePadding.x; + float ty = iMin.y + (iMax.y - iMin.y - sz.y) * 0.5f; + dl->AddText(font, font->LegacySize, ImVec2(tx, ty), + IM_COL32(255, 255, 255, (int)S.drawElement("tabs.send", "input-overlay-text-alpha").size), buf); + } + ImGui::PopItemWidth(); + } + + // Toggle button — shows current mode with swap icon + ImGui::SameLine(0, Layout::spacingMd()); + { + const char* currLabel = s_input_usd ? "DRGX" : "USD"; + bool canToggle = (market.price_usd > 0); + ImGui::BeginDisabled(!canToggle); + if (TactileButton("##ToggleCurrency", ImVec2(toggleW, 0), S.resolveFont("button"))) { + s_input_usd = !s_input_usd; + if (s_input_usd && market.price_usd > 0) + s_usd_amount = s_amount * market.price_usd; + } + // Draw swap arrows icon + label centered on button + { + ImVec2 bMin = ImGui::GetItemRectMin(); + ImVec2 bMax = ImGui::GetItemRectMax(); + float bH = bMax.y - bMin.y; + ImFont* font = ImGui::GetFont(); + ImVec2 textSz = font->CalcTextSizeA(font->LegacySize, 10000, 0, currLabel); + float iconW = schema::UI().drawElement("tabs.send", "swap-icon-width").size; + float iconGap = schema::UI().drawElement("tabs.send", "swap-icon-gap").size; + float totalW = iconW + iconGap + textSz.x; + float startX = bMin.x + ((bMax.x - bMin.x) - totalW) * 0.5f; + float cy = bMin.y + bH * 0.5f; + ImU32 iconCol = ImGui::GetColorU32(ImGuiCol_Text); + float s = iconW * 0.5f; + float cx = startX + s; + // Swap icon (Material Design) + ImFont* swapFont = Type().iconSmall(); + const char* swapIcon = ICON_MD_SWAP_HORIZ; + ImVec2 swapSz = swapFont->CalcTextSizeA(swapFont->LegacySize, 1000.0f, 0.0f, swapIcon); + dl->AddText(swapFont, swapFont->LegacySize, + ImVec2(cx - swapSz.x * 0.5f, cy - swapSz.y * 0.5f), iconCol, swapIcon); + // Text label + float tx = startX + iconW + iconGap; + float ty = cy - textSz.y * 0.5f; + dl->AddText(font, font->LegacySize, ImVec2(tx, ty), iconCol, currLabel); + } + ImGui::EndDisabled(); + } + + // Combined amount bar (slider + usage indicator) + RenderAmountBar(dl, available, colW, capFont, market.price_usd, "##f"); + + // Amount error + if (s_amount > 0 && s_amount + s_fee > available && available > 0) { + snprintf(buf, sizeof(buf), "Exceeds available (%.8f)", available - s_fee); + Type().textColored(TypeStyle::Caption, Error(), buf); + } + } + + // ---- MEMO (shielded only) ---- + if (is_valid_z || s_to_address[0] == '\0') { + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + { + ImVec2 divPos = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(containerMin.x + pad, divPos.y), + ImVec2(containerMin.x + pad + colW, divPos.y), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.send", "divider-thickness").size); + } + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MEMO (OPTIONAL)"); + ImGui::Dummy(ImVec2(0, S.drawElement("tabs.send", "memo-label-gap").size)); + + float memoInputH = std::max(S.drawElement("tabs.send", "memo-min-height").size, S.drawElement("tabs.send", "memo-base-height").size * vScale); + ImGui::PushItemWidth(colW); + ImGui::InputTextMultiline("##Memo", s_memo, sizeof(s_memo), + ImVec2(colW, memoInputH)); + ImGui::PopItemWidth(); + + size_t memo_len = strlen(s_memo); + snprintf(buf, sizeof(buf), "%zu / %d", memo_len, (int)S.drawElement("business", "memo-max-length").size); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + + // Divider before action buttons + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + { + ImVec2 divPos = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(containerMin.x + pad, divPos.y), + ImVec2(containerMin.x + formW - pad, divPos.y), + ImGui::GetColorU32(Divider()), S.drawElement("tabs.send", "divider-thickness").size); + } + ImGui::Dummy(ImVec2(0, innerGap * 0.5f)); + + // ---- ACTION BUTTONS (full width) ---- + RenderActionButtons(app, innerW, vScale, is_valid_address, available, "##main"); + + // Add bottom padding + ImGui::Dummy(ImVec2(0, pad * vScale)); + ImGui::Unindent(pad); + + // Enforce shared card height (matches receive tab) + { + float currentCardH = ImGui::GetCursorScreenPos().y - containerMin.y; + float targetCardH = Layout::mainCardTargetH(formW, vScale); + if (currentCardH < targetCardH) + ImGui::Dummy(ImVec2(0, targetCardH - currentCardH)); + } + + // Draw glass panel background on channel 0 + ImVec2 containerMax(containerMin.x + formW, ImGui::GetCursorScreenPos().y); + dl->ChannelsSetCurrent(0); + DrawGlassPanel(dl, containerMin, containerMax, glassSpec); + dl->ChannelsMerge(); + + ImGui::SetCursorScreenPos(ImVec2(containerMin.x, containerMax.y)); + ImGui::Dummy(ImVec2(formW, 0)); + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + + // Pass card bottom Y so error overlay can anchor to it + float cardBottom = containerMax.y; + + // ---- TRANSACTION PROGRESS ---- + { + ImVec2 progPos = ImGui::GetCursorScreenPos(); + RenderTxProgress(dl, progPos.x, progPos.y, formW, body2, capFont, cardBottom); + if ((!s_tx_status.empty() || s_sending) && + (s_sending || (s_tx_status.find("Error") == std::string::npos && + s_tx_status.find("Failed") == std::string::npos && + s_tx_status.find("error") == std::string::npos))) { + ImGui::Dummy(ImVec2(0, sectionGap)); + } + } + } + + // ---- RECENT SENDS ---- + RenderRecentSends(dl, state, formW, capFont, app); + + ImGui::EndGroup(); + ImGui::EndDisabled(); // sendSyncing guard + // Round to nearest pixel to prevent sub-pixel oscillation (vibration) + // when content like "recent sends" elapsed-time text changes width each frame + float measuredH = ImGui::GetCursorPosY() - contentStartY; + s_sendContentH = std::round(measuredH); + ImGui::EndChild(); // ##SendFormScroll +} + +void SetSendFromAddress(const std::string& address) +{ + strncpy(s_from_address, address.c_str(), sizeof(s_from_address) - 1); + s_from_address[sizeof(s_from_address) - 1] = '\0'; + s_selected_from_idx = -1; +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/send_tab.h b/src/ui/windows/send_tab.h new file mode 100644 index 0000000..8f85007 --- /dev/null +++ b/src/ui/windows/send_tab.h @@ -0,0 +1,34 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Send tab + * Form for sending transactions + */ +void RenderSendTab(App* app); + +/** + * @brief Render the send-confirm modal popup. + * Must be called at the top-level window scope (after ImGui::End of the main + * window) so the modal dim layer blocks ALL input — sidebar, tabs, etc. + */ +void RenderSendConfirmPopup(App* app); + +/** + * @brief Pre-fill the "from" address in the send tab + * @param address The address to send from + */ +void SetSendFromAddress(const std::string& address); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/settings_window.cpp b/src/ui/windows/settings_window.cpp new file mode 100644 index 0000000..88f0202 --- /dev/null +++ b/src/ui/windows/settings_window.cpp @@ -0,0 +1,567 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "settings_window.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../config/settings.h" +#include "../../util/i18n.h" +#include "../../util/platform.h" +#include "../../rpc/rpc_client.h" +#include "../theme.h" +#include "../schema/ui_schema.h" +#include "../schema/skin_manager.h" +#include "../notifications.h" +#include "../effects/imgui_acrylic.h" +#include "../material/draw_helpers.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include + +// Icon text for settings UI +#define ICON_CUSTOM_THEME ICON_MD_TUNE +#define ICON_REFRESH_THEMES ICON_MD_REFRESH + +namespace dragonx { +namespace ui { + +// Settings state - these get loaded from Settings on window open +static bool s_initialized = false; +static int s_language_index = 0; +static bool s_save_ztxs = true; +static bool s_allow_custom_fees = false; +static bool s_auto_shield = false; +static bool s_fetch_prices = true; +static bool s_use_tor = false; +static char s_rpc_host[128] = DRAGONX_DEFAULT_RPC_HOST; +static char s_rpc_port[16] = DRAGONX_DEFAULT_RPC_PORT; +static char s_rpc_user[64] = ""; +static char s_rpc_password[64] = ""; +static char s_tx_explorer[256] = "https://explorer.dragonx.is/tx/"; +static char s_addr_explorer[256] = "https://explorer.dragonx.is/address/"; + +// Acrylic settings +static bool s_acrylic_enabled = true; +static float s_blur_amount = 1.5f; // 0.0=Off, continuous blur multiplier +static float s_noise_opacity = 0.5f; +static bool s_reduced_transparency = false; // Accessibility option +static bool s_gradient_background = false; // Gradient background mode + +// Saved skin ID for cancel/revert +static std::string s_saved_skin_id; + +// Load current settings into UI state +static void loadSettingsToUI(config::Settings* settings) { + if (!settings) return; + + s_saved_skin_id = settings->getSkinId(); + s_save_ztxs = settings->getSaveZtxs(); + s_allow_custom_fees = settings->getAllowCustomFees(); + s_auto_shield = settings->getAutoShield(); + s_fetch_prices = settings->getFetchPrices(); + s_use_tor = settings->getUseTor(); + + strncpy(s_tx_explorer, settings->getTxExplorerUrl().c_str(), sizeof(s_tx_explorer) - 1); + strncpy(s_addr_explorer, settings->getAddressExplorerUrl().c_str(), sizeof(s_addr_explorer) - 1); + + // Set language index + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + std::string current_lang = settings->getLanguage(); + if (current_lang.empty()) current_lang = "en"; + + s_language_index = 0; + int idx = 0; + for (const auto& lang : languages) { + if (lang.first == current_lang) { + s_language_index = idx; + break; + } + idx++; + } + + s_initialized = true; +} + +// Save UI state to settings +static void saveSettingsFromUI(config::Settings* settings) { + if (!settings) return; + + settings->setTheme(settings->getSkinId()); // Theme now synced with skin + settings->setSaveZtxs(s_save_ztxs); + settings->setAllowCustomFees(s_allow_custom_fees); + settings->setAutoShield(s_auto_shield); + settings->setFetchPrices(s_fetch_prices); + settings->setUseTor(s_use_tor); + settings->setTxExplorerUrl(s_tx_explorer); + settings->setAddressExplorerUrl(s_addr_explorer); + + // Save language + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + auto it = languages.begin(); + std::advance(it, s_language_index); + if (it != languages.end()) { + settings->setLanguage(it->first); + } + + // Save acrylic / visual effects settings + settings->setAcrylicEnabled(s_acrylic_enabled); + settings->setAcrylicQuality(s_blur_amount > 0.001f ? static_cast(effects::AcrylicQuality::Low) : static_cast(effects::AcrylicQuality::Off)); + settings->setBlurMultiplier(s_blur_amount); + settings->setReducedTransparency(s_reduced_transparency); + settings->setNoiseOpacity(s_noise_opacity); + settings->setGradientBackground(s_gradient_background); + + settings->save(); +} + +void RenderSettingsWindow(App* app, bool* p_open) +{ + // Load settings on first open + if (!s_initialized && app->settings()) { + loadSettingsToUI(app->settings()); + // Initialize acrylic settings from current state + s_acrylic_enabled = effects::ImGuiAcrylic::IsEnabled(); + s_blur_amount = effects::ImGuiAcrylic::GetBlurMultiplier(); + s_noise_opacity = effects::ImGuiAcrylic::GetNoiseOpacity(); + s_reduced_transparency = effects::ImGuiAcrylic::GetReducedTransparency(); + s_gradient_background = schema::SkinManager::instance().isGradientMode(); + } + + auto& S = schema::UI(); + auto win = S.window("dialogs.settings"); + auto lbl = S.label("dialogs.settings", "label"); + auto cmb = S.combo("dialogs.settings", "combo"); + auto connLbl = S.label("dialogs.settings", "connection-label"); + auto portInput = S.input("dialogs.settings", "port-input"); + auto walletBtn = S.button("dialogs.settings", "wallet-button"); + auto saveBtn = S.button("dialogs.settings", "save-button"); + auto cancelBtn = S.button("dialogs.settings", "cancel-button"); + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + // Use acrylic modal popup + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Settings"); + if (!effects::ImGuiAcrylic::BeginAcrylicPopupModal("Settings", p_open, ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + effects::ImGuiAcrylic::EndAcrylicPopup(); + return; + } + + if (ImGui::BeginTabBar("SettingsTabs")) { + // General settings tab + if (ImGui::BeginTabItem("General")) { + ImGui::Spacing(); + + // Skin/theme selection + ImGui::Text("Theme:"); + ImGui::SameLine(lbl.position); + + // Active skin combo (populated from SkinManager) + auto& skinMgr = schema::SkinManager::instance(); + const auto& skins = skinMgr.available(); + + // Find active skin for preview text + std::string active_preview = "DragonX"; + bool active_is_custom = false; + for (const auto& skin : skins) { + if (skin.id == skinMgr.activeSkinId()) { + active_preview = skin.name; + active_is_custom = !skin.bundled; + break; + } + } + + ImGui::SetNextItemWidth(cmb.width); + if (ImGui::BeginCombo("##Theme", active_preview.c_str())) { + // Bundled themes header + ImGui::TextDisabled("Built-in"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (!skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + + if (ImGui::Selectable(skin.name.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) { + ImGui::SetItemDefaultFocus(); + } + } + + // Custom themes (if any) + bool has_custom = false; + for (const auto& skin : skins) { + if (!skin.bundled) { has_custom = true; break; } + } + if (has_custom) { + ImGui::Spacing(); + ImGui::TextDisabled("Custom"); + ImGui::Separator(); + for (size_t i = 0; i < skins.size(); i++) { + const auto& skin = skins[i]; + if (skin.bundled) continue; + bool is_selected = (skin.id == skinMgr.activeSkinId()); + + if (!skin.valid) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.3f, 0.3f, 1.0f)); + ImGui::BeginDisabled(true); + std::string label = skin.name + " (invalid)"; + ImGui::Selectable(label.c_str(), false); + ImGui::EndDisabled(); + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("%s", skin.validationError.c_str()); + } + } else { + std::string label = skin.name; + if (!skin.author.empty()) { + label += " (" + skin.author + ")"; + } + if (ImGui::Selectable(label.c_str(), is_selected)) { + skinMgr.setActiveSkin(skin.id); + if (app->settings()) { + app->settings()->setSkinId(skin.id); + app->settings()->save(); + } + } + if (is_selected) { + ImGui::SetItemDefaultFocus(); + } + } + } + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Hotkey: Ctrl+Left/Right to cycle themes"); + + // Show indicator if custom theme is active + if (active_is_custom) { + ImGui::SameLine(); + ImGui::PushFont(material::Type().iconSmall()); + ImGui::TextColored(ImVec4(0.4f, 0.8f, 1.0f, 1.0f), ICON_CUSTOM_THEME); + ImGui::PopFont(); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Custom theme active"); + } + } + + ImGui::SameLine(); + ImGui::PushFont(material::Type().iconSmall()); + if (material::StyledButton(ICON_REFRESH_THEMES, ImVec2(0, 0))) { + skinMgr.refresh(); + Notifications::instance().info("Theme list refreshed"); + } + ImGui::PopFont(); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Scan for new themes.\nPlace theme folders in:\n%s", + schema::SkinManager::getUserSkinsDirectory().c_str()); + } + + ImGui::Spacing(); + + // Language selection + ImGui::Text("Language:"); + ImGui::SameLine(lbl.position); + auto& i18n = util::I18n::instance(); + const auto& languages = i18n.getAvailableLanguages(); + + // Build language display names array + std::vector lang_names; + lang_names.reserve(languages.size()); + for (const auto& lang : languages) { + lang_names.push_back(lang.second.c_str()); // Display name + } + + ImGui::SetNextItemWidth(cmb.width); + if (ImGui::Combo("##Language", &s_language_index, lang_names.data(), static_cast(lang_names.size()))) { + // Get locale code from index + auto it = languages.begin(); + std::advance(it, s_language_index); + i18n.loadLanguage(it->first); + } + ImGui::TextDisabled(" Note: Some text requires restart to update"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Acrylic Effects settings + ImGui::Text("Visual Effects"); + ImGui::Spacing(); + + ImGui::Text("Acrylic Level:"); + ImGui::SameLine(lbl.position); + ImGui::SetNextItemWidth(cmb.width); + { + char blur_fmt[16]; + if (s_blur_amount < 0.01f) + snprintf(blur_fmt, sizeof(blur_fmt), "Off"); + else + snprintf(blur_fmt, sizeof(blur_fmt), "%.0f%%%%", s_blur_amount * 25.0f); + if (ImGui::SliderFloat("##AcrylicBlur", &s_blur_amount, 0.0f, 4.0f, blur_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + if (s_blur_amount > 0.0f && s_blur_amount < 0.15f) s_blur_amount = 0.0f; + s_acrylic_enabled = (s_blur_amount > 0.001f); + effects::ImGuiAcrylic::ApplyBlurAmount(s_blur_amount); + } + } + ImGui::TextDisabled(" Blur amount (0%% = off, 100%% = maximum)"); + + ImGui::Spacing(); + ImGui::Text("Noise Opacity:"); + ImGui::SameLine(lbl.position); + ImGui::SetNextItemWidth(cmb.width); + { + char noise_fmt[16]; + if (s_noise_opacity < 0.01f) + snprintf(noise_fmt, sizeof(noise_fmt), "Off"); + else + snprintf(noise_fmt, sizeof(noise_fmt), "%.0f%%%%", s_noise_opacity * 100.0f); + if (ImGui::SliderFloat("##NoiseOpacity", &s_noise_opacity, 0.0f, 1.0f, noise_fmt, + ImGuiSliderFlags_AlwaysClamp)) { + effects::ImGuiAcrylic::SetNoiseOpacity(s_noise_opacity); + } + } + ImGui::TextDisabled(" Grain texture intensity (0%% = off, 100%% = maximum)"); + + ImGui::Spacing(); + + // Accessibility: Reduced transparency + if (ImGui::Checkbox("Reduce transparency", &s_reduced_transparency)) { + effects::ImGuiAcrylic::SetReducedTransparency(s_reduced_transparency); + } + ImGui::TextDisabled(" Use solid colors instead of blur effects (accessibility)"); + + ImGui::Spacing(); + + if (ImGui::Checkbox("Simple background", &s_gradient_background)) { + schema::SkinManager::instance().setGradientMode(s_gradient_background); + } + ImGui::TextDisabled(" Replace textured backgrounds with smooth gradients"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Privacy settings + ImGui::Text("Privacy"); + ImGui::Spacing(); + + ImGui::Checkbox("Save shielded transaction history locally", &s_save_ztxs); + ImGui::TextDisabled(" Stores z-addr transactions in a local file for viewing"); + + ImGui::Spacing(); + + ImGui::Checkbox("Auto-shield transparent funds", &s_auto_shield); + ImGui::TextDisabled(" Automatically move transparent funds to shielded addresses"); + + ImGui::Spacing(); + + ImGui::Checkbox("Use Tor for network connections", &s_use_tor); + ImGui::TextDisabled(" Route all connections through Tor for enhanced privacy"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Other settings + ImGui::Text("Other"); + ImGui::Spacing(); + + ImGui::Checkbox("Allow custom transaction fees", &s_allow_custom_fees); + ImGui::Checkbox("Fetch price data from CoinGecko", &s_fetch_prices); + + ImGui::EndTabItem(); + } + + // Connection settings tab + if (ImGui::BeginTabItem("Connection")) { + ImGui::Spacing(); + + ImGui::Text("RPC Connection"); + ImGui::TextDisabled("Configure connection to dragonxd daemon"); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Host:"); + ImGui::SameLine(connLbl.position); + ImGui::SetNextItemWidth(cmb.width); + ImGui::InputText("##RPCHost", s_rpc_host, sizeof(s_rpc_host)); + + ImGui::Text("Port:"); + ImGui::SameLine(connLbl.position); + ImGui::SetNextItemWidth(portInput.width); + ImGui::InputText("##RPCPort", s_rpc_port, sizeof(s_rpc_port)); + + ImGui::Spacing(); + + ImGui::Text("Username:"); + ImGui::SameLine(connLbl.position); + ImGui::SetNextItemWidth(cmb.width); + ImGui::InputText("##RPCUser", s_rpc_user, sizeof(s_rpc_user)); + + ImGui::Text("Password:"); + ImGui::SameLine(connLbl.position); + ImGui::SetNextItemWidth(cmb.width); + ImGui::InputText("##RPCPassword", s_rpc_password, sizeof(s_rpc_password), + ImGuiInputTextFlags_Password); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::TextDisabled("Note: Connection settings are usually auto-detected from DRAGONX.conf"); + + ImGui::Spacing(); + + if (material::StyledButton("Test Connection", ImVec2(0,0), S.resolveFont("button"))) { + if (app->rpc()) { + app->rpc()->getInfo([](const nlohmann::json& result, const std::string& error) { + if (error.empty()) { + std::string version = result.value("version", "unknown"); + std::string msg = "Connection successful!\ndragonxd version: " + version; + Notifications::instance().success(msg); + } else { + Notifications::instance().error("Connection failed: " + error); + } + }); + } else { + Notifications::instance().error("RPC client not initialized"); + } + } + + ImGui::EndTabItem(); + } + + // Wallet tab + if (ImGui::BeginTabItem("Wallet")) { + ImGui::Spacing(); + + ImGui::Text("Wallet Maintenance"); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + if (material::StyledButton("Rescan Blockchain", ImVec2(walletBtn.width, 0), S.resolveFont(walletBtn.font))) { + if (app->rpc()) { + // Start rescan from block 0 + app->rpc()->rescanBlockchain(0, [](const nlohmann::json& result, const std::string& error) { + if (error.empty()) { + int start = result.value("start_height", 0); + int end = result.value("stop_height", 0); + std::string msg = "Rescan started from block " + std::to_string(start) + + " to " + std::to_string(end); + Notifications::instance().success(msg); + } else { + Notifications::instance().error("Rescan failed: " + error); + } + }); + } else { + Notifications::instance().error("RPC client not initialized"); + } + } + ImGui::TextDisabled(" Rescan blockchain for missing transactions"); + + ImGui::Spacing(); + + if (material::StyledButton("Clear Saved Z-Transaction History", ImVec2(walletBtn.width, 0), S.resolveFont(walletBtn.font))) { + // Clear z-transaction history file + std::string ztx_file = util::Platform::getDragonXDataDir() + "ztx_history.json"; + if (util::Platform::deleteFile(ztx_file)) { + Notifications::instance().success("Z-transaction history cleared"); + } else { + Notifications::instance().info("No history file found"); + } + } + ImGui::TextDisabled(" Delete locally stored shielded transaction data"); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Wallet Info"); + ImGui::Spacing(); + + // Get actual wallet size + std::string wallet_path = util::Platform::getDragonXDataDir() + "wallet.dat"; + uint64_t wallet_size = util::Platform::getFileSize(wallet_path); + if (wallet_size > 0) { + std::string size_str = util::Platform::formatFileSize(wallet_size); + ImGui::Text("Wallet file size: %s", size_str.c_str()); + } else { + ImGui::TextDisabled("Wallet file not found"); + } + ImGui::Text("Wallet location: %s", wallet_path.c_str()); + + ImGui::EndTabItem(); + } + + // Explorer tab + if (ImGui::BeginTabItem("Explorer")) { + ImGui::Spacing(); + + ImGui::Text("Block Explorer URLs"); + ImGui::TextDisabled("Configure external block explorer links"); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Transaction URL:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##TxExplorer", s_tx_explorer, sizeof(s_tx_explorer)); + + ImGui::Text("Address URL:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##AddrExplorer", s_addr_explorer, sizeof(s_addr_explorer)); + + ImGui::Spacing(); + ImGui::TextDisabled("URLs should include a trailing slash. The txid/address will be appended."); + + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Save/Cancel buttons + if (material::StyledButton("Save", ImVec2(saveBtn.width, 0), S.resolveFont(saveBtn.font))) { + saveSettingsFromUI(app->settings()); + Notifications::instance().success("Settings saved"); + *p_open = false; + } + ImGui::SameLine(); + if (material::StyledButton("Cancel", ImVec2(cancelBtn.width, 0), S.resolveFont(cancelBtn.font))) { + // Reload settings to revert changes + loadSettingsToUI(app->settings()); + // Revert skin to what was active when settings opened + if (!s_saved_skin_id.empty()) { + schema::SkinManager::instance().setActiveSkin(s_saved_skin_id); + if (app->settings()) { + app->settings()->setSkinId(s_saved_skin_id); + app->settings()->save(); + } + } + *p_open = false; + } + + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/settings_window.h b/src/ui/windows/settings_window.h new file mode 100644 index 0000000..dbc3c2c --- /dev/null +++ b/src/ui/windows/settings_window.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Settings window + * Modal dialog for application settings + */ +void RenderSettingsWindow(App* app, bool* p_open); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/shield_dialog.cpp b/src/ui/windows/shield_dialog.cpp new file mode 100644 index 0000000..11a3141 --- /dev/null +++ b/src/ui/windows/shield_dialog.cpp @@ -0,0 +1,312 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "shield_dialog.h" +#include "../../app.h" +#include "../../config/version.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../../util/i18n.h" +#include "../notifications.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +#include +#include + +namespace dragonx { +namespace ui { + +// Static state +static bool s_open = false; +static ShieldDialog::Mode s_mode = ShieldDialog::Mode::ShieldCoinbase; +static char s_from_address[512] = "*"; +static char s_to_address[512] = ""; +static double s_fee = DRAGONX_DEFAULT_FEE; +static int s_utxo_limit = 50; // overridden by schema at runtime +static bool s_operation_pending = false; +static std::string s_operation_id; +static std::string s_status_message; +static int s_selected_zaddr_idx = -1; + +void ShieldDialog::show(Mode mode) +{ + s_mode = mode; + s_open = true; + s_operation_pending = false; + s_status_message.clear(); + s_operation_id.clear(); + + if (mode == Mode::ShieldCoinbase) { + strncpy(s_from_address, "*", sizeof(s_from_address)); + } else { + s_from_address[0] = '\0'; + } + s_to_address[0] = '\0'; + s_fee = DRAGONX_DEFAULT_FEE; + s_utxo_limit = (int)schema::UI().drawElement("business", "utxo-limit").size; + s_selected_zaddr_idx = -1; +} + +void ShieldDialog::showShieldCoinbase(const std::string& fromAddress) +{ + show(Mode::ShieldCoinbase); + strncpy(s_from_address, fromAddress.c_str(), sizeof(s_from_address) - 1); +} + +void ShieldDialog::showMerge() +{ + show(Mode::MergeToAddress); +} + +void ShieldDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.shield"); + auto addrLbl = S.label("dialogs.shield", "address-label"); + auto addrFrontLbl = S.label("dialogs.shield", "address-front-label"); + auto addrBackLbl = S.label("dialogs.shield", "address-back-label"); + auto feeInput = S.input("dialogs.shield", "fee-input"); + auto utxoInput = S.input("dialogs.shield", "utxo-limit-input"); + auto shieldBtn = S.button("dialogs.shield", "shield-button"); + auto cancelBtn = S.button("dialogs.shield", "cancel-button"); + + const char* title = (s_mode == Mode::ShieldCoinbase) + ? "Shield Coinbase Rewards" + : "Merge to Address"; + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup(title); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal(title, &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + const auto& state = app->getWalletState(); + + // Description + if (s_mode == Mode::ShieldCoinbase) { + ImGui::TextWrapped( + "Shield your mining rewards by sending coinbase outputs from " + "transparent addresses to a shielded address. This improves " + "privacy by hiding your mining income." + ); + } else { + ImGui::TextWrapped( + "Merge multiple UTXOs into a single shielded address. This can " + "help reduce wallet size and improve privacy." + ); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // From address (for shield coinbase) + if (s_mode == Mode::ShieldCoinbase) { + ImGui::Text("From Address:"); + ImGui::SetNextItemWidth(-1); + ImGui::InputText("##FromAddr", s_from_address, sizeof(s_from_address)); + ImGui::TextDisabled("Use '*' to shield from all transparent addresses"); + ImGui::Spacing(); + } + + // To address (z-address dropdown) + ImGui::Text("To Address (Shielded):"); + + // Get z-addresses for dropdown + std::string to_display = s_to_address[0] ? s_to_address : "Select z-address..."; + if (to_display.length() > static_cast(addrLbl.truncate)) { + to_display = to_display.substr(0, addrFrontLbl.truncate) + "..." + to_display.substr(to_display.length() - addrBackLbl.truncate); + } + + ImGui::SetNextItemWidth(-1); + if (ImGui::BeginCombo("##ToAddr", to_display.c_str())) { + for (size_t i = 0; i < state.z_addresses.size(); i++) { + const auto& addr = state.z_addresses[i]; + std::string label = addr.address; + if (label.length() > static_cast(addrLbl.truncate)) { + label = label.substr(0, addrFrontLbl.truncate) + "..." + label.substr(label.length() - addrBackLbl.truncate); + } + + bool selected = (s_selected_zaddr_idx == static_cast(i)); + if (ImGui::Selectable(label.c_str(), selected)) { + s_selected_zaddr_idx = static_cast(i); + strncpy(s_to_address, addr.address.c_str(), sizeof(s_to_address) - 1); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + + ImGui::Spacing(); + + // Fee + ImGui::Text("Fee:"); + ImGui::SetNextItemWidth(feeInput.width); + ImGui::InputDouble("##Fee", &s_fee, 0.0001, 0.001, "%.8f"); + ImGui::SameLine(); + ImGui::TextDisabled("DRGX"); + + ImGui::Spacing(); + + // UTXO limit + ImGui::Text("UTXO Limit:"); + ImGui::SetNextItemWidth(utxoInput.width); + ImGui::InputInt("##Limit", &s_utxo_limit); + ImGui::SameLine(); + ImGui::TextDisabled("Max UTXOs per operation"); + if (s_utxo_limit < 1) s_utxo_limit = 1; + if (s_utxo_limit > 100) s_utxo_limit = 100; + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Status message + if (!s_status_message.empty()) { + if (s_operation_pending) { + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.0f, 1.0f), "%s", s_status_message.c_str()); + } else { + ImGui::TextWrapped("%s", s_status_message.c_str()); + } + ImGui::Spacing(); + } + + // Buttons + bool can_submit = !s_operation_pending && s_to_address[0] != '\0'; + + if (!can_submit) ImGui::BeginDisabled(); + + const char* btn_label = (s_mode == Mode::ShieldCoinbase) ? "Shield Funds" : "Merge Funds"; + if (material::StyledButton(btn_label, ImVec2(shieldBtn.width, 0), S.resolveFont(shieldBtn.font))) { + s_operation_pending = true; + s_status_message = "Submitting operation..."; + + if (s_mode == Mode::ShieldCoinbase) { + std::string from(s_from_address), to(s_to_address); + double fee = s_fee; + int limit = s_utxo_limit; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), from, to, fee, limit]() -> rpc::RPCWorker::MainCb { + nlohmann::json result; + std::string error; + try { + result = rpc->call("z_shieldcoinbase", {from, to, fee, limit}); + } catch (const std::exception& e) { + error = e.what(); + } + return [result, error]() { + s_operation_pending = false; + if (error.empty()) { + s_operation_id = result.value("opid", ""); + s_status_message = "Operation submitted: " + s_operation_id; + Notifications::instance().success("Shield operation started"); + } else { + s_status_message = "Error: " + error; + Notifications::instance().error("Shield failed: " + error); + } + }; + }); + } + } else { + std::vector fromAddrs; + fromAddrs.push_back("ANY_TADDR"); + std::string to(s_to_address); + double fee = s_fee; + int limit = s_utxo_limit; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), fromAddrs, to, fee, limit]() -> rpc::RPCWorker::MainCb { + nlohmann::json addrs = nlohmann::json::array(); + for (const auto& addr : fromAddrs) addrs.push_back(addr); + nlohmann::json result; + std::string error; + try { + result = rpc->call("z_mergetoaddress", {addrs, to, fee, 0, limit}); + } catch (const std::exception& e) { + error = e.what(); + } + return [result, error]() { + s_operation_pending = false; + if (error.empty()) { + s_operation_id = result.value("opid", ""); + s_status_message = "Operation submitted: " + s_operation_id; + Notifications::instance().success("Merge operation started"); + } else { + s_status_message = "Error: " + error; + Notifications::instance().error("Merge failed: " + error); + } + }; + }); + } + } + } + + if (!can_submit) ImGui::EndDisabled(); + + ImGui::SameLine(); + + if (material::StyledButton("Cancel", ImVec2(cancelBtn.width, 0), S.resolveFont(cancelBtn.font))) { + s_open = false; + } + + // Show operation status if we have an opid + if (!s_operation_id.empty()) { + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Operation ID: %s", s_operation_id.c_str()); + + if (material::StyledButton("Check Status", ImVec2(0,0), S.resolveFont(shieldBtn.font))) { + std::string opid = s_operation_id; + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), opid]() -> rpc::RPCWorker::MainCb { + nlohmann::json result; + std::string error; + try { + nlohmann::json ids = nlohmann::json::array(); + ids.push_back(opid); + result = rpc->call("z_getoperationstatus", {ids}); + } catch (const std::exception& e) { + error = e.what(); + } + return [result, error]() { + if (error.empty() && result.is_array() && !result.empty()) { + auto& op = result[0]; + std::string status = op.value("status", "unknown"); + if (status == "success") { + s_status_message = "Operation completed successfully!"; + Notifications::instance().success("Shield/merge completed!"); + } else if (status == "failed") { + std::string errMsg = op.value("error", nlohmann::json{}).value("message", "Unknown error"); + s_status_message = "Operation failed: " + errMsg; + Notifications::instance().error("Operation failed: " + errMsg); + } else if (status == "executing") { + s_status_message = "Operation in progress..."; + } else { + s_status_message = "Status: " + status; + } + } else if (!error.empty()) { + s_status_message = "Error checking status: " + error; + } + }; + }); + } + } + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/shield_dialog.h b/src/ui/windows/shield_dialog.h new file mode 100644 index 0000000..f6a4035 --- /dev/null +++ b/src/ui/windows/shield_dialog.h @@ -0,0 +1,47 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Dialog for shielding coinbase rewards and merging funds + */ +class ShieldDialog { +public: + enum class Mode { + ShieldCoinbase, // Shield mining rewards (t-addr coinbase -> z-addr) + MergeToAddress // Merge multiple inputs to single z-addr + }; + + /** + * @brief Show the shield dialog + * @param mode Operating mode + */ + static void show(Mode mode = Mode::ShieldCoinbase); + + /** + * @brief Show shield coinbase dialog for specific address + */ + static void showShieldCoinbase(const std::string& fromAddress = "*"); + + /** + * @brief Show merge to address dialog + */ + static void showMerge(); + + /** + * @brief Render the dialog (call each frame) + */ + static void render(App* app); +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/transaction_details_dialog.cpp b/src/ui/windows/transaction_details_dialog.cpp new file mode 100644 index 0000000..1194048 --- /dev/null +++ b/src/ui/windows/transaction_details_dialog.cpp @@ -0,0 +1,208 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "transaction_details_dialog.h" +#include "../../app.h" +#include "../../config/settings.h" +#include "../../util/i18n.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "imgui.h" +#include + +namespace dragonx { +namespace ui { + +// Static member initialization +bool TransactionDetailsDialog::s_open = false; +TransactionInfo TransactionDetailsDialog::s_transaction; + +void TransactionDetailsDialog::show(const TransactionInfo& tx) +{ + s_open = true; + s_transaction = tx; +} + +bool TransactionDetailsDialog::isOpen() +{ + return s_open; +} + +void TransactionDetailsDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.transaction-details"); + auto lbl = S.label("dialogs.transaction-details", "label"); + auto confLbl = S.label("dialogs.transaction-details", "confirmations-label"); + auto txidInput = S.input("dialogs.transaction-details", "txid-input"); + auto copyBtn = S.button("dialogs.transaction-details", "copy-button"); + auto addrInput = S.input("dialogs.transaction-details", "address-input"); + auto memoInput = S.input("dialogs.transaction-details", "memo-input"); + auto bottomBtn = S.button("dialogs.transaction-details", "bottom-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Transaction Details"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Transaction Details", &s_open, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + const auto& tx = s_transaction; + + // Type indicator with color + ImVec4 type_color; + std::string type_display; + if (tx.type == "receive") { + type_color = ImVec4(0.3f, 0.8f, 0.3f, 1.0f); + type_display = "RECEIVED"; + } else if (tx.type == "send") { + type_color = ImVec4(0.8f, 0.3f, 0.3f, 1.0f); + type_display = "SENT"; + } else if (tx.type == "generate" || tx.type == "mined") { + type_color = ImVec4(0.3f, 0.6f, 0.9f, 1.0f); + type_display = "MINED"; + } else if (tx.type == "immature") { + type_color = ImVec4(0.8f, 0.8f, 0.3f, 1.0f); + type_display = "IMMATURE"; + } else { + type_color = ImVec4(0.7f, 0.7f, 0.7f, 1.0f); + type_display = tx.type; + } + + ImGui::TextColored(type_color, "%s", type_display.c_str()); + ImGui::SameLine(ImGui::GetWindowWidth() - confLbl.position); + + // Confirmations badge + if (tx.confirmations == 0) { + ImGui::TextColored(ImVec4(0.8f, 0.6f, 0.0f, 1.0f), "Pending"); + } else if (tx.confirmations < 10) { + ImGui::TextColored(ImVec4(0.8f, 0.8f, 0.3f, 1.0f), "%d confirmations", tx.confirmations); + } else { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "%d confirmations", tx.confirmations); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Amount (prominent display) + ImGui::Text("Amount:"); + ImGui::SameLine(lbl.position); + if (tx.amount >= 0) { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "+%.8f DRGX", tx.amount); + } else { + ImGui::TextColored(ImVec4(0.8f, 0.3f, 0.3f, 1.0f), "%.8f DRGX", tx.amount); + } + + // USD equivalent if price available + double price_usd = app->state().market.price_usd; + if (price_usd > 0) { + ImGui::SameLine(); + ImGui::TextDisabled("(~$%.2f USD)", std::abs(tx.amount) * price_usd); + } + + ImGui::Spacing(); + + // Date/Time + ImGui::Text("Date:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%s", tx.getTimeString().c_str()); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Transaction ID + ImGui::Text("Transaction ID:"); + char txid_buf[128]; + strncpy(txid_buf, tx.txid.c_str(), sizeof(txid_buf) - 1); + txid_buf[sizeof(txid_buf) - 1] = '\0'; + ImGui::SetNextItemWidth(txidInput.width); + ImGui::InputText("##TxID", txid_buf, sizeof(txid_buf), ImGuiInputTextFlags_ReadOnly); + ImGui::SameLine(); + if (material::StyledButton("Copy##TxID", ImVec2(copyBtn.width, 0), S.resolveFont(copyBtn.font))) { + ImGui::SetClipboardText(tx.txid.c_str()); + } + + ImGui::Spacing(); + + // Address + if (!tx.address.empty()) { + ImGui::Text(tx.type == "send" ? "To Address:" : "From Address:"); + + // Use multiline for z-addresses + if (tx.address.length() > 50) { + char addr_buf[512]; + strncpy(addr_buf, tx.address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##Address", addr_buf, sizeof(addr_buf), + ImVec2(addrInput.width, addrInput.height > 0 ? addrInput.height : 50), ImGuiInputTextFlags_ReadOnly); + } else { + char addr_buf[128]; + strncpy(addr_buf, tx.address.c_str(), sizeof(addr_buf) - 1); + addr_buf[sizeof(addr_buf) - 1] = '\0'; + ImGui::SetNextItemWidth(addrInput.width); + ImGui::InputText("##Address", addr_buf, sizeof(addr_buf), ImGuiInputTextFlags_ReadOnly); + } + ImGui::SameLine(); + if (material::StyledButton("Copy##Addr", ImVec2(copyBtn.width, 0), S.resolveFont(copyBtn.font))) { + ImGui::SetClipboardText(tx.address.c_str()); + } + } + + ImGui::Spacing(); + + // Memo (if present) + if (!tx.memo.empty()) { + ImGui::Separator(); + ImGui::Spacing(); + + ImGui::Text("Memo:"); + char memo_buf[512]; + strncpy(memo_buf, tx.memo.c_str(), sizeof(memo_buf) - 1); + memo_buf[sizeof(memo_buf) - 1] = '\0'; + ImGui::InputTextMultiline("##Memo", memo_buf, sizeof(memo_buf), + ImVec2(-1, memoInput.height > 0 ? memoInput.height : 60), ImGuiInputTextFlags_ReadOnly); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Buttons + float button_width = bottomBtn.width; + float total_width = button_width * 2 + ImGui::GetStyle().ItemSpacing.x; + float start_x = (ImGui::GetWindowWidth() - total_width) / 2.0f; + ImGui::SetCursorPosX(start_x); + + if (material::StyledButton("View on Explorer", ImVec2(button_width, 0), S.resolveFont(bottomBtn.font))) { + std::string url = app->settings()->getTxExplorerUrl() + tx.txid; + // Platform-specific URL opening + #ifdef _WIN32 + ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + #elif __APPLE__ + std::string cmd = "open \"" + url + "\""; + system(cmd.c_str()); + #else + std::string cmd = "xdg-open \"" + url + "\" &"; + system(cmd.c_str()); + #endif + } + + ImGui::SameLine(); + + if (material::StyledButton("Close", ImVec2(button_width, 0), S.resolveFont(bottomBtn.font))) { + s_open = false; + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/transaction_details_dialog.h b/src/ui/windows/transaction_details_dialog.h new file mode 100644 index 0000000..a8e25bc --- /dev/null +++ b/src/ui/windows/transaction_details_dialog.h @@ -0,0 +1,44 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include "../../data/wallet_state.h" + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog showing full transaction details + */ +class TransactionDetailsDialog { +public: + /** + * @brief Show the dialog for a transaction + * @param tx The transaction to display + */ + static void show(const TransactionInfo& tx); + + /** + * @brief Render the dialog (call every frame) + * @param app Pointer to app instance + */ + static void render(App* app); + + /** + * @brief Check if dialog is currently open + */ + static bool isOpen(); + +private: + static bool s_open; + static TransactionInfo s_transaction; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/transactions_tab.cpp b/src/ui/windows/transactions_tab.cpp new file mode 100644 index 0000000..8449697 --- /dev/null +++ b/src/ui/windows/transactions_tab.cpp @@ -0,0 +1,858 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "transactions_tab.h" +#include "transaction_details_dialog.h" +#include "export_transactions_dialog.h" +#include "../../app.h" +#include "../../config/settings.h" +#include "../../config/version.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "../layout.h" +#include "../schema/ui_schema.h" +#include "../material/type.h" +#include "../material/draw_helpers.h" +#include "../material/colors.h" +#include "../../embedded/IconsMaterialDesign.h" +#include "imgui.h" +#include +#include +#include +#include +#include + +namespace dragonx { +namespace ui { + +using namespace material; + +// Helper to truncate strings +static std::string truncateString(const std::string& str, int maxLen = 16) { + if (str.length() <= static_cast(maxLen)) return str; + int half = (maxLen - 3) / 2; + return str.substr(0, half) + "..." + str.substr(str.length() - half); +} + +// Case-insensitive string search +static bool containsIgnoreCase(const std::string& str, const std::string& search) { + if (search.empty()) return true; + std::string str_lower = str; + std::string search_lower = search; + std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(), ::tolower); + std::transform(search_lower.begin(), search_lower.end(), search_lower.begin(), ::tolower); + return str_lower.find(search_lower) != std::string::npos; +} + +// A display-ready transaction that may be a merged autoshield pair. +// For non-merged entries, send_idx or recv_idx is -1. +struct DisplayTx { + std::string txid; + std::string display_type; // "send", "receive", "mined", "immature", "shield" + double amount = 0.0; + int64_t timestamp = 0; + int confirmations = 0; + std::string address; // primary display address + std::string from_address; + std::string memo; + int orig_idx = -1; // index into state.transactions (first/primary) + int send_idx = -1; // index of send leg (shield only) + int recv_idx = -1; // index of recv leg (shield only) + bool is_shield = false; + + bool isConfirmed() const { return confirmations >= 1; } + std::string getTimeString() const; +}; + +std::string DisplayTx::getTimeString() const { + if (timestamp <= 0) return "Pending"; + std::time_t t = static_cast(timestamp); + char buf[64]; + std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", std::localtime(&t)); + return buf; +} + +// Relative time string +static std::string timeAgo(int64_t timestamp) { + if (timestamp <= 0) return ""; + int64_t now = (int64_t)std::time(nullptr); + int64_t diff = now - timestamp; + if (diff < 0) diff = 0; + if (diff < 60) return std::to_string(diff) + "s ago"; + if (diff < 3600) return std::to_string(diff / 60) + "m ago"; + if (diff < 86400) return std::to_string(diff / 3600) + "h ago"; + return std::to_string(diff / 86400) + "d ago"; +} + +// Draw a small transaction-type icon +static void DrawTxIcon(ImDrawList* dl, const std::string& type, + float cx, float cy, float /*s*/, ImU32 col) +{ + using namespace material; + ImFont* iconFont = Type().iconSmall(); + const char* icon; + if (type == "send") { + icon = ICON_MD_CALL_MADE; + } else if (type == "receive") { + icon = ICON_MD_CALL_RECEIVED; + } else if (type == "shield") { + icon = ICON_MD_SHIELD; + } else { + icon = ICON_MD_CONSTRUCTION; + } + ImVec2 sz = iconFont->CalcTextSizeA(iconFont->LegacySize, 1000.0f, 0.0f, icon); + dl->AddText(iconFont, iconFont->LegacySize, + ImVec2(cx - sz.x * 0.5f, cy - sz.y * 0.5f), col, icon); +} + +void RenderTransactionsTab(App* app) +{ + auto& S = schema::UISchema::instance(); + const auto searchInput = S.input("tabs.transactions", "search-input"); + const auto filterCombo = S.combo("tabs.transactions", "filter-combo"); + const auto filterGapEl = S.drawElement("tabs.transactions", "filter-gap"); + const auto txTable = S.table("tabs.transactions", "transaction-table"); + const auto addrLabel = S.label("tabs.transactions", "address-label"); + const auto& state = app->state(); + + // Responsive scale factors (recomputed every frame) + ImVec2 contentAvail = ImGui::GetContentRegionAvail(); + const float hs = Layout::hScale(contentAvail.x); + const float vs = Layout::vScale(contentAvail.y); + const float glassRound = Layout::glassRounding(); + const float innerPad = Layout::cardInnerPadding(); + const float cGap = Layout::cardGap(); + + // Non-scrolling container — content resizes to fit available height + ImVec2 txAvail = ImGui::GetContentRegionAvail(); + ImGui::BeginChild("##TxScroll", txAvail, false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + + ImDrawList* dl = ImGui::GetWindowDrawList(); + GlassPanelSpec glassSpec; + glassSpec.rounding = glassRound; + ImFont* ovFont = Type().overline(); + ImFont* capFont = Type().caption(); + ImFont* body2 = Type().body2(); + char buf[128]; + + ImU32 greenCol = Success(); + ImU32 redCol = Error(); + ImU32 goldCol = Warning(); + + // Expanded row index for inline detail + static int s_expanded_row = -1; + + // Pagination state + static int s_current_page = 0; + static int s_prev_filter_hash = 0; // detect filter changes to reset page + + // ================================================================ + // Summary Cards — Received | Sent | Mined + // ================================================================ + { + int recvCount = 0, sendCount = 0, minedCount = 0; + double recvTotal = 0.0, sendTotal = 0.0, minedTotal = 0.0; + + for (const auto& tx : state.transactions) { + if (tx.type == "receive") { + recvCount++; + recvTotal += std::abs(tx.amount); + } else if (tx.type == "send") { + sendCount++; + sendTotal += std::abs(tx.amount); + } else if (tx.type == "generate" || tx.type == "immature" || tx.type == "mined") { + minedCount++; + minedTotal += std::abs(tx.amount); + } + } + + float availWidth = ImGui::GetContentRegionAvail().x; + float cardGap = cGap; + float cardW = (availWidth - 2 * cardGap) / 3.0f; + float cardH = Layout::cardHeight(70.0f, vs); + float iconSz = std::max(4.0f, schema::UI().drawElement("tabs.transactions", "summary-icon-size").size * hs); + ImVec2 origin = ImGui::GetCursorScreenPos(); + + // Clickable type filter (clicking a card sets the type filter) + static int type_filter = 0; + + // --- Received card --- + { + ImVec2 cMin = origin; + ImVec2 cMax(cMin.x + cardW, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, glassSpec); + + float cx = cMin.x + innerPad; + float cy = cMin.y + Layout::spacingMd(); + + // Icon + DrawTxIcon(dl, "receive", cx + iconSz, cy + iconSz * 1.33f, iconSz, greenCol); + + float labelX = cx + iconSz * 3.0f; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(labelX, cy), OnSurfaceMedium(), "RECEIVED"); + cy += ovFont->LegacySize + Layout::spacingSm(); + + snprintf(buf, sizeof(buf), "%d txs", recvCount); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceDisabled(), buf); + cy += capFont->LegacySize + Layout::spacingXs(); + + snprintf(buf, sizeof(buf), "+%.4f %s", recvTotal, DRAGONX_TICKER); + dl->AddText(body2, body2->LegacySize, ImVec2(cx, cy), greenCol, buf); + + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, 40), glassSpec.rounding, 0, 1.5f); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) type_filter = (type_filter == 2) ? 0 : 2; + } + } + + // --- Sent card --- + { + float xOff = cardW + cardGap; + ImVec2 cMin(origin.x + xOff, origin.y); + ImVec2 cMax(cMin.x + cardW, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, glassSpec); + + float cx = cMin.x + innerPad; + float cy = cMin.y + Layout::spacingMd(); + + DrawTxIcon(dl, "send", cx + iconSz, cy + iconSz * 1.33f, iconSz, redCol); + + float labelX = cx + iconSz * 3.0f; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(labelX, cy), OnSurfaceMedium(), "SENT"); + cy += ovFont->LegacySize + Layout::spacingSm(); + + snprintf(buf, sizeof(buf), "%d txs", sendCount); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceDisabled(), buf); + cy += capFont->LegacySize + Layout::spacingXs(); + + snprintf(buf, sizeof(buf), "-%.4f %s", sendTotal, DRAGONX_TICKER); + dl->AddText(body2, body2->LegacySize, ImVec2(cx, cy), redCol, buf); + + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, 40), glassSpec.rounding, 0, 1.5f); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) type_filter = (type_filter == 1) ? 0 : 1; + } + } + + // --- Mined card --- + { + float xOff = 2 * (cardW + cardGap); + ImVec2 cMin(origin.x + xOff, origin.y); + ImVec2 cMax(cMin.x + cardW, cMin.y + cardH); + DrawGlassPanel(dl, cMin, cMax, glassSpec); + + float cx = cMin.x + innerPad; + float cy = cMin.y + Layout::spacingMd(); + + DrawTxIcon(dl, "mined", cx + iconSz, cy + iconSz * 1.33f, iconSz, goldCol); + + float labelX = cx + iconSz * 3.0f; + dl->AddText(ovFont, ovFont->LegacySize, ImVec2(labelX, cy), OnSurfaceMedium(), "MINED"); + cy += ovFont->LegacySize + Layout::spacingSm(); + + snprintf(buf, sizeof(buf), "%d txs", minedCount); + dl->AddText(capFont, capFont->LegacySize, ImVec2(cx, cy), OnSurfaceDisabled(), buf); + cy += capFont->LegacySize + Layout::spacingXs(); + + snprintf(buf, sizeof(buf), "+%.4f %s", minedTotal, DRAGONX_TICKER); + dl->AddText(body2, body2->LegacySize, ImVec2(cx, cy), goldCol, buf); + + if (material::IsRectHovered(cMin, cMax)) { + dl->AddRect(cMin, cMax, IM_COL32(255, 255, 255, 40), glassSpec.rounding, 0, 1.5f); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsMouseClicked(0)) type_filter = (type_filter == 3) ? 0 : 3; + } + } + + // Selected card accent + if (type_filter > 0) { + int idx_map[] = {-1, 1, 0, 2}; + int idx = idx_map[type_filter]; + float xOff = idx * (cardW + cardGap); + ImVec2 acMin(origin.x + xOff, origin.y + cardH - 3); + ImVec2 acMax(origin.x + xOff + cardW, origin.y + cardH); + ImU32 acCol = (type_filter == 1) ? redCol : (type_filter == 2) ? greenCol : goldCol; + dl->AddRectFilled(acMin, acMax, acCol, 2.0f); + } + + ImGui::Dummy(ImVec2(availWidth, cardH)); + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + + // ================================================================ + // Search & Filter bar + // ================================================================ + static char search_filter[128] = ""; + float searchMaxW = (searchInput.maxWidth >= 0) ? searchInput.maxWidth : 300.0f; + float searchRatio = (searchInput.widthRatio >= 0) ? searchInput.widthRatio : 0.30f; + float searchWidth = std::min(searchMaxW * hs, availWidth * searchRatio); + + ImGui::SetNextItemWidth(searchWidth); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, Layout::spacingSm()); + ImGui::InputTextWithHint("##TxSearch", "Search...", search_filter, sizeof(search_filter)); + ImGui::PopStyleVar(); + + float filterGap = std::max(8.0f, ((filterGapEl.size > 0) ? filterGapEl.size : 20.0f) * hs); + ImGui::SameLine(0, filterGap); + float comboW = std::max(80.0f, ((filterCombo.width > 0) ? filterCombo.width : 120.0f) * hs); + ImGui::SetNextItemWidth(comboW); + const char* types[] = { "All", "Sent", "Received", "Mined" }; + ImGui::Combo("##TxType", &type_filter, types, IM_ARRAYSIZE(types)); + + ImGui::SameLine(0, filterGap); + if (TactileButton("Refresh", ImVec2(0, 0), S.resolveFont("button"))) { + app->refreshNow(); + } + + ImGui::SameLine(0, filterGap); + if (TactileButton("Export CSV", ImVec2(0, 0), S.resolveFont("button"))) { + ExportTransactionsDialog::show(); + } + + ImGui::Dummy(ImVec2(0, Layout::spacingSm() + Layout::spacingXs())); + + // ================================================================ + // Transaction list — DrawList-based rows in scrollable child + // ================================================================ + + int filtered_count = 0; + std::string search_str(search_filter); + + // Build display list, merging autoshield send+receive pairs. + // Two entries sharing the same txid where one is "send" and + // one is "receive" to a z-address are combined into a single + // "shield" entry. We first index by txid, then build the list. + std::vector display_txns; + { + // Map txid -> indices in state.transactions + std::unordered_map> txid_map; + for (size_t i = 0; i < state.transactions.size(); i++) { + txid_map[state.transactions[i].txid].push_back(i); + } + + std::vector consumed(state.transactions.size(), false); + + for (size_t i = 0; i < state.transactions.size(); i++) { + if (consumed[i]) continue; + const auto& tx = state.transactions[i]; + + // Try to find an autoshield pair (same txid, send+receive to z-addr) + bool merged = false; + const auto& siblings = txid_map[tx.txid]; + if (siblings.size() >= 2) { + int send_i = -1, recv_i = -1; + for (size_t si : siblings) { + if (consumed[si]) continue; + const auto& stx = state.transactions[si]; + if (stx.type == "send" && send_i < 0) send_i = (int)si; + else if (stx.type == "receive" && recv_i < 0) recv_i = (int)si; + } + if (send_i >= 0 && recv_i >= 0) { + const auto& stx = state.transactions[send_i]; + const auto& rtx = state.transactions[recv_i]; + // Confirm receive goes to a z-address (shielded) + bool recv_is_shielded = !rtx.address.empty() && rtx.address[0] == 'z'; + if (recv_is_shielded) { + DisplayTx dtx; + dtx.txid = tx.txid; + dtx.display_type = "shield"; + dtx.is_shield = true; + dtx.amount = rtx.amount; // positive receive amount + dtx.timestamp = std::max(stx.timestamp, rtx.timestamp); + dtx.confirmations = std::min(stx.confirmations, rtx.confirmations); + dtx.address = rtx.address; // shielded destination + dtx.from_address = stx.address.empty() ? stx.from_address : stx.address; + dtx.memo = rtx.memo.empty() ? stx.memo : rtx.memo; + dtx.orig_idx = send_i; + dtx.send_idx = send_i; + dtx.recv_idx = recv_i; + consumed[send_i] = true; + consumed[recv_i] = true; + display_txns.push_back(std::move(dtx)); + merged = true; + } + } + } + + if (!merged) { + consumed[i] = true; + DisplayTx dtx; + dtx.txid = tx.txid; + dtx.display_type = tx.type; + dtx.amount = tx.amount; + dtx.timestamp = tx.timestamp; + dtx.confirmations = tx.confirmations; + dtx.address = tx.address; + dtx.from_address = tx.from_address; + dtx.memo = tx.memo; + dtx.orig_idx = (int)i; + display_txns.push_back(std::move(dtx)); + } + } + + // Sort by timestamp descending (same as raw list) + std::sort(display_txns.begin(), display_txns.end(), + [](const DisplayTx& a, const DisplayTx& b) { + return a.timestamp > b.timestamp; + }); + } + + // Apply type + search filters + std::vector filtered_indices; + for (size_t i = 0; i < display_txns.size(); i++) { + const auto& dtx = display_txns[i]; + if (type_filter != 0) { + if (type_filter == 1 && dtx.display_type != "send") continue; + if (type_filter == 2 && dtx.display_type != "receive" && dtx.display_type != "shield") continue; + if (type_filter == 3 && dtx.display_type != "generate" && dtx.display_type != "immature" && dtx.display_type != "mined") continue; + } + if (!search_str.empty()) { + if (!containsIgnoreCase(dtx.address, search_str) && + !containsIgnoreCase(dtx.txid, search_str) && + !containsIgnoreCase(dtx.memo, search_str) && + !(dtx.is_shield && containsIgnoreCase(std::string("shielded"), search_str))) { + continue; + } + } + filtered_indices.push_back(i); + } + filtered_count = static_cast(filtered_indices.size()); + + // Pagination — slice filtered results into pages + int perPage = std::max(10, (int)schema::UI().drawElement("tabs.transactions", "rows-per-page").sizeOr(50.0f)); + int totalPages = std::max(1, (filtered_count + perPage - 1) / perPage); + + // Reset page when filters change + int filterHash = type_filter * 1000003 + filtered_count * 31 + static_cast(search_str.size()); + if (filterHash != s_prev_filter_hash) { + s_current_page = 0; + s_prev_filter_hash = filterHash; + } + if (s_current_page >= totalPages) s_current_page = totalPages - 1; + if (s_current_page < 0) s_current_page = 0; + + int pageStart = s_current_page * perPage; + int pageEnd = std::min(pageStart + perPage, filtered_count); + + // ---- Heading line: "TRANSACTIONS" left, pagination right ---- + { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TRANSACTIONS"); + + if (totalPages > 1) { + float paginationH = ImGui::GetFrameHeight(); + float btnW = paginationH; + float gap = Layout::spacingSm(); + float pageNumW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, " 999 / 999 ").x + Layout::spacingLg(); + float totalPagW = btnW * 4 + pageNumW + gap * 4; + + // Right-align: position cursor so the group ends at the right edge + ImGui::SameLine(); + float startX = ImGui::GetContentRegionMax().x - totalPagW; + ImGui::SetCursorPosX(startX); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, Layout::spacingSm()); + ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 15))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 30))); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 45))); + + // First page + ImGui::BeginDisabled(s_current_page == 0); + ImGui::PushFont(Type().iconSmall()); + if (ImGui::Button(ICON_MD_FIRST_PAGE "##txFirst", ImVec2(btnW, btnW))) { + s_current_page = 0; + s_expanded_row = -1; + } + ImGui::PopFont(); + ImGui::EndDisabled(); + + ImGui::SameLine(0, gap); + + // Previous page + ImGui::BeginDisabled(s_current_page == 0); + ImGui::PushFont(Type().iconSmall()); + if (ImGui::Button(ICON_MD_CHEVRON_LEFT "##txPrev", ImVec2(btnW, btnW))) { + s_current_page--; + s_expanded_row = -1; + } + ImGui::PopFont(); + ImGui::EndDisabled(); + + ImGui::SameLine(0, gap); + + // Page indicator — render centered text over a fixed-width dummy + { + snprintf(buf, sizeof(buf), "%d / %d", s_current_page + 1, totalPages); + ImVec2 pageSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + ImVec2 regionPos = ImGui::GetCursorScreenPos(); + // Reserve the fixed width without advancing to a new line + ImGui::InvisibleButton("##pageNum", ImVec2(pageNumW, paginationH)); + // Draw the text centered within that reserved area + ImVec2 textPos( + regionPos.x + (pageNumW - pageSz.x) * 0.5f, + regionPos.y + (paginationH - pageSz.y) * 0.5f + ); + ImGui::GetWindowDrawList()->AddText(capFont, capFont->LegacySize, textPos, OnSurfaceMedium(), buf); + } + + ImGui::SameLine(0, gap); + + // Next page + ImGui::BeginDisabled(s_current_page >= totalPages - 1); + ImGui::PushFont(Type().iconSmall()); + if (ImGui::Button(ICON_MD_CHEVRON_RIGHT "##txNext", ImVec2(btnW, btnW))) { + s_current_page++; + s_expanded_row = -1; + } + ImGui::PopFont(); + ImGui::EndDisabled(); + + ImGui::SameLine(0, gap); + + // Last page + ImGui::BeginDisabled(s_current_page >= totalPages - 1); + ImGui::PushFont(Type().iconSmall()); + if (ImGui::Button(ICON_MD_LAST_PAGE "##txLast", ImVec2(btnW, btnW))) { + s_current_page = totalPages - 1; + s_expanded_row = -1; + } + ImGui::PopFont(); + ImGui::EndDisabled(); + + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(2); + } + } + ImGui::Dummy(ImVec2(0, Layout::spacingXs())); + + // Glass panel wrapping the list area — scale reserve with vScale + float scaledReserve = (txTable.bottomReserve > 0) ? txTable.bottomReserve : std::max(schema::UI().drawElement("tabs.transactions", "bottom-reserve-min").size, schema::UI().drawElement("tabs.transactions", "bottom-reserve-base").size * vs); + float listH = ImGui::GetContentRegionAvail().y - scaledReserve; + float minListH = std::max(schema::UI().drawElement("tabs.transactions", "list-min-height").size, schema::UI().drawElement("tabs.transactions", "list-base-height").size * vs); + if (listH < minListH) listH = minListH; + + ImVec2 listPanelMin = ImGui::GetCursorScreenPos(); + ImVec2 listPanelMax(listPanelMin.x + availWidth, listPanelMin.y + listH); + DrawGlassPanel(dl, listPanelMin, listPanelMax, glassSpec); + + // Scroll state for clipping mask (captured inside child, used after EndChild) + float scrollY = 0.0f; + float scrollMaxY = 0.0f; + + // Vertex start indices for CSS-style clipping mask (alpha fade at edges) + int vtxMaskStart = dl->VtxBuffer.Size; + + ImGui::BeginChild("##TxList", ImVec2(availWidth, listH), false, + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoScrollWithMouse); + ApplySmoothScroll(); + ImDrawList* childDL = ImGui::GetWindowDrawList(); + int childVtxStart = childDL->VtxBuffer.Size; + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + { + if (!app->isConnected()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " Not connected to daemon..."); + } else if (state.transactions.empty()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " No transactions found"); + } else if (filtered_indices.empty()) { + ImGui::Dummy(ImVec2(0, 20)); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), " No matching transactions"); + } else { + float rowH = body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd(); + float innerW = ImGui::GetContentRegionAvail().x; + float rowIconSz = std::max(3.5f, schema::UI().drawElement("tabs.transactions", "row-icon-size").size * hs); + float rowPadLeft = Layout::spacingLg(); + + // Scroll state for gradient overlay fade (drawn after EndChild) + scrollY = ImGui::GetScrollY(); + scrollMaxY = ImGui::GetScrollMaxY(); + + // Viewport culling bounds + float viewTop = scrollY; + float viewBot = scrollY + ImGui::GetWindowHeight(); + + // Render only the current page slice + for (int fi = pageStart; fi < pageEnd; fi++) { + size_t i = filtered_indices[fi]; + const auto& tx = display_txns[i]; + bool is_expanded = (s_expanded_row == static_cast(i)); + + ImGui::PushID(static_cast(i)); + ImVec2 rowPos = ImGui::GetCursorScreenPos(); + ImVec2 rowEnd(rowPos.x + innerW, rowPos.y + rowH); + + // Determine type info + ImU32 iconCol; + const char* typeStr; + if (tx.display_type == "shield") { + iconCol = Primary(); typeStr = "Shielded"; + } else if (tx.display_type == "receive") { + iconCol = greenCol; typeStr = "Recv"; + } else if (tx.display_type == "send") { + iconCol = redCol; typeStr = "Sent"; + } else if (tx.display_type == "immature") { + iconCol = Warning(); typeStr = "Immature"; + } else { + iconCol = goldCol; typeStr = "Mined"; + } + + // Expanded selection accent + if (is_expanded) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 20), schema::UI().drawElement("tabs.transactions", "row-hover-rounding").size); + dl->AddRectFilled(rowPos, ImVec2(rowPos.x + schema::UI().drawElement("tabs.transactions", "row-accent-width").size, rowEnd.y), Primary(), schema::UI().drawElement("tabs.transactions", "accent-bar-rounding").size); + } + + // Hover glow + bool hovered = material::IsRectHovered(rowPos, rowEnd); + if (hovered && !is_expanded) { + dl->AddRectFilled(rowPos, rowEnd, IM_COL32(255, 255, 255, 15), schema::UI().drawElement("tabs.transactions", "row-hover-rounding").size); + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + + float cx = rowPos.x + rowPadLeft; + float cy = rowPos.y + Layout::spacingMd(); + + // Icon + DrawTxIcon(dl, tx.display_type, cx + rowIconSz, cy + body2->LegacySize * 0.5f, rowIconSz, iconCol); + + // Type label + float labelX = cx + rowIconSz * 2.0f + Layout::spacingSm(); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy), iconCol, typeStr); + + // Time (next to type) + std::string ago = timeAgo(tx.timestamp); + float typeW = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, typeStr).x; + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX + typeW + Layout::spacingLg(), cy), + OnSurfaceDisabled(), ago.c_str()); + + // Address (second line, left side) + std::string addr_display = truncateString(tx.address, (addrLabel.truncate > 0) ? addrLabel.truncate : 20); + dl->AddText(capFont, capFont->LegacySize, ImVec2(labelX, cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceMedium(), addr_display.c_str()); + + // Amount (right-aligned, first line) + ImU32 amtCol = (tx.amount >= 0) ? greenCol : redCol; + if (tx.amount >= 0) + snprintf(buf, sizeof(buf), "+%.8f", tx.amount); + else + snprintf(buf, sizeof(buf), "%.8f", tx.amount); + ImVec2 amtSz = body2->CalcTextSizeA(body2->LegacySize, FLT_MAX, 0, buf); + float amtX = rowPos.x + innerW - amtSz.x - Layout::spacingLg(); + DrawTextShadow(dl, body2, body2->LegacySize, ImVec2(amtX, cy), amtCol, buf, + 1.0f, 1.0f, IM_COL32(0, 0, 0, 120)); + + // USD equivalent (right-aligned, second line) + double priceUsd = state.market.price_usd; + if (priceUsd > 0.0) { + double usdVal = std::abs(tx.amount) * priceUsd; + if (usdVal >= 1.0) + snprintf(buf, sizeof(buf), "$%.2f", usdVal); + else if (usdVal >= 0.01) + snprintf(buf, sizeof(buf), "$%.4f", usdVal); + else + snprintf(buf, sizeof(buf), "$%.6f", usdVal); + ImVec2 usdSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, buf); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(rowPos.x + innerW - usdSz.x - Layout::spacingLg(), cy + body2->LegacySize + Layout::spacingXs()), + OnSurfaceDisabled(), buf); + } + + // Status badge (centered area, second line) + { + const char* statusStr; + ImU32 statusCol; + if (tx.confirmations == 0) { + statusStr = "Pending"; statusCol = Warning(); + } else if (tx.confirmations < 10) { + snprintf(buf, sizeof(buf), "%d conf", tx.confirmations); + statusStr = buf; statusCol = Warning(); + } else if (tx.confirmations >= 100 && (tx.display_type == "generate" || tx.display_type == "mined")) { + statusStr = "Mature"; statusCol = greenCol; + } else { + statusStr = "Confirmed"; statusCol = WithAlpha(Success(), 140); + } + // Position status badge in the middle-right area + ImVec2 sSz = capFont->CalcTextSizeA(capFont->LegacySize, FLT_MAX, 0, statusStr); + float statusX = amtX - sSz.x - Layout::spacingXxl(); + float minStatusX = cx + innerW * 0.25f; // don't overlap address + if (statusX < minStatusX) statusX = minStatusX; + // Background pill + ImU32 pillBg = (statusCol & 0x00FFFFFFu) | (static_cast(30) << 24); + ImVec2 pillMin(statusX - Layout::spacingSm(), cy + body2->LegacySize + 1); + ImVec2 pillMax(statusX + sSz.x + Layout::spacingSm(), pillMin.y + capFont->LegacySize + Layout::spacingXs()); + dl->AddRectFilled(pillMin, pillMax, pillBg, schema::UI().drawElement("tabs.transactions", "status-pill-rounding").size); + dl->AddText(capFont, capFont->LegacySize, + ImVec2(statusX, cy + body2->LegacySize + Layout::spacingXs()), statusCol, statusStr); + } + + // Click to expand/collapse + invisible button for interaction + ImGui::InvisibleButton("##txRow", ImVec2(innerW, rowH)); + if (ImGui::IsItemClicked(0)) { + s_expanded_row = is_expanded ? -1 : static_cast(i); + } + + // Tooltip + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("%s\n%s\n%s", tx.address.c_str(), + tx.txid.c_str(), tx.getTimeString().c_str()); + } + + // Context menu + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + if (effects::ImGuiAcrylic::BeginAcrylicContextItem("TxContext", 0, acrylicTheme.menu)) { + if (ImGui::MenuItem("Copy Address") && !tx.address.empty()) { + ImGui::SetClipboardText(tx.address.c_str()); + } + if (ImGui::MenuItem("Copy TxID")) { + ImGui::SetClipboardText(tx.txid.c_str()); + } + ImGui::Separator(); + if (ImGui::MenuItem("View on Explorer")) { + std::string url = app->settings()->getTxExplorerUrl() + tx.txid; + #ifdef _WIN32 + ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + #elif __APPLE__ + std::string cmd = "open \"" + url + "\""; + system(cmd.c_str()); + #else + std::string cmd = "xdg-open \"" + url + "\" &"; + system(cmd.c_str()); + #endif + } + if (ImGui::MenuItem("View Details")) { + if (tx.orig_idx >= 0 && tx.orig_idx < (int)state.transactions.size()) + TransactionDetailsDialog::show(state.transactions[tx.orig_idx]); + } + effects::ImGuiAcrylic::EndAcrylicPopup(); + } + + // ---- Inline detail expansion ---- + if (is_expanded) { + ImVec2 detailPos = ImGui::GetCursorScreenPos(); + // We'll draw the glass panel after measuring the content + float detailPad = Layout::spacingLg(); + float detailW = innerW - detailPad * 2; + + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + detailPad); + ImGui::BeginGroup(); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + detailW); + + // From address + if (!tx.from_address.empty()) { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "FROM"); + ImGui::TextWrapped("%s", tx.from_address.c_str()); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + // To address + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), + tx.display_type == "send" ? "TO" : (tx.display_type == "shield" ? "SHIELDED TO" : "ADDRESS")); + ImGui::TextWrapped("%s", tx.address.c_str()); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // TxID (full, copyable) + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "TRANSACTION ID"); + ImGui::TextWrapped("%s", tx.txid.c_str()); + if (ImGui::IsItemHovered()) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsItemClicked()) ImGui::SetClipboardText(tx.txid.c_str()); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Memo + if (!tx.memo.empty()) { + Type().textColored(TypeStyle::Overline, OnSurfaceMedium(), "MEMO"); + ImGui::TextWrapped("%s", tx.memo.c_str()); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + } + + // Confirmations + time + snprintf(buf, sizeof(buf), "%d confirmations | %s", + tx.confirmations, tx.getTimeString().c_str()); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + + // Action buttons + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 15))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(IM_COL32(255, 255, 255, 30))); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, schema::UI().drawElement("tabs.transactions", "detail-btn-rounding").size); + if (TactileSmallButton("Copy TxID##detail", S.resolveFont("button"))) { + ImGui::SetClipboardText(tx.txid.c_str()); + } + ImGui::SameLine(); + if (!tx.address.empty() && TactileSmallButton("Copy Address##detail", S.resolveFont("button"))) { + ImGui::SetClipboardText(tx.address.c_str()); + } + ImGui::SameLine(); + if (TactileSmallButton("Explorer##detail", S.resolveFont("button"))) { + std::string url = app->settings()->getTxExplorerUrl() + tx.txid; + #ifdef _WIN32 + ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + #elif __APPLE__ + std::string cmd2 = "open \"" + url + "\""; + system(cmd2.c_str()); + #else + std::string cmd2 = "xdg-open \"" + url + "\" &"; + system(cmd2.c_str()); + #endif + } + ImGui::SameLine(); + if (TactileSmallButton("Full Details##detail", S.resolveFont("button"))) { + if (tx.orig_idx >= 0 && tx.orig_idx < (int)state.transactions.size()) + TransactionDetailsDialog::show(state.transactions[tx.orig_idx]); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); + + ImGui::PopTextWrapPos(); + ImGui::EndGroup(); + + // Draw glass panel behind detail area + ImVec2 detailEnd = ImGui::GetCursorScreenPos(); + float detailH = detailEnd.y - detailPos.y + Layout::spacingMd(); + GlassPanelSpec detailGlass; + detailGlass.rounding = glassRound * 0.75f; + detailGlass.fillAlpha = 25; + DrawGlassPanel(dl, ImVec2(detailPos.x + Layout::spacingSm() + Layout::spacingXs(), detailPos.y), + ImVec2(detailPos.x + innerW - Layout::spacingSm() - Layout::spacingXs(), detailPos.y + detailH), detailGlass); + ImGui::Dummy(ImVec2(0, Layout::spacingMd())); + } + + // Subtle divider between rows + if (fi < pageEnd - 1 && !is_expanded) { + ImVec2 divStart = ImGui::GetCursorScreenPos(); + dl->AddLine(ImVec2(divStart.x + rowPadLeft + rowIconSz * 2.0f, divStart.y), + ImVec2(divStart.x + innerW - Layout::spacingLg(), divStart.y), + IM_COL32(255, 255, 255, 15)); + } + + ImGui::PopID(); + } + } + } + ImGui::Dummy(ImVec2(0, Layout::spacingSm())); + ImGui::EndChild(); + + // CSS-style clipping mask + { + float fadeZone = std::min( + (body2->LegacySize + capFont->LegacySize + Layout::spacingLg() + Layout::spacingMd()) * 1.2f, + listH * 0.18f); + ApplyScrollEdgeMask(dl, vtxMaskStart, childDL, childVtxStart, + listPanelMin.y, listPanelMax.y, fadeZone, scrollY, scrollMaxY); + } + + // Status line with page info + snprintf(buf, sizeof(buf), "Showing %d\xe2\x80\x93%d of %d transactions (total: %zu)", + filtered_count > 0 ? pageStart + 1 : 0, pageEnd, filtered_count, state.transactions.size()); + Type().textColored(TypeStyle::Caption, OnSurfaceDisabled(), buf); + } + + ImGui::EndChild(); // ##TxScroll +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/transactions_tab.h b/src/ui/windows/transactions_tab.h new file mode 100644 index 0000000..94a2b2a --- /dev/null +++ b/src/ui/windows/transactions_tab.h @@ -0,0 +1,19 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +namespace dragonx { +class App; + +namespace ui { + +/** + * @brief Render the Transactions tab + * Shows transaction history + */ +void RenderTransactionsTab(App* app); + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/validate_address_dialog.cpp b/src/ui/windows/validate_address_dialog.cpp new file mode 100644 index 0000000..03d72c1 --- /dev/null +++ b/src/ui/windows/validate_address_dialog.cpp @@ -0,0 +1,224 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "validate_address_dialog.h" +#include "../../app.h" +#include "../../rpc/rpc_client.h" +#include "../../rpc/rpc_worker.h" +#include "../schema/ui_schema.h" +#include "../material/draw_helpers.h" +#include "../theme.h" +#include "../effects/imgui_acrylic.h" +#include "imgui.h" + +namespace dragonx { +namespace ui { + +// Static member initialization +bool ValidateAddressDialog::s_open = false; +bool ValidateAddressDialog::s_validated = false; +bool ValidateAddressDialog::s_validating = false; +char ValidateAddressDialog::s_address_input[512] = ""; +bool ValidateAddressDialog::s_is_valid = false; +bool ValidateAddressDialog::s_is_mine = false; +std::string ValidateAddressDialog::s_address_type; +std::string ValidateAddressDialog::s_error_message; + +void ValidateAddressDialog::show() +{ + s_open = true; + s_validated = false; + s_validating = false; + s_address_input[0] = '\0'; + s_is_valid = false; + s_is_mine = false; + s_address_type.clear(); + s_error_message.clear(); +} + +bool ValidateAddressDialog::isOpen() +{ + return s_open; +} + +void ValidateAddressDialog::render(App* app) +{ + if (!s_open) return; + + auto& S = schema::UI(); + auto win = S.window("dialogs.validate-address"); + auto valBtn = S.button("dialogs.validate-address", "validate-button"); + auto pasteBtn = S.button("dialogs.validate-address", "paste-button"); + auto lbl = S.label("dialogs.validate-address", "label"); + auto closeBtn = S.button("dialogs.validate-address", "close-button"); + + ImGui::SetNextWindowSize(ImVec2(win.width, win.height), ImGuiCond_FirstUseEver); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowFocus(); + + const auto& acrylicTheme = GetCurrentAcrylicTheme(); + ImGui::OpenPopup("Validate Address"); + if (effects::ImGuiAcrylic::BeginAcrylicPopupModal("Validate Address", &s_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar, acrylicTheme.popup)) { + ImGui::TextWrapped("Enter a DragonX address to check if it's valid and whether it belongs to this wallet."); + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Address input + ImGui::Text("Address:"); + ImGui::SetNextItemWidth(-1); + bool enter_pressed = ImGui::InputText("##ValidateAddr", s_address_input, sizeof(s_address_input), + ImGuiInputTextFlags_EnterReturnsTrue); + + ImGui::Spacing(); + + // Validate button + bool can_validate = strlen(s_address_input) > 0 && !s_validating && app->isConnected(); + + if (!can_validate) { + ImGui::BeginDisabled(); + } + + if (material::StyledButton("Validate", ImVec2(valBtn.width, 0), S.resolveFont(valBtn.font)) || (enter_pressed && can_validate)) { + s_validating = true; + s_validated = false; + s_error_message.clear(); + + std::string address(s_address_input); + + // Determine if z-address or t-address + bool is_zaddr = !address.empty() && address[0] == 'z'; + + if (is_zaddr) { + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), address]() -> rpc::RPCWorker::MainCb { + bool valid = false, mine = false; + std::string error; + try { + auto result = rpc->call("validateaddress", {address}); + valid = result.value("isvalid", false); + mine = result.value("ismine", false); + } catch (const std::exception& e) { + error = e.what(); + } + return [valid, mine, error]() { + if (error.empty()) { + s_is_valid = valid; + s_is_mine = mine; + s_address_type = "Shielded (z-address)"; + } else { + s_error_message = error; + s_is_valid = false; + } + s_validated = true; + s_validating = false; + }; + }); + } + } else { + if (app->worker()) { + app->worker()->post([rpc = app->rpc(), address]() -> rpc::RPCWorker::MainCb { + bool valid = false, mine = false; + std::string error; + try { + auto result = rpc->call("validateaddress", {address}); + valid = result.value("isvalid", false); + mine = result.value("ismine", false); + } catch (const std::exception& e) { + error = e.what(); + } + return [valid, mine, error]() { + if (error.empty()) { + s_is_valid = valid; + s_is_mine = mine; + s_address_type = "Transparent (t-address)"; + } else { + s_error_message = error; + s_is_valid = false; + } + s_validated = true; + s_validating = false; + }; + }); + } + } + } + + if (!can_validate) { + ImGui::EndDisabled(); + } + + ImGui::SameLine(); + + if (material::StyledButton("Paste", ImVec2(pasteBtn.width, 0), S.resolveFont(pasteBtn.font))) { + const char* clipboard = ImGui::GetClipboardText(); + if (clipboard) { + strncpy(s_address_input, clipboard, sizeof(s_address_input) - 1); + s_address_input[sizeof(s_address_input) - 1] = '\0'; + s_validated = false; + } + } + + if (s_validating) { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Validating..."); + } + + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // Results + if (s_validated) { + ImGui::Text("Results:"); + ImGui::Spacing(); + + if (!s_error_message.empty()) { + ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "Error: %s", s_error_message.c_str()); + } else { + // Valid/Invalid indicator + ImGui::Text("Status:"); + ImGui::SameLine(lbl.position); + if (s_is_valid) { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "VALID"); + } else { + ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "INVALID"); + } + + if (s_is_valid) { + // Address type + ImGui::Text("Type:"); + ImGui::SameLine(lbl.position); + ImGui::Text("%s", s_address_type.c_str()); + + // Is mine? + ImGui::Text("Ownership:"); + ImGui::SameLine(lbl.position); + if (s_is_mine) { + ImGui::TextColored(ImVec4(0.3f, 0.8f, 0.3f, 1.0f), "This wallet owns this address"); + } else { + ImGui::TextDisabled("Not owned by this wallet"); + } + } + } + } else if (!app->isConnected()) { + ImGui::TextColored(ImVec4(1.0f, 0.6f, 0.0f, 1.0f), "Not connected to daemon"); + } + + ImGui::Spacing(); + + // Close button at bottom + float button_width = closeBtn.width; + ImGui::SetCursorPosX((ImGui::GetWindowWidth() - button_width) / 2.0f); + if (material::StyledButton("Close", ImVec2(button_width, 0), S.resolveFont(closeBtn.font))) { + s_open = false; + } + } + effects::ImGuiAcrylic::EndAcrylicPopup(); +} + +} // namespace ui +} // namespace dragonx diff --git a/src/ui/windows/validate_address_dialog.h b/src/ui/windows/validate_address_dialog.h new file mode 100644 index 0000000..78b0db3 --- /dev/null +++ b/src/ui/windows/validate_address_dialog.h @@ -0,0 +1,50 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { + +class App; + +namespace ui { + +/** + * @brief Dialog for validating cryptocurrency addresses + */ +class ValidateAddressDialog { +public: + /** + * @brief Show the validate address dialog + */ + static void show(); + + /** + * @brief Render the dialog (call every frame) + * @param app Pointer to app instance for RPC calls + */ + static void render(App* app); + + /** + * @brief Check if dialog is currently open + */ + static bool isOpen(); + +private: + static bool s_open; + static bool s_validated; + static bool s_validating; + static char s_address_input[512]; + + // Validation results + static bool s_is_valid; + static bool s_is_mine; + static std::string s_address_type; + static std::string s_error_message; +}; + +} // namespace ui +} // namespace dragonx diff --git a/src/util/base64.cpp b/src/util/base64.cpp new file mode 100644 index 0000000..64a27a8 --- /dev/null +++ b/src/util/base64.cpp @@ -0,0 +1,104 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "base64.h" +#include + +namespace dragonx { +namespace util { + +static const char base64_chars[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string base64_encode(const unsigned char* data, size_t len) +{ + std::string ret; + ret.reserve(((len + 2) / 3) * 4); + + int i = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (len--) { + char_array_3[i++] = *(data++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; i < 4; i++) + ret += base64_chars[char_array_4[i]]; + i = 0; + } + } + + if (i) { + for (int j = i; j < 3; j++) + char_array_3[j] = '\0'; + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + + for (int j = 0; j < i + 1; j++) + ret += base64_chars[char_array_4[j]]; + + while (i++ < 3) + ret += '='; + } + + return ret; +} + +std::vector base64_decode(const std::string& encoded) +{ + size_t in_len = encoded.size(); + int i = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::vector ret; + + while (in_len-- && (encoded[in_] != '=') && is_base64(encoded[in_])) { + char_array_4[i++] = encoded[in_]; in_++; + if (i == 4) { + for (i = 0; i < 4; i++) { + const char* p = strchr(base64_chars, char_array_4[i]); + char_array_4[i] = p ? static_cast(p - base64_chars) : 0; + } + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; i < 3; i++) + ret.push_back(char_array_3[i]); + i = 0; + } + } + + if (i) { + for (int j = 0; j < i; j++) { + const char* p = strchr(base64_chars, char_array_4[j]); + char_array_4[j] = p ? static_cast(p - base64_chars) : 0; + } + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + + for (int j = 0; j < i - 1; j++) + ret.push_back(char_array_3[j]); + } + + return ret; +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/base64.h b/src/util/base64.h new file mode 100644 index 0000000..8f8b62f --- /dev/null +++ b/src/util/base64.h @@ -0,0 +1,53 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include + +namespace dragonx { +namespace util { + +/** + * @brief Base64 encoding/decoding utilities + */ + +/** + * @brief Encode binary data to base64 string + * @param data Input data + * @param len Length of input data + * @return Base64 encoded string + */ +std::string base64_encode(const unsigned char* data, size_t len); + +/** + * @brief Encode string to base64 + * @param input Input string + * @return Base64 encoded string + */ +inline std::string base64_encode(const std::string& input) { + return base64_encode(reinterpret_cast(input.data()), input.size()); +} + +/** + * @brief Decode base64 string to binary data + * @param encoded Base64 encoded string + * @return Decoded binary data + */ +std::vector base64_decode(const std::string& encoded); + +/** + * @brief Decode base64 string to string + * @param encoded Base64 encoded string + * @return Decoded string + */ +inline std::string base64_decode_string(const std::string& encoded) { + auto decoded = base64_decode(encoded); + return std::string(decoded.begin(), decoded.end()); +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/bootstrap.cpp b/src/util/bootstrap.cpp new file mode 100644 index 0000000..e695eeb --- /dev/null +++ b/src/util/bootstrap.cpp @@ -0,0 +1,746 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "bootstrap.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "../util/logger.h" + +namespace fs = std::filesystem; + +namespace dragonx { +namespace util { + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +static bool endsWith(const std::string& s, const std::string& suffix) { + if (suffix.size() > s.size()) return false; + return s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; +} + +static size_t writeFileCallback(void* contents, size_t size, size_t nmemb, void* userp) { + size_t total = size * nmemb; + FILE* fp = static_cast(userp); + return fwrite(contents, 1, total, fp); +} + +std::string Bootstrap::formatSize(double bytes) { + const char* units[] = { "B", "KB", "MB", "GB", "TB" }; + int idx = 0; + double v = bytes; + while (v >= 1024.0 && idx < 4) { + v /= 1024.0; + idx++; + } + char buf[64]; + if (idx == 0) + snprintf(buf, sizeof(buf), "%.0f %s", v, units[idx]); + else + snprintf(buf, sizeof(buf), "%.2f %s", v, units[idx]); + return buf; +} + +// --------------------------------------------------------------------------- +// Lifecycle +// --------------------------------------------------------------------------- + +Bootstrap::~Bootstrap() { + cancel(); + if (worker_.joinable()) worker_.join(); +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +void Bootstrap::start(const std::string& dataDir, const std::string& url) { + if (worker_running_) return; // already running + + cancel_requested_ = false; + worker_running_ = true; + + // Ensure data dir exists + fs::create_directories(dataDir); + + worker_ = std::thread([this, dataDir, url]() { + std::string zipPath = dataDir + "/bootstrap_tmp.zip"; + + // Step 1: Download (with resume support) + // Check for a partial file from a previous interrupted download. + { + std::error_code ec; + if (fs::exists(zipPath, ec) && fs::file_size(zipPath, ec) > 0 && !ec) { + auto partial = fs::file_size(zipPath, ec); + DEBUG_LOGF("[Bootstrap] Found partial download: %s (%s)\n", + zipPath.c_str(), formatSize((double)partial).c_str()); + setProgress(State::Downloading, + "Resuming download (" + formatSize((double)partial) + " already on disk)..."); + } else { + setProgress(State::Downloading, "Connecting to dragonx.is..."); + } + } + if (!download(url, zipPath)) { + if (cancel_requested_) + setProgress(State::Failed, "Download cancelled"); + else + setProgress(State::Failed, "Download failed — check your internet connection"); + // Keep the partial file so the next attempt can resume. + // Only delete if the file is empty / doesn't exist. + std::error_code ec; + auto sz = fs::exists(zipPath, ec) ? fs::file_size(zipPath, ec) : 0; + if (sz == 0) fs::remove(zipPath, ec); + worker_running_ = false; + return; + } + + if (cancel_requested_) { + setProgress(State::Failed, "Download cancelled"); + // Keep partial file for resume on retry. + worker_running_ = false; + return; + } + // Step 2: Verify checksums + { + // Derive base URL from the zip URL (strip filename) + std::string baseUrl = url; + auto lastSlash = baseUrl.rfind('/'); + if (lastSlash != std::string::npos) + baseUrl = baseUrl.substr(0, lastSlash); + + if (!verifyChecksums(zipPath, baseUrl)) { + if (!cancel_requested_) { + // Checksum failure — delete the corrupt file so next attempt re-downloads + std::error_code ec; + fs::remove(zipPath, ec); + } + worker_running_ = false; + return; + } + } + + if (cancel_requested_) { + setProgress(State::Failed, "Verification cancelled"); + worker_running_ = false; + return; + } + // Step 3: Clean old chain data + setProgress(State::Extracting, "Removing old chain data..."); + cleanChainData(dataDir); + + // Step 4: Extract (skipping wallet.dat) + if (!extract(zipPath, dataDir)) { + if (cancel_requested_) + setProgress(State::Failed, "Extraction cancelled"); + else + setProgress(State::Failed, "Extraction failed — zip file may be corrupted"); + worker_running_ = false; + return; + } + + setProgress(State::Completed, "Bootstrap complete!"); + worker_running_ = false; + }); + worker_.detach(); +} + +void Bootstrap::cancel() { + cancel_requested_ = true; +} + +Bootstrap::Progress Bootstrap::getProgress() const { + std::lock_guard lk(mutex_); + return progress_; +} + +bool Bootstrap::isDone() const { + std::lock_guard lk(mutex_); + return progress_.state == State::Completed || progress_.state == State::Failed; +} + +// --------------------------------------------------------------------------- +// Progress update (thread-safe) +// --------------------------------------------------------------------------- + +void Bootstrap::setProgress(State state, const std::string& text, double downloaded, double total) { + std::lock_guard lk(mutex_); + progress_.state = state; + progress_.status_text = text; + progress_.downloaded_bytes = downloaded; + progress_.total_bytes = total; + progress_.percent = (total > 0) ? (float)(100.0 * downloaded / total) : 0.0f; + if (state == State::Failed) { + progress_.error = text; + } +} + +// --------------------------------------------------------------------------- +// HEAD request for remote file size +// --------------------------------------------------------------------------- + +long long Bootstrap::getRemoteFileSize(const std::string& url) { + CURL* curl = curl_easy_init(); + if (!curl) return -1; + + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // HEAD request + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "ObsidianDragon/1.0"); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); + + CURLcode res = curl_easy_perform(curl); + if (res != CURLE_OK) { + DEBUG_LOGF("[Bootstrap] HEAD request failed: %s\n", curl_easy_strerror(res)); + curl_easy_cleanup(curl); + return -1; + } + + curl_off_t cl = -1; + curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl); + curl_easy_cleanup(curl); + + DEBUG_LOGF("[Bootstrap] Remote file size: %lld bytes\n", (long long)cl); + return (long long)cl; +} + +// --------------------------------------------------------------------------- +// Download (libcurl) +// --------------------------------------------------------------------------- + +int Bootstrap::progressCallback(void* clientp, long long dltotal, long long dlnow, + long long /*ultotal*/, long long /*ulnow*/) { + auto* self = static_cast(clientp); + if (self->cancel_requested_) return 1; // abort transfer + + // When resuming, dlnow/dltotal only reflect the *remaining* portion. + // Add resume_offset_ so the user sees true total progress. + double offset = self->resume_offset_; + double realNow = offset + (double)dlnow; + double realTotal = (dltotal > 0) ? (offset + (double)dltotal) : 0.0; + + std::string sizeText = formatSize(realNow) + " / " + + (realTotal > 0 ? formatSize(realTotal) : "unknown"); + self->setProgress(State::Downloading, sizeText, realNow, realTotal); + return 0; +} + +bool Bootstrap::download(const std::string& url, const std::string& destZip) { + CURL* curl = curl_easy_init(); + if (!curl) { + setProgress(State::Failed, "Failed to initialise libcurl"); + return false; + } + + // --- Resume support with integrity check --- + // Check if a partial file exists from a previous attempt. + long long existing_bytes = 0; + { + std::error_code ec; + if (fs::exists(destZip, ec) && !ec) { + existing_bytes = (long long)fs::file_size(destZip, ec); + if (ec) existing_bytes = 0; + } + } + + // If we have a partial file, check the remote file size to detect + // server-side changes that would corrupt a resumed download. + if (existing_bytes > 0) { + long long remoteSize = getRemoteFileSize(url); + if (remoteSize > 0) { + if (existing_bytes >= remoteSize) { + // File is already complete (or bigger — stale from an older zip) + DEBUG_LOGF("[Bootstrap] Local file (%lld bytes) >= remote (%lld bytes), re-downloading\n", + existing_bytes, remoteSize); + std::error_code ec; + fs::remove(destZip, ec); + existing_bytes = 0; + } + } else { + // Could not determine remote size — play it safe and re-download + DEBUG_LOGF("[Bootstrap] Could not determine remote file size, re-downloading to be safe\n"); + std::error_code ec; + fs::remove(destZip, ec); + existing_bytes = 0; + } + } + + resume_offset_ = (double)existing_bytes; + + FILE* fp = nullptr; + if (existing_bytes > 0) { + // Open in append-binary mode and tell curl to resume + fp = fopen(destZip.c_str(), "ab"); + if (!fp) { + curl_easy_cleanup(curl); + setProgress(State::Failed, "Failed to open output file for resume: " + destZip); + return false; + } + curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, (curl_off_t)existing_bytes); + DEBUG_LOGF("[Bootstrap] Resuming download from byte %lld\n", existing_bytes); + } else { + fp = fopen(destZip.c_str(), "wb"); + if (!fp) { + curl_easy_cleanup(curl); + setProgress(State::Failed, "Failed to open output file: " + destZip); + return false; + } + } + + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFileCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progressCallback); + curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "ObsidianDragon/1.0"); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); // no timeout for large file + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L); + curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1024L); // abort if < 1 KB/s + curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 60L); // ... for 60 seconds + + // HTTPS certificate verification + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); + + CURLcode res = curl_easy_perform(curl); + fclose(fp); + curl_easy_cleanup(curl); + + if (res == CURLE_RANGE_ERROR) { + // Server does not support range requests — restart from scratch + DEBUG_LOGF("[Bootstrap] Server does not support resume, restarting download\n"); + resume_offset_ = 0; + std::error_code ec; + fs::remove(destZip, ec); + return download(url, destZip); // recursive retry without resume + } + + if (res != CURLE_OK) { + DEBUG_LOGF("[Bootstrap] curl error: %s\n", curl_easy_strerror(res)); + return false; + } + return true; +} + +// --------------------------------------------------------------------------- +// Zip extraction (miniz) +// --------------------------------------------------------------------------- + +bool Bootstrap::extract(const std::string& zipPath, const std::string& dataDir) { + mz_zip_archive zip = {}; + if (!mz_zip_reader_init_file(&zip, zipPath.c_str(), 0)) { + setProgress(State::Failed, "Failed to open zip file"); + return false; + } + + int numFiles = (int)mz_zip_reader_get_num_files(&zip); + for (int i = 0; i < numFiles; i++) { + if (cancel_requested_) { + mz_zip_reader_end(&zip); + return false; + } + + mz_zip_archive_file_stat stat; + if (!mz_zip_reader_file_stat(&zip, i, &stat)) continue; + + std::string filename = stat.m_filename; + + // *** CRITICAL: Skip wallet.dat *** + if (filename == "wallet.dat" || endsWith(filename, "/wallet.dat")) { + DEBUG_LOGF("[Bootstrap] Skipping wallet.dat (protected)\n"); + continue; + } + + std::string destPath = dataDir; + // Ensure trailing separator + if (!destPath.empty() && destPath.back() != '/' && destPath.back() != '\\') + destPath += '/'; + destPath += filename; + + if (mz_zip_reader_is_file_a_directory(&zip, i)) { + std::error_code ec; + fs::create_directories(destPath, ec); + } else { + // Ensure parent directory exists + std::error_code ec; + fs::create_directories(fs::path(destPath).parent_path(), ec); + + if (!mz_zip_reader_extract_to_file(&zip, i, destPath.c_str(), 0)) { + DEBUG_LOGF("[Bootstrap] Failed to extract: %s\n", filename.c_str()); + // Non-fatal: continue with remaining files + } + } + + // Update progress + float pct = (numFiles > 0) ? (100.0f * (i + 1) / numFiles) : 0.0f; + setProgress(State::Extracting, + "Extracting: " + filename, + (double)(i + 1), (double)numFiles); + progress_.percent = pct; // override to use file count ratio + } + + mz_zip_reader_end(&zip); + + // Clean up zip file + std::error_code ec; + fs::remove(zipPath, ec); + + return true; +} + +// --------------------------------------------------------------------------- +// Pre-extraction cleanup +// --------------------------------------------------------------------------- + +void Bootstrap::cleanChainData(const std::string& dataDir) { + // Directories to remove completely + for (const char* subdir : {"blocks", "chainstate", "notarizations"}) { + fs::path p = fs::path(dataDir) / subdir; + std::error_code ec; + if (fs::exists(p, ec)) { + fs::remove_all(p, ec); + if (ec) DEBUG_LOGF("[Bootstrap] Warning: could not remove %s: %s\n", subdir, ec.message().c_str()); + } + } + // Individual files to remove (will be replaced by bootstrap) + for (const char* file : {"fee_estimates.dat", "peers.dat"}) { + fs::path p = fs::path(dataDir) / file; + std::error_code ec; + if (fs::exists(p, ec)) { + fs::remove(p, ec); + } + } + // NEVER remove: wallet.dat, debug.log, .lock, *.conf +} + +// --------------------------------------------------------------------------- +// Small-file download (checksums) +// --------------------------------------------------------------------------- + +static size_t writeStringCallback(void* contents, size_t size, size_t nmemb, void* userp) { + size_t total = size * nmemb; + auto* str = static_cast(userp); + str->append(static_cast(contents), total); + return total; +} + +std::string Bootstrap::downloadSmallFile(const std::string& url) { + CURL* curl = curl_easy_init(); + if (!curl) return {}; + + std::string result; + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "ObsidianDragon/1.0"); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); + + CURLcode res = curl_easy_perform(curl); + curl_easy_cleanup(curl); + + if (res != CURLE_OK) { + DEBUG_LOGF("[Bootstrap] Failed to download %s: %s\n", url.c_str(), curl_easy_strerror(res)); + return {}; + } + return result; +} + +// --------------------------------------------------------------------------- +// Checksum helpers +// --------------------------------------------------------------------------- + +std::string Bootstrap::parseChecksumFile(const std::string& content) { + // Typical format: " " or just "" + // Extract the first whitespace-delimited token. + std::istringstream iss(content); + std::string token; + if (iss >> token) { + // Normalise to lowercase + std::transform(token.begin(), token.end(), token.begin(), + [](unsigned char c) { return std::tolower(c); }); + return token; + } + return {}; +} + +std::string Bootstrap::computeSHA256(const std::string& filePath) { + FILE* fp = fopen(filePath.c_str(), "rb"); + if (!fp) return {}; + + // Get file size for progress reporting + fseek(fp, 0, SEEK_END); + long long fileSize = ftell(fp); + fseek(fp, 0, SEEK_SET); + + crypto_hash_sha256_state state; + crypto_hash_sha256_init(&state); + + unsigned char buf[65536]; + size_t n; + long long processed = 0; + while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { + if (cancel_requested_) { + fclose(fp); + return {}; + } + crypto_hash_sha256_update(&state, buf, n); + processed += (long long)n; + + // Update progress every ~4MB + if (fileSize > 0 && (processed % (4 * 1024 * 1024)) < (long long)sizeof(buf)) { + float pct = (float)(100.0 * processed / fileSize); + char msg[128]; + snprintf(msg, sizeof(msg), "Verifying SHA-256... %.0f%% (%s / %s)", + pct, formatSize((double)processed).c_str(), + formatSize((double)fileSize).c_str()); + setProgress(State::Downloading, msg, (double)processed, (double)fileSize); + } + } + fclose(fp); + + unsigned char hash[crypto_hash_sha256_BYTES]; + crypto_hash_sha256_final(&state, hash); + + std::ostringstream oss; + oss << std::hex << std::setfill('0'); + for (int i = 0; i < crypto_hash_sha256_BYTES; i++) + oss << std::setw(2) << (int)hash[i]; + return oss.str(); +} + +// --------------------------------------------------------------------------- +// MD5 — minimal embedded implementation (RFC 1321) +// --------------------------------------------------------------------------- + +namespace { + +struct MD5Context { + uint32_t state[4]; + uint64_t count; + uint8_t buffer[64]; +}; + +static const uint32_t md5_T[64] = { + 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, + 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,0x6b901122,0xfd987193,0xa679438e,0x49b40821, + 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8, + 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, + 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, + 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, + 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, + 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391 +}; +static const int md5_S[64] = { + 7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22, + 5, 9,14,20,5, 9,14,20,5, 9,14,20,5, 9,14,20, + 4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23, + 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21 +}; + +static inline uint32_t md5_rotl(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); } + +static void md5_transform(uint32_t state[4], const uint8_t block[64]) { + uint32_t M[16]; + for (int i = 0; i < 16; i++) + M[i] = (uint32_t)block[i*4] | ((uint32_t)block[i*4+1]<<8) | + ((uint32_t)block[i*4+2]<<16) | ((uint32_t)block[i*4+3]<<24); + + uint32_t a=state[0], b=state[1], c=state[2], d=state[3]; + for (int i = 0; i < 64; i++) { + uint32_t f, g; + if (i < 16) { f = (b & c) | (~b & d); g = i; } + else if (i < 32) { f = (d & b) | (~d & c); g = (5*i+1) % 16; } + else if (i < 48) { f = b ^ c ^ d; g = (3*i+5) % 16; } + else { f = c ^ (b | ~d); g = (7*i) % 16; } + uint32_t tmp = d; d = c; c = b; + b = b + md5_rotl(a + f + md5_T[i] + M[g], md5_S[i]); + a = tmp; + } + state[0]+=a; state[1]+=b; state[2]+=c; state[3]+=d; +} + +static void md5_init(MD5Context* ctx) { + ctx->state[0]=0x67452301; ctx->state[1]=0xefcdab89; + ctx->state[2]=0x98badcfe; ctx->state[3]=0x10325476; + ctx->count = 0; + memset(ctx->buffer, 0, 64); +} + +static void md5_update(MD5Context* ctx, const uint8_t* data, size_t len) { + size_t idx = (size_t)(ctx->count % 64); + ctx->count += len; + for (size_t i = 0; i < len; i++) { + ctx->buffer[idx++] = data[i]; + if (idx == 64) { md5_transform(ctx->state, ctx->buffer); idx = 0; } + } +} + +static void md5_final(MD5Context* ctx, uint8_t digest[16]) { + uint64_t bits = ctx->count * 8; + uint8_t pad = 0x80; + md5_update(ctx, &pad, 1); + pad = 0; + while (ctx->count % 64 != 56) md5_update(ctx, &pad, 1); + uint8_t bitbuf[8]; + for (int i = 0; i < 8; i++) bitbuf[i] = (uint8_t)(bits >> (i*8)); + md5_update(ctx, bitbuf, 8); + for (int i = 0; i < 4; i++) { + digest[i*4+0] = (uint8_t)(ctx->state[i]); + digest[i*4+1] = (uint8_t)(ctx->state[i]>>8); + digest[i*4+2] = (uint8_t)(ctx->state[i]>>16); + digest[i*4+3] = (uint8_t)(ctx->state[i]>>24); + } +} + +} // anon namespace + +std::string Bootstrap::computeMD5(const std::string& filePath) { + FILE* fp = fopen(filePath.c_str(), "rb"); + if (!fp) return {}; + + // Get file size for progress reporting + fseek(fp, 0, SEEK_END); + long long fileSize = ftell(fp); + fseek(fp, 0, SEEK_SET); + + MD5Context ctx; + md5_init(&ctx); + + uint8_t buf[65536]; + size_t n; + long long processed = 0; + while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { + if (cancel_requested_) { + fclose(fp); + return {}; + } + md5_update(&ctx, buf, n); + processed += (long long)n; + + // Update progress every ~4MB + if (fileSize > 0 && (processed % (4 * 1024 * 1024)) < (long long)sizeof(buf)) { + float pct = (float)(100.0 * processed / fileSize); + char msg[128]; + snprintf(msg, sizeof(msg), "Verifying MD5... %.0f%% (%s / %s)", + pct, formatSize((double)processed).c_str(), + formatSize((double)fileSize).c_str()); + setProgress(State::Downloading, msg, (double)processed, (double)fileSize); + } + } + fclose(fp); + + uint8_t digest[16]; + md5_final(&ctx, digest); + + std::ostringstream oss; + oss << std::hex << std::setfill('0'); + for (int i = 0; i < 16; i++) + oss << std::setw(2) << (int)digest[i]; + return oss.str(); +} + +// --------------------------------------------------------------------------- +// Checksum verification pipeline +// --------------------------------------------------------------------------- + +bool Bootstrap::verifyChecksums(const std::string& zipPath, const std::string& baseUrl) { + setProgress(State::Downloading, "Downloading checksums..."); + + std::string sha256Url = baseUrl + "/" + kZipName + ".sha256"; + std::string md5Url = baseUrl + "/" + kZipName + ".md5"; + + std::string sha256Content = downloadSmallFile(sha256Url); + std::string md5Content = downloadSmallFile(md5Url); + + if (cancel_requested_) return false; + + bool haveSHA256 = !sha256Content.empty(); + bool haveMD5 = !md5Content.empty(); + + if (!haveSHA256 && !haveMD5) { + DEBUG_LOGF("[Bootstrap] Warning: no checksum files available — skipping verification\n"); + // Allow the process to continue (server may not have checksum files yet) + return true; + } + + // --- SHA-256 --- + if (haveSHA256) { + setProgress(State::Downloading, "Verifying SHA-256..."); + std::string expected = parseChecksumFile(sha256Content); + std::string actual = computeSHA256(zipPath); + + if (cancel_requested_) return false; + + if (expected.empty() || actual.empty()) { + DEBUG_LOGF("[Bootstrap] SHA-256: could not compute/parse (expected=%s, actual=%s)\n", + expected.c_str(), actual.c_str()); + setProgress(State::Failed, "SHA-256 verification error"); + return false; + } + + if (expected != actual) { + DEBUG_LOGF("[Bootstrap] SHA-256 MISMATCH!\n expected: %s\n actual: %s\n", + expected.c_str(), actual.c_str()); + setProgress(State::Failed, + "SHA-256 mismatch — the server's checksum file may be out of date.\n" + "Expected: " + expected.substr(0, 16) + "...\n" + "Got: " + actual.substr(0, 16) + "...\n" + "Try again or use a fresh download."); + return false; + } + DEBUG_LOGF("[Bootstrap] SHA-256 verified: %s\n", actual.c_str()); + } + + // --- MD5 --- + if (haveMD5) { + setProgress(State::Downloading, "Verifying MD5..."); + std::string expected = parseChecksumFile(md5Content); + std::string actual = computeMD5(zipPath); + + if (cancel_requested_) return false; + + if (expected.empty() || actual.empty()) { + DEBUG_LOGF("[Bootstrap] MD5: could not compute/parse (expected=%s, actual=%s)\n", + expected.c_str(), actual.c_str()); + setProgress(State::Failed, "MD5 verification error"); + return false; + } + + if (expected != actual) { + DEBUG_LOGF("[Bootstrap] MD5 MISMATCH!\n expected: %s\n actual: %s\n", + expected.c_str(), actual.c_str()); + setProgress(State::Failed, + "MD5 mismatch — the server's checksum file may be out of date.\n" + "Expected: " + expected + "\n" + "Got: " + actual + "\n" + "Try again or use a fresh download."); + return false; + } + DEBUG_LOGF("[Bootstrap] MD5 verified: %s\n", actual.c_str()); + } + + setProgress(State::Downloading, "Checksums verified \xe2\x9c\x93"); + return true; +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/bootstrap.h b/src/util/bootstrap.h new file mode 100644 index 0000000..7b6a944 --- /dev/null +++ b/src/util/bootstrap.h @@ -0,0 +1,116 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include +#include +#include + +namespace dragonx { +namespace util { + +/** + * @brief Bootstrap downloader + extractor for DRAGONX blockchain data. + * + * Downloads a blockchain snapshot zip from bootstrap.dragonx.is, verifies + * SHA-256 / MD5 checksums, extracts it into the DRAGONX data directory + * (skipping wallet.dat), and cleans old chain data before extraction. + * All work runs on a background thread; progress is queried thread-safely + * from the UI thread. + */ +class Bootstrap { +public: + enum class State { + Idle, + Downloading, + Extracting, + Completed, + Failed + }; + + struct Progress { + State state = State::Idle; + double downloaded_bytes = 0; + double total_bytes = 0; // 0 if server doesn't send Content-Length + float percent = 0.0f; // 0..100 + std::string status_text; // human-readable status + std::string error; // non-empty on failure + }; + + Bootstrap() = default; + ~Bootstrap(); + + // Non-copyable + Bootstrap(const Bootstrap&) = delete; + Bootstrap& operator=(const Bootstrap&) = delete; + + /// Base URL for bootstrap downloads (zip + checksum files). + static constexpr const char* kBaseUrl = "https://bootstrap.dragonx.is"; + static constexpr const char* kZipName = "DRAGONX.zip"; + + /// Start the bootstrap process on a background thread. + /// @param dataDir Path to DRAGONX data dir (e.g. ~/.hush/DRAGONX/) + /// @param url Bootstrap zip URL + void start(const std::string& dataDir, + const std::string& url = "https://bootstrap.dragonx.is/DRAGONX.zip"); + + /// Cancel an in-progress download/extract. + void cancel(); + + /// Thread-safe read of current progress. + Progress getProgress() const; + + /// Whether the operation is finished (success or failure). + bool isDone() const; + + /// Format a byte count as human-readable string (e.g. "1.24 GB") + static std::string formatSize(double bytes); + +private: + mutable std::mutex mutex_; + Progress progress_; + std::atomic cancel_requested_{false}; + std::thread worker_; + std::atomic worker_running_{false}; + + bool download(const std::string& url, const std::string& destZip); + bool extract(const std::string& zipPath, const std::string& dataDir); + void cleanChainData(const std::string& dataDir); + void setProgress(State state, const std::string& text, double downloaded = 0, double total = 0); + + /// Download a small text file (checksum) into a string. Returns empty on failure. + std::string downloadSmallFile(const std::string& url); + + /// Compute SHA-256 of a file, return lowercase hex digest. + /// Updates progress with "Verifying SHA-256..." status during computation. + std::string computeSHA256(const std::string& filePath); + + /// Compute MD5 of a file, return lowercase hex digest. + /// Updates progress with "Verifying MD5..." status during computation. + std::string computeMD5(const std::string& filePath); + + /// Parse the first hex token from a checksum file (handles " " format). + static std::string parseChecksumFile(const std::string& content); + + /// Verify downloaded zip against remote checksums. Returns true if valid. + bool verifyChecksums(const std::string& zipPath, const std::string& baseUrl); + + /// Perform a HEAD request to get remote file size. + /// Returns -1 on failure. + long long getRemoteFileSize(const std::string& url); + + /// Byte offset of the partial file when resuming a download. + /// Added to dlnow in progress reports so the bar reflects true total. + double resume_offset_{0}; + + // libcurl progress callback (static → calls into instance via clientp) + static int progressCallback(void* clientp, long long dltotal, long long dlnow, + long long ultotal, long long ulnow); +}; + +} // namespace util +} // namespace dragonx diff --git a/src/util/i18n.cpp b/src/util/i18n.cpp new file mode 100644 index 0000000..f8a4fde --- /dev/null +++ b/src/util/i18n.cpp @@ -0,0 +1,321 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "i18n.h" + +#include +#include +#include +#include + +// Embedded language files +#include "embedded/lang_es.h" +#include "embedded/lang_zh.h" +#include "embedded/lang_ru.h" +#include "embedded/lang_de.h" +#include "embedded/lang_fr.h" +#include "embedded/lang_pt.h" +#include "embedded/lang_ja.h" +#include "embedded/lang_ko.h" +#include "../util/logger.h" + +namespace dragonx { +namespace util { + +using json = nlohmann::json; + +I18n::I18n() +{ + // Register built-in languages + registerLanguage("en", "English"); + registerLanguage("es", "Español"); + registerLanguage("zh", "中文"); + registerLanguage("ru", "Русский"); + registerLanguage("de", "Deutsch"); + registerLanguage("fr", "Français"); + registerLanguage("pt", "Português"); + registerLanguage("ja", "日本語"); + registerLanguage("ko", "한국어"); + + // Load default English strings (built-in fallback) + loadLanguage("en"); +} + +I18n& I18n::instance() +{ + static I18n instance; + return instance; +} + +bool I18n::loadLanguage(const std::string& locale) +{ + // First, try to load from file (allows user overrides) + std::string lang_file = "res/lang/" + locale + ".json"; + std::ifstream file(lang_file); + + if (file.is_open()) { + try { + json j; + file >> j; + + strings_.clear(); + for (auto& [key, value] : j.items()) { + if (value.is_string()) { + strings_[key] = value.get(); + } + } + + current_locale_ = locale; + DEBUG_LOGF("Loaded language file: %s (%zu strings)\n", lang_file.c_str(), strings_.size()); + return true; + + } catch (const std::exception& e) { + DEBUG_LOGF("Error parsing language file %s: %s\n", lang_file.c_str(), e.what()); + } + } + + // Try embedded language data + const unsigned char* embedded_data = nullptr; + unsigned int embedded_size = 0; + + if (locale == "es") { + embedded_data = res_lang_es_json; + embedded_size = res_lang_es_json_len; + } else if (locale == "zh") { + embedded_data = res_lang_zh_json; + embedded_size = res_lang_zh_json_len; + } else if (locale == "ru") { + embedded_data = res_lang_ru_json; + embedded_size = res_lang_ru_json_len; + } else if (locale == "de") { + embedded_data = res_lang_de_json; + embedded_size = res_lang_de_json_len; + } else if (locale == "fr") { + embedded_data = res_lang_fr_json; + embedded_size = res_lang_fr_json_len; + } else if (locale == "pt") { + embedded_data = res_lang_pt_json; + embedded_size = res_lang_pt_json_len; + } else if (locale == "ja") { + embedded_data = res_lang_ja_json; + embedded_size = res_lang_ja_json_len; + } else if (locale == "ko") { + embedded_data = res_lang_ko_json; + embedded_size = res_lang_ko_json_len; + } + + if (embedded_data != nullptr && embedded_size > 0) { + try { + std::string json_str(reinterpret_cast(embedded_data), embedded_size); + json j = json::parse(json_str); + + strings_.clear(); + for (auto& [key, value] : j.items()) { + if (value.is_string()) { + strings_[key] = value.get(); + } + } + + current_locale_ = locale; + DEBUG_LOGF("Loaded embedded language: %s (%zu strings)\n", locale.c_str(), strings_.size()); + return true; + + } catch (const std::exception& e) { + DEBUG_LOGF("Error parsing embedded language %s: %s\n", locale.c_str(), e.what()); + } + } + + // If English, use built-in strings + if (locale == "en") { + strings_.clear(); + + // Navigation & Tabs + strings_["balance"] = "Balance"; + strings_["send"] = "Send"; + strings_["receive"] = "Receive"; + strings_["transactions"] = "Transactions"; + strings_["mining"] = "Mining"; + strings_["peers"] = "Peers"; + strings_["market"] = "Market"; + strings_["settings"] = "Settings"; + + // Balance Tab + strings_["summary"] = "Summary"; + strings_["shielded"] = "Shielded"; + strings_["transparent"] = "Transparent"; + strings_["total"] = "Total"; + strings_["unconfirmed"] = "Unconfirmed"; + strings_["your_addresses"] = "Your Addresses"; + strings_["z_addresses"] = "Z-Addresses"; + strings_["t_addresses"] = "T-Addresses"; + strings_["no_addresses"] = "No addresses found. Create one using the buttons above."; + strings_["new_z_address"] = "New Z-Address"; + strings_["new_t_address"] = "New T-Address"; + strings_["type"] = "Type"; + strings_["address"] = "Address"; + strings_["copy_address"] = "Copy Full Address"; + strings_["send_from_this_address"] = "Send From This Address"; + strings_["export_private_key"] = "Export Private Key"; + strings_["export_viewing_key"] = "Export Viewing Key"; + strings_["show_qr_code"] = "Show QR Code"; + strings_["not_connected"] = "Not connected to daemon..."; + + // Send Tab + strings_["pay_from"] = "Pay From"; + strings_["send_to"] = "Send To"; + strings_["amount"] = "Amount"; + strings_["memo"] = "Memo (optional, encrypted)"; + strings_["miner_fee"] = "Miner Fee"; + strings_["fee"] = "Fee"; + strings_["send_transaction"] = "Send Transaction"; + strings_["clear"] = "Clear"; + strings_["select_address"] = "Select address..."; + strings_["paste"] = "Paste"; + strings_["max"] = "Max"; + strings_["available"] = "Available"; + strings_["invalid_address"] = "Invalid address format"; + strings_["memo_z_only"] = "Note: Memos are only available when sending to shielded (z) addresses"; + strings_["characters"] = "characters"; + strings_["from"] = "From"; + strings_["to"] = "To"; + strings_["sending"] = "Sending transaction"; + strings_["confirm_send"] = "Confirm Send"; + strings_["confirm_transaction"] = "Confirm Transaction"; + strings_["confirm_and_send"] = "Confirm & Send"; + strings_["cancel"] = "Cancel"; + + // Receive Tab + strings_["receiving_addresses"] = "Your Receiving Addresses"; + strings_["new_z_shielded"] = "New z-Address (Shielded)"; + strings_["new_t_transparent"] = "New t-Address (Transparent)"; + strings_["address_details"] = "Address Details"; + strings_["view_on_explorer"] = "View on Explorer"; + strings_["qr_code"] = "QR Code"; + strings_["request_payment"] = "Request Payment"; + + // Transactions Tab + strings_["date"] = "Date"; + strings_["status"] = "Status"; + strings_["confirmations"] = "Confirmations"; + strings_["confirmed"] = "Confirmed"; + strings_["pending"] = "Pending"; + strings_["sent"] = "sent"; + strings_["received"] = "received"; + strings_["mined"] = "mined"; + + // Mining Tab + strings_["mining_control"] = "Mining Control"; + strings_["start_mining"] = "Start Mining"; + strings_["stop_mining"] = "Stop Mining"; + strings_["mining_threads"] = "Mining Threads"; + strings_["mining_statistics"] = "Mining Statistics"; + strings_["local_hashrate"] = "Local Hashrate"; + strings_["network_hashrate"] = "Network Hashrate"; + strings_["difficulty"] = "Difficulty"; + strings_["est_time_to_block"] = "Est. Time to Block"; + strings_["mining_off"] = "Mining is OFF"; + strings_["mining_on"] = "Mining is ON"; + + // Peers Tab + strings_["connected_peers"] = "Connected Peers"; + strings_["banned_peers"] = "Banned Peers"; + strings_["ip_address"] = "IP Address"; + strings_["version"] = "Version"; + strings_["height"] = "Height"; + strings_["ping"] = "Ping"; + strings_["ban"] = "Ban"; + strings_["unban"] = "Unban"; + strings_["clear_all_bans"] = "Clear All Bans"; + + // Market Tab + strings_["price_chart"] = "Price Chart"; + strings_["current_price"] = "Current Price"; + strings_["24h_change"] = "24h Change"; + strings_["24h_volume"] = "24h Volume"; + strings_["market_cap"] = "Market Cap"; + + // Settings + strings_["general"] = "General"; + strings_["display"] = "Display"; + strings_["network"] = "Network"; + strings_["theme"] = "Theme"; + strings_["language"] = "Language"; + strings_["dragonx_green"] = "DragonX (Green)"; + strings_["dark"] = "Dark"; + strings_["light"] = "Light"; + strings_["allow_custom_fees"] = "Allow custom fees"; + strings_["use_embedded_daemon"] = "Use embedded dragonxd"; + strings_["save"] = "Save"; + strings_["close"] = "Close"; + + // Menu + strings_["file"] = "File"; + strings_["edit"] = "Edit"; + strings_["view"] = "View"; + strings_["help"] = "Help"; + strings_["import_private_key"] = "Import Private Key..."; + strings_["backup_wallet"] = "Backup Wallet..."; + strings_["exit"] = "Exit"; + strings_["about_dragonx"] = "About ObsidianDragon"; + strings_["refresh_now"] = "Refresh Now"; + + // Dialogs + strings_["about"] = "About"; + strings_["import"] = "Import"; + strings_["export"] = "Export"; + strings_["copy_to_clipboard"] = "Copy to Clipboard"; + + // Status + strings_["connected"] = "Connected"; + strings_["disconnected"] = "Disconnected"; + strings_["connecting"] = "Connecting..."; + strings_["syncing"] = "Syncing..."; + strings_["block"] = "Block"; + strings_["no_addresses_available"] = "No addresses available"; + + // Errors & Messages + strings_["error"] = "Error"; + strings_["success"] = "Success"; + strings_["warning"] = "Warning"; + strings_["amount_exceeds_balance"] = "Amount exceeds balance"; + strings_["transaction_sent"] = "Transaction sent successfully"; + + current_locale_ = "en"; + DEBUG_LOGF("Using built-in English strings (%zu strings)\n", strings_.size()); + return true; + } + + // Fallback: reload English so we never leave stale strings + DEBUG_LOGF("Language file not found: %s — falling back to English\n", lang_file.c_str()); + if (locale != "en") { + loadLanguage("en"); + } + return false; +} + +const char* I18n::translate(const char* key) const +{ + if (!key) return ""; + + auto it = strings_.find(key); + if (it != strings_.end()) { + return it->second.c_str(); + } + + // Return key if translation not found + return key; +} + +void I18n::registerLanguage(const std::string& code, const std::string& name) +{ + // Check if already registered + for (const auto& lang : available_languages_) { + if (lang.first == code) return; + } + + available_languages_.emplace_back(code, name); +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/i18n.h b/src/util/i18n.h new file mode 100644 index 0000000..ca1bae6 --- /dev/null +++ b/src/util/i18n.h @@ -0,0 +1,79 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include + +namespace dragonx { +namespace util { + +/** + * @brief Internationalization support + * + * Simple string table implementation for translating UI text. + * Strings are stored in JSON files in res/lang/ directory. + */ +class I18n { +public: + /** + * @brief Get the singleton instance + */ + static I18n& instance(); + + /** + * @brief Load a language file + * @param locale Language code (e.g., "en", "es", "zh") + * @return true if loaded successfully + */ + bool loadLanguage(const std::string& locale); + + /** + * @brief Translate a string + * @param key The string key (usually English text) + * @return Translated string, or key if not found + */ + const char* translate(const char* key) const; + + /** + * @brief Get current locale + */ + const std::string& getCurrentLocale() const { return current_locale_; } + + /** + * @brief Get list of available languages + */ + const std::vector>& getAvailableLanguages() const { return available_languages_; } + + /** + * @brief Register an available language + * @param code Language code (e.g., "en") + * @param name Display name (e.g., "English") + */ + void registerLanguage(const std::string& code, const std::string& name); + +private: + I18n(); + + std::string current_locale_ = "en"; + std::unordered_map strings_; + std::vector> available_languages_; +}; + +/** + * @brief Convenience function for translation + * @param key The string key + * @return Translated string + */ +inline const char* tr(const char* key) { + return I18n::instance().translate(key); +} + +} // namespace util +} // namespace dragonx + +// Convenience macro for translations +#define TR(key) dragonx::util::tr(key) diff --git a/src/util/logger.cpp b/src/util/logger.cpp new file mode 100644 index 0000000..17e4aa3 --- /dev/null +++ b/src/util/logger.cpp @@ -0,0 +1,91 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "logger.h" + +#include +#include +#include +#include +#include + +namespace dragonx { +namespace util { + +Logger::Logger() = default; + +Logger::~Logger() +{ + if (file_.is_open()) { + file_.close(); + } +} + +Logger& Logger::instance() +{ + static Logger logger; + return logger; +} + +bool Logger::init(const std::string& path) +{ + std::lock_guard lock(mutex_); + + if (file_.is_open()) { + file_.close(); + } + + file_.open(path, std::ios::out | std::ios::app); + initialized_ = file_.is_open(); + + if (initialized_) { + write("=== Logger initialized ==="); + } + + return initialized_; +} + +void Logger::write(const std::string& message) +{ + std::lock_guard lock(mutex_); + + // Get current timestamp + auto now = std::chrono::system_clock::now(); + auto time = std::chrono::system_clock::to_time_t(now); + auto ms = std::chrono::duration_cast( + now.time_since_epoch()) % 1000; + + std::stringstream ss; + ss << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S"); + ss << '.' << std::setfill('0') << std::setw(3) << ms.count(); + ss << " | " << message; + + std::string line = ss.str(); + + // Write to file if open + if (file_.is_open()) { + file_ << line << std::endl; + file_.flush(); + } + + // Also write to stdout in debug mode +#ifdef DRAGONX_DEBUG + printf("%s\n", line.c_str()); +#endif +} + +void Logger::writef(const char* format, ...) +{ + char buffer[4096]; + + va_list args; + va_start(args, format); + vsnprintf(buffer, sizeof(buffer), format, args); + va_end(args); + + write(buffer); +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/logger.h b/src/util/logger.h new file mode 100644 index 0000000..c4a5460 --- /dev/null +++ b/src/util/logger.h @@ -0,0 +1,65 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include +#include +#include + +namespace dragonx { +namespace util { + +/** + * @brief Simple file logger + */ +class Logger { +public: + Logger(); + ~Logger(); + + /** + * @brief Initialize logger with output file + * @param path Path to log file + * @return true if opened successfully + */ + bool init(const std::string& path); + + /** + * @brief Write a log message + * @param message Message to log + */ + void write(const std::string& message); + + /** + * @brief Write a formatted log message + * @param format printf-style format string + */ + void writef(const char* format, ...); + + /** + * @brief Get the singleton instance + */ + static Logger& instance(); + +private: + std::ofstream file_; + std::mutex mutex_; + bool initialized_ = false; +}; + +// Convenience macros +#define LOG(msg) dragonx::util::Logger::instance().write(msg) +#define LOGF(...) dragonx::util::Logger::instance().writef(__VA_ARGS__) + +#ifdef DRAGONX_DEBUG +#define DEBUG_LOG(msg) LOG(msg) +#define DEBUG_LOGF(...) LOGF(__VA_ARGS__) +#else +#define DEBUG_LOG(msg) +#define DEBUG_LOGF(...) +#endif + +} // namespace util +} // namespace dragonx diff --git a/src/util/noise_texture.cpp b/src/util/noise_texture.cpp new file mode 100644 index 0000000..61935f0 --- /dev/null +++ b/src/util/noise_texture.cpp @@ -0,0 +1,168 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "noise_texture.h" +#include "texture_loader.h" +#include +#include + +namespace dragonx { +namespace util { + +static constexpr int kNoiseSize = 256; + +ImTextureID GetNoiseTexture(int* texSize) +{ + static ImTextureID s_tex = 0; + static bool s_init = false; + + if (texSize) *texSize = kNoiseSize; + + if (s_init) return s_tex; + s_init = true; + + // Generate subtle white-noise RGBA pixels. + // Each pixel is white (RGB=255) with alpha in a narrow band + // around 128 so the grain is uniform and gentle. + const int numPixels = kNoiseSize * kNoiseSize; + unsigned char* pixels = (unsigned char*)malloc(numPixels * 4); + if (!pixels) return 0; + + // Simple LCG PRNG (deterministic, fast, no need for crypto quality) + unsigned int seed = 0xDEADBEEF; + for (int i = 0; i < numPixels; ++i) { + seed = seed * 1664525u + 1013904223u; + // Range: 16–240 (centered on 128, ±112) for visible, high-contrast grain + unsigned char v = 16 + (unsigned char)((seed >> 24) % 225); + pixels[i * 4 + 0] = 255; // R + pixels[i * 4 + 1] = 255; // G + pixels[i * 4 + 2] = 255; // B + pixels[i * 4 + 3] = v; // A — high contrast variation + } + + bool ok = CreateRawTexture(pixels, kNoiseSize, kNoiseSize, + true /* repeat/tile */, &s_tex); + free(pixels); + + if (!ok) { + s_tex = 0; + } + return s_tex; +} + +// ============================================================================ +// Pre-tiled viewport-sized noise texture +// ============================================================================ + +// Generate the base 256x256 noise pattern into a caller-allocated buffer. +// Same deterministic LCG as GetNoiseTexture(). +static void GenerateBaseNoise(unsigned char* out, int sz) +{ + unsigned int seed = 0xDEADBEEF; + const int numPixels = sz * sz; + for (int i = 0; i < numPixels; ++i) { + seed = seed * 1664525u + 1013904223u; + unsigned char v = 16 + (unsigned char)((seed >> 24) % 225); + out[i * 4 + 0] = 255; + out[i * 4 + 1] = 255; + out[i * 4 + 2] = 255; + out[i * 4 + 3] = v; + } +} + +ImTextureID GetTiledNoiseTexture(int viewportW, int viewportH, + int* outW, int* outH) +{ + static ImTextureID s_tex = 0; + static int s_texW = 0; + static int s_texH = 0; + + if (outW) *outW = s_texW; + if (outH) *outH = s_texH; + + // Re-use if viewport hasn't changed + if (s_tex && s_texW == viewportW && s_texH == viewportH) { + return s_tex; + } + + // Destroy old texture + if (s_tex) { + DestroyTexture(s_tex); + s_tex = 0; + s_texW = s_texH = 0; + } + + if (viewportW <= 0 || viewportH <= 0) return 0; + + // Generate base tile + unsigned char* base = (unsigned char*)malloc(kNoiseSize * kNoiseSize * 4); + if (!base) return 0; + GenerateBaseNoise(base, kNoiseSize); + + // Allocate viewport-sized buffer and tile the base pattern + const size_t rowBytes = (size_t)viewportW * 4; + unsigned char* tiled = (unsigned char*)malloc(rowBytes * viewportH); + if (!tiled) { free(base); return 0; } + + const int basePitch = kNoiseSize * 4; + for (int y = 0; y < viewportH; ++y) { + int sy = y % kNoiseSize; + unsigned char* dst = tiled + y * rowBytes; + const unsigned char* srcRow = base + sy * basePitch; + int x = 0; + // Copy full tile-width strips + while (x + kNoiseSize <= viewportW) { + memcpy(dst + x * 4, srcRow, basePitch); + x += kNoiseSize; + } + // Partial remaining strip + if (x < viewportW) { + memcpy(dst + x * 4, srcRow, (viewportW - x) * 4); + } + } + free(base); + + bool ok = CreateRawTexture(tiled, viewportW, viewportH, + false /* no repeat needed */, &s_tex); + free(tiled); + + if (ok) { + s_texW = viewportW; + s_texH = viewportH; + } else { + s_tex = 0; + } + + if (outW) *outW = s_texW; + if (outH) *outH = s_texH; + return s_tex; +} + +void DrawTiledNoiseRect(ImDrawList* dl, const ImVec2& pMin, const ImVec2& pMax, + ImU32 tintColor) +{ + if (!dl || (tintColor & IM_COL32_A_MASK) == 0) return; + + ImGuiViewport* vp = ImGui::GetMainViewport(); + int vpW = (int)vp->Size.x; + int vpH = (int)vp->Size.y; + if (vpW <= 0 || vpH <= 0) return; + + int texW = 0, texH = 0; + ImTextureID tex = GetTiledNoiseTexture(vpW, vpH, &texW, &texH); + if (!tex || texW <= 0 || texH <= 0) return; + + // Compute UVs: map screen-space rect to texture coordinates. + // The tiled texture covers the entire viewport, so UV = screenPos / vpSize. + // Subtract viewport origin for multi-viewport support. + float u0 = (pMin.x - vp->Pos.x) / (float)texW; + float v0 = (pMin.y - vp->Pos.y) / (float)texH; + float u1 = (pMax.x - vp->Pos.x) / (float)texW; + float v1 = (pMax.y - vp->Pos.y) / (float)texH; + + dl->AddImage(tex, pMin, pMax, ImVec2(u0, v0), ImVec2(u1, v1), tintColor); +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/noise_texture.h b/src/util/noise_texture.h new file mode 100644 index 0000000..fb8024e --- /dev/null +++ b/src/util/noise_texture.h @@ -0,0 +1,35 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include "imgui.h" + +namespace dragonx { +namespace util { + +// Returns a cached noise texture (created on first call). +// The texture is a 256x256 tileable white-noise pattern with +// per-pixel random alpha (0-255) designed to be overlaid at very +// low opacity to give cards a subtle grain / paper texture. +// +// texSize receives 256 (the width/height of the texture). +ImTextureID GetNoiseTexture(int* texSize = nullptr); + +// Returns a viewport-sized pre-tiled noise texture (single draw call). +// The 256x256 base noise is tiled across the given viewport dimensions. +// Re-creates the texture when the viewport size changes. +// outW/outH receive the actual texture dimensions. +ImTextureID GetTiledNoiseTexture(int viewportW, int viewportH, + int* outW = nullptr, int* outH = nullptr); + +// Draw a tiled noise overlay in a single AddImage call. +// Uses the pre-tiled viewport-sized texture — call this instead of +// manually looping with AddImage for each tile. +// dl: draw list, pMin/pMax: rect to cover, tintColor: alpha-premultiplied tint. +void DrawTiledNoiseRect(ImDrawList* dl, const ImVec2& pMin, const ImVec2& pMax, + ImU32 tintColor); + +} // namespace util +} // namespace dragonx diff --git a/src/util/payment_uri.cpp b/src/util/payment_uri.cpp new file mode 100644 index 0000000..e7ed5d6 --- /dev/null +++ b/src/util/payment_uri.cpp @@ -0,0 +1,147 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#include "payment_uri.h" + +#include +#include +#include + +namespace dragonx { +namespace util { + +std::string urlDecode(const std::string& encoded) +{ + std::string result; + result.reserve(encoded.size()); + + for (size_t i = 0; i < encoded.size(); i++) { + if (encoded[i] == '%' && i + 2 < encoded.size()) { + // Decode hex pair + char hex[3] = { encoded[i + 1], encoded[i + 2], '\0' }; + char* end; + long val = strtol(hex, &end, 16); + if (end == hex + 2) { + result += static_cast(val); + i += 2; + continue; + } + } else if (encoded[i] == '+') { + result += ' '; + continue; + } + result += encoded[i]; + } + + return result; +} + +bool isPaymentURI(const std::string& str) +{ + // Check for drgx: or hush: prefix (case insensitive) + std::string lower = str; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + return lower.substr(0, 5) == "drgx:" || lower.substr(0, 5) == "hush:"; +} + +PaymentURI parsePaymentURI(const std::string& uri) +{ + PaymentURI result; + result.valid = false; + + // Check prefix + if (!isPaymentURI(uri)) { + result.error = "Invalid URI scheme. Expected drgx: or hush:"; + return result; + } + + // Skip the scheme prefix (drgx: or hush:) + size_t schemeEnd = uri.find(':'); + if (schemeEnd == std::string::npos) { + result.error = "Invalid URI format"; + return result; + } + + std::string remainder = uri.substr(schemeEnd + 1); + + // Handle double-slash format (drgx://address) + if (remainder.size() >= 2 && remainder[0] == '/' && remainder[1] == '/') { + remainder = remainder.substr(2); + } + + // Split address and query string + size_t queryStart = remainder.find('?'); + if (queryStart == std::string::npos) { + // No query parameters, just the address + result.address = remainder; + } else { + result.address = remainder.substr(0, queryStart); + std::string queryString = remainder.substr(queryStart + 1); + + // Parse query parameters + std::istringstream queryStream(queryString); + std::string param; + + while (std::getline(queryStream, param, '&')) { + size_t eqPos = param.find('='); + if (eqPos == std::string::npos) continue; + + std::string key = param.substr(0, eqPos); + std::string value = urlDecode(param.substr(eqPos + 1)); + + // Convert key to lowercase for case-insensitive matching + std::transform(key.begin(), key.end(), key.begin(), ::tolower); + + if (key == "amount" || key == "amt") { + try { + result.amount = std::stod(value); + } catch (...) { + // Invalid amount, keep as 0 + } + } else if (key == "label") { + result.label = value; + } else if (key == "memo") { + result.memo = value; + } else if (key == "message" || key == "msg") { + result.message = value; + } + } + } + + // Validate address + if (result.address.empty()) { + result.error = "No address specified in URI"; + return result; + } + + // Basic address format check + bool validFormat = false; + + // z-address: starts with 'zs' and is 78+ chars + if (result.address[0] == 'z' && result.address.size() >= 78) { + validFormat = true; + } + // t-address: starts with 'R' (DragonX) or 't' (HUSH) and is ~34 chars + else if ((result.address[0] == 'R' || result.address[0] == 't') && + result.address.size() >= 26 && result.address.size() <= 36) { + validFormat = true; + } + + if (!validFormat) { + result.error = "Invalid address format"; + return result; + } + + // Validate amount if present + if (result.amount < 0) { + result.error = "Invalid negative amount"; + return result; + } + + result.valid = true; + return result; +} + +} // namespace util +} // namespace dragonx diff --git a/src/util/payment_uri.h b/src/util/payment_uri.h new file mode 100644 index 0000000..8927974 --- /dev/null +++ b/src/util/payment_uri.h @@ -0,0 +1,51 @@ +// DragonX Wallet - ImGui Edition +// Copyright 2024-2026 The Hush Developers +// Released under the GPLv3 + +#pragma once + +#include + +namespace dragonx { +namespace util { + +/** + * @brief Parsed payment URI data + */ +struct PaymentURI { + std::string address; + double amount = 0.0; + std::string label; + std::string memo; + std::string message; + bool valid = false; + std::string error; +}; + +/** + * @brief Parse a DragonX/HUSH payment URI + * + * Supports format: drgx:
?amount=&label=