diff --git a/scripts/sync_template.sh b/scripts/sync_template.sh new file mode 100755 index 0000000..61abc35 --- /dev/null +++ b/scripts/sync_template.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# sync_template.sh - Refresh the standalone app SDK (template/sysroot) from the +# live tree: headers from programs/include + freestanding toolchain headers, +# libraries from programs/lib build outputs. +# Usage: ./scripts/sync_template.sh (from project root; run 'make programs' first) + +set -e + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +SYSROOT="$PROJECT_ROOT/template/sysroot" +INC="$SYSROOT/include" +LIB="$SYSROOT/lib" + +# Include directories from programs/include that form the app SDK surface. +# (gui/dialogs.hpp depends on libloader/, so it ships too.) +SDK_DIRS=(Api gui http libc libloader montauk tls) + +# Library build outputs copied into sysroot/lib. +SDK_LIBS=( + "programs/lib/libc/liblibc.a" + "programs/lib/libc/crt1.o" + "programs/lib/libc/crti.o" + "programs/lib/libc/crtn.o" + "programs/lib/bearssl/libbearssl.a" + "programs/lib/libjpeg/libjpeg.a" + "programs/lib/tls/libtls.a" +) + +# All libraries must exist before we wipe anything. +for f in "${SDK_LIBS[@]}"; do + if [ ! -f "$PROJECT_ROOT/$f" ]; then + echo "sync_template: missing $f - run 'make programs' first" >&2 + exit 1 + fi +done + +# The sysroot is fully generated from the sources below, so rebuild it from +# scratch to drop headers that no longer exist upstream. +rm -rf "$INC" "$LIB" +mkdir -p "$INC" "$LIB" + +# Freestanding C headers (intrinsics, stddef.h, ...) and C++ headers, +# flattened into the sysroot root like the compiler's default search path. +cp -r "$PROJECT_ROOT/kernel/freestnd-c-hdrs/x86_64/include/." "$INC/" +cp -r "$PROJECT_ROOT/kernel/freestnd-cxx-hdrs/x86_64/include/." "$INC/" + +# MontaukOS SDK headers. +for d in "${SDK_DIRS[@]}"; do + cp -r "$PROJECT_ROOT/programs/include/$d" "$INC/$d" +done + +# BearSSL public headers, available both as and . +cp "$PROJECT_ROOT"/programs/lib/bearssl/inc/*.h "$INC/" +mkdir -p "$INC/bearssl" +cp "$PROJECT_ROOT"/programs/lib/bearssl/inc/*.h "$INC/bearssl/" + +# Libraries and CRT objects. +for f in "${SDK_LIBS[@]}"; do + cp "$PROJECT_ROOT/$f" "$LIB/" +done + +echo "sync_template: refreshed $SYSROOT" +echo " headers: freestnd-c-hdrs, freestnd-cxx-hdrs, programs/include/{${SDK_DIRS[*]}}, bearssl" +echo " libraries: $(cd "$LIB" && ls | tr '\n' ' ')" diff --git a/template/README.md b/template/README.md index 0fc2b52..4d01273 100644 --- a/template/README.md +++ b/template/README.md @@ -42,12 +42,13 @@ myapp/ │ └── cxxrt.cpp C++ new/delete runtime (keep this) ├── sysroot/ │ ├── include/ -│ │ ├── montauk/ syscall.h, heap.h, string.h, config.h, toml.h, user.h -│ │ ├── gui/ gui.hpp, canvas.hpp, truetype.hpp, widgets.hpp, svg.hpp, ... +│ │ ├── montauk/ syscall.h, heap.h, thread.h, string.h, config.h, toml.h, user.h +│ │ ├── gui/ gui.hpp, canvas.hpp, truetype.hpp, widgets.hpp, mtk.hpp, dialogs.hpp, ... │ │ ├── http/ http.hpp (HTTP GET/POST/etc. wrapper) │ │ ├── tls/ tls.hpp (HTTPS/TLS, for USE_TLS=1) │ │ ├── Api/ Syscall.hpp (low-level syscall numbers) │ │ ├── libc/ stdio.h, stdlib.h, string.h, ... +│ │ ├── libloader/ libloader.h (shared library loading, used by gui/dialogs.hpp) │ │ ├── bearssl*.h BearSSL headers (for USE_TLS=1) │ │ └── (freestanding C/C++ standard headers) │ └── lib/ @@ -74,3 +75,11 @@ myapp/ - No exceptions, no RTTI, 32 KiB user stack `USE_CRT=1` is meant for plain C ports and other code that already expects `main(argc, argv)`. The current CRT does not run global constructors or destructors yet, so keep using `_start()` for the default C++ template flow. + +## Keeping the SDK Current + +The sysroot is a snapshot of the MontaukOS tree (headers from `programs/include` plus the freestanding toolchain headers, libraries from `programs/lib`). To refresh it after kernel or library changes, run from the MontaukOS project root: + +```bash +make programs && ./scripts/sync_template.sh +``` diff --git a/template/bin/myapp.elf b/template/bin/myapp.elf index 51b7260..f691b04 100755 Binary files a/template/bin/myapp.elf and b/template/bin/myapp.elf differ diff --git a/template/obj/src/cxxrt.o b/template/obj/src/cxxrt.o index e1ea148..17591f9 100644 Binary files a/template/obj/src/cxxrt.o and b/template/obj/src/cxxrt.o differ diff --git a/template/obj/src/main.o b/template/obj/src/main.o index 121099f..352b7c5 100644 Binary files a/template/obj/src/main.o and b/template/obj/src/main.o differ diff --git a/template/obj/src/stb_truetype_impl.o b/template/obj/src/stb_truetype_impl.o index c5e4bb0..65ff948 100644 Binary files a/template/obj/src/stb_truetype_impl.o and b/template/obj/src/stb_truetype_impl.o differ diff --git a/template/sysroot/include/Api/Syscall.hpp b/template/sysroot/include/Api/Syscall.hpp index 88f3ac3..aa16747 100644 --- a/template/sysroot/include/Api/Syscall.hpp +++ b/template/sysroot/include/Api/Syscall.hpp @@ -57,8 +57,6 @@ namespace Montauk { static constexpr uint64_t SYS_FDELETE = 77; static constexpr uint64_t SYS_FMKDIR = 78; static constexpr uint64_t SYS_DRIVELIST = 79; - static constexpr uint64_t SYS_DRIVELABEL = 124; - static constexpr uint64_t SYS_NETSTATUS = 125; static constexpr uint64_t SYS_TERMSCALE = 43; static constexpr uint64_t SYS_RESOLVE = 44; static constexpr uint64_t SYS_GETRANDOM = 45; @@ -78,6 +76,7 @@ namespace Montauk { static constexpr uint64_t SYS_WINPOLL = 57; static constexpr uint64_t SYS_WINENUM = 58; static constexpr uint64_t SYS_WINMAP = 59; + static constexpr uint64_t SYS_WINUNMAP = 97; static constexpr uint64_t SYS_WINSENDEVENT = 60; static constexpr uint64_t SYS_WINRESIZE = 64; static constexpr uint64_t SYS_WINSETSCALE = 65; @@ -123,14 +122,100 @@ namespace Montauk { static constexpr uint64_t SYS_SETTZ = 90; static constexpr uint64_t SYS_GETTZ = 91; - // Audio control commands (for SYS_AUDIOCTL) - static constexpr int AUDIO_CTL_SET_VOLUME = 0; - static constexpr int AUDIO_CTL_GET_VOLUME = 1; - static constexpr int AUDIO_CTL_GET_POS = 2; - static constexpr int AUDIO_CTL_PAUSE = 3; - static constexpr int AUDIO_CTL_GET_OUTPUT = 4; // 0=HDA, 1=Bluetooth - static constexpr int AUDIO_CTL_SET_OUTPUT = 5; // Switch audio output - static constexpr int AUDIO_CTL_BT_STATUS = 6; // Get Bluetooth connection status + // User management + static constexpr uint64_t SYS_SETUSER = 92; + static constexpr uint64_t SYS_GETUSER = 93; + static constexpr uint64_t SYS_FRENAME = 94; + static constexpr uint64_t SYS_GETCWD = 95; + static constexpr uint64_t SYS_CHDIR = 96; + static constexpr uint64_t SYS_DUPHANDLE = 98; + static constexpr uint64_t SYS_WAIT_HANDLE = 99; + static constexpr uint64_t SYS_STREAM_CREATE = 100; + static constexpr uint64_t SYS_STREAM_READ = 101; + static constexpr uint64_t SYS_STREAM_WRITE = 102; + static constexpr uint64_t SYS_MAILBOX_CREATE = 103; + static constexpr uint64_t SYS_MAILBOX_SEND = 104; + static constexpr uint64_t SYS_MAILBOX_RECV = 105; + static constexpr uint64_t SYS_WAITSET_CREATE = 106; + static constexpr uint64_t SYS_WAITSET_ADD = 107; + static constexpr uint64_t SYS_WAITSET_REMOVE = 108; + static constexpr uint64_t SYS_WAITSET_WAIT = 109; + static constexpr uint64_t SYS_PROC_OPEN = 110; + static constexpr uint64_t SYS_SURFACE_CREATE = 111; + static constexpr uint64_t SYS_SURFACE_MAP = 112; + static constexpr uint64_t SYS_SURFACE_RESIZE = 113; + + // Shared library syscalls + static constexpr uint64_t SYS_LOAD_LIB = 114; + static constexpr uint64_t SYS_UNLOAD_LIB = 115; + static constexpr uint64_t SYS_DLSYM = 116; + static constexpr uint64_t SYS_GETLIBBASE = 117; + + /* CrashReport */ + static constexpr uint64_t SYS_CRASH_REPORT = 118; + static constexpr uint64_t SYS_CLIPBOARD_SET_TEXT = 119; + static constexpr uint64_t SYS_CLIPBOARD_GET_INFO = 120; + static constexpr uint64_t SYS_CLIPBOARD_GET_TEXT = 121; + static constexpr uint64_t SYS_CLIPBOARD_CLEAR = 122; + static constexpr uint64_t SYS_INPUT_WAIT = 123; + static constexpr uint64_t SYS_DRIVELABEL = 124; + static constexpr uint64_t SYS_NETSTATUS = 125; + static constexpr uint64_t SYS_DRIVEKIND = 127; + + // Audio mixer enumeration + static constexpr uint64_t SYS_AUDIOLIST = 128; + // Block until the mixer state serial differs from the caller's snapshot. + static constexpr uint64_t SYS_AUDIOWAIT = 129; + + // Threading + static constexpr uint64_t SYS_THREAD_SPAWN = 130; + static constexpr uint64_t SYS_THREAD_EXIT = 131; + static constexpr uint64_t SYS_THREAD_JOIN = 132; + static constexpr uint64_t SYS_THREAD_SELF = 133; + + // Flush + unmount persistent volumes for power-off + static constexpr uint64_t SYS_FS_SYNC = 134; + + // Cross-process graceful power-off request channel + static constexpr uint64_t SYS_POWER_REQUEST = 135; + + // Paginated directory read (path, names, max, startIndex) + static constexpr uint64_t SYS_READDIR_AT = 136; + + // Graceful power-off request actions (SYS_POWER_REQUEST). The desktop posts + // a pending action and exits; login.elf reads it, runs the shutdown stages, + // then issues the matching SYS_SHUTDOWN / SYS_RESET. + enum PowerRequestAction : int { + POWER_REQ_QUERY = 0, // read-and-clear the pending action + POWER_REQ_SHUTDOWN = 1, + POWER_REQ_REBOOT = 2, + }; + + static constexpr uint32_t CLIPBOARD_MAX_TEXT_BYTES = 256 * 1024; + + static constexpr uint32_t IPC_SIGNAL_READABLE = 1u << 0; + static constexpr uint32_t IPC_SIGNAL_WRITABLE = 1u << 1; + static constexpr uint32_t IPC_SIGNAL_PEER_CLOSED = 1u << 2; + static constexpr uint32_t IPC_SIGNAL_EXITED = 1u << 3; + static constexpr uint32_t IPC_SIGNAL_READY = 1u << 4; + + // Audio control commands (for SYS_AUDIOCTL). + // + // Commands 0..3 act on the stream named by the handle argument. + // Commands 7..12 act on the global master and ignore the handle. + static constexpr int AUDIO_CTL_SET_VOLUME = 0; + static constexpr int AUDIO_CTL_GET_VOLUME = 1; + static constexpr int AUDIO_CTL_GET_POS = 2; + static constexpr int AUDIO_CTL_PAUSE = 3; + static constexpr int AUDIO_CTL_GET_OUTPUT = 4; // 0=HDA, 1=Bluetooth + static constexpr int AUDIO_CTL_SET_OUTPUT = 5; // Switch audio output + static constexpr int AUDIO_CTL_BT_STATUS = 6; // Get Bluetooth status + static constexpr int AUDIO_CTL_SET_MASTER_VOLUME = 7; // 0-100 + static constexpr int AUDIO_CTL_GET_MASTER_VOLUME = 8; + static constexpr int AUDIO_CTL_SET_MUTE = 9; // 0/1, per-stream + static constexpr int AUDIO_CTL_GET_MUTE = 10; + static constexpr int AUDIO_CTL_SET_MASTER_MUTE = 11; + static constexpr int AUDIO_CTL_GET_MASTER_MUTE = 12; static constexpr int SOCK_TCP = 1; static constexpr int SOCK_UDP = 2; @@ -176,6 +261,7 @@ namespace Montauk { char osVersion[32]; uint32_t apiVersion; uint32_t maxProcesses; + uint32_t buildNumber; // monotonic kernel build number }; struct KeyEvent { @@ -194,6 +280,31 @@ namespace Montauk { uint8_t buttons; }; + struct IpcWaitResult { + int32_t index; + uint32_t signals; + }; + + struct ClipboardInfo { + uint32_t textBytes; + uint32_t _pad; + uint64_t serial; + }; + + // One entry per active mixer stream; returned by SYS_AUDIOLIST. + struct AudioStreamInfo { + int32_t handle; + int32_t ownerPid; + char name[64]; + uint32_t sampleRate; + uint8_t channels; + uint8_t bitsPerSample; + uint8_t volume; // 0-100 + uint8_t muted; // 0/1 + uint8_t paused; // 0/1 + uint8_t _pad[7]; + }; + // Window server shared types struct WinEvent { uint8_t type; // 0=key, 1=mouse, 2=resize, 3=close, 4=scale @@ -226,7 +337,7 @@ namespace Montauk { }; struct DevInfo { - uint8_t category; // 0=CPU, 1=Interrupt, 2=Timer, 3=Input, 4=USB, 5=Network, 6=Display, 7=Storage, 8=PCI + uint8_t category; // 0=CPU, 1=Interrupt, 2=Timer, 3=Input, 4=USB, 5=Network, 6=Display, 7=Storage, 8=PCI, 9=Audio, 10=ACPI uint8_t _pad[3]; char name[48]; char detail[48]; @@ -234,7 +345,7 @@ namespace Montauk { struct DiskInfo { uint8_t port; // block device index - uint8_t type; // 0=none, 1=SATA, 2=SATAPI, 3=NVMe + uint8_t type; // 0=none, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB mass storage uint8_t sataGen; // SATA gen (1/2/3) uint8_t _pad0; uint64_t sectorCount; // Total user-addressable sectors @@ -322,6 +433,12 @@ namespace Montauk { char name[64]; }; + struct ThermalInfo { + char name[32]; // short zone name (e.g. "THRM", "TZ00") + int32_t temperature; // tenths of degrees Celsius, or -1 if unavailable + uint32_t _pad; + }; + struct ProcInfo { int32_t pid; int32_t parentPid; @@ -339,4 +456,27 @@ namespace Montauk { uint64_t pageSize; }; + // Crash report (filled by kernel on process fault, returned via SYS_CRASH_REPORT) + struct CrashReportInfo { + int pid; + char processName[64]; + uint8_t exceptionVector; + char exceptionName[32]; + uint64_t faultingAddress; + uint64_t instructionPointer; + uint64_t stackPointer; + uint64_t codeSegment; + uint64_t flags; + uint64_t stackSegment; + uint8_t pfPresent : 1; + uint8_t pfWrite : 1; + uint8_t pfUser : 1; + uint8_t pfReservedWrite : 1; + uint8_t pfInstructionFetch : 1; + uint8_t pfProtectionKey : 1; + uint8_t pfShadowStack : 1; + uint8_t pfSGX : 1; + uint64_t timestampTick; + }; + } diff --git a/template/sysroot/include/gui/canvas.hpp b/template/sysroot/include/gui/canvas.hpp index fda9d62..873eb75 100644 --- a/template/sysroot/include/gui/canvas.hpp +++ b/template/sysroot/include/gui/canvas.hpp @@ -71,6 +71,35 @@ struct Canvas { } } + void fill_rect_alpha(int x, int y, int rw, int rh, Color c) { + if (c.a == 0) return; + if (c.a == 255) { fill_rect(x, y, rw, rh, c); return; } + + int x0 = gui_max(x, 0), y0 = gui_max(y, 0); + int x1 = gui_min(x + rw, w), y1 = gui_min(y + rh, h); + if (x0 >= x1 || y0 >= y1) return; + + uint32_t a = c.a; + uint32_t inv_a = 255 - a; + uint32_t src_r = a * c.r; + uint32_t src_g = a * c.g; + uint32_t src_b = a * c.b; + + for (int dy = y0; dy < y1; dy++) { + uint32_t* row = pixels + dy * w; + for (int dx = x0; dx < x1; dx++) { + uint32_t p = row[dx]; + uint32_t dr = (p >> 16) & 0xFF; + uint32_t dg = (p >> 8) & 0xFF; + uint32_t db = p & 0xFF; + uint32_t nr = (src_r + dr * inv_a) / 255; + uint32_t ng = (src_g + dg * inv_a) / 255; + uint32_t nb = (src_b + db * inv_a) / 255; + row[dx] = (0xFFu << 24) | (nr << 16) | (ng << 8) | nb; + } + } + } + void fill_rounded_rect(int x, int y, int rw, int rh, int radius, Color c) { if (radius <= 0) { fill_rect(x, y, rw, rh, c); return; } uint32_t px = c.to_pixel(); @@ -135,51 +164,12 @@ struct Canvas { void text(int x, int y, const char* str, Color c) { if (fonts::system_font && fonts::system_font->valid) { fonts::system_font->draw_to_buffer(pixels, w, h, x, y, str, c, fonts::UI_SIZE); - return; - } - uint32_t px = c.to_pixel(); - for (int i = 0; str[i] && x + (i + 1) * FONT_WIDTH <= w; i++) { - const uint8_t* glyph = &font_data[(unsigned char)str[i] * FONT_HEIGHT]; - int cx = x + i * FONT_WIDTH; - for (int fy = 0; fy < FONT_HEIGHT && y + fy < h; fy++) { - uint8_t bits = glyph[fy]; - for (int fx = 0; fx < FONT_WIDTH; fx++) { - if (bits & (0x80 >> fx)) { - int dx = cx + fx; - int dy = y + fy; - if (dx >= 0 && dx < w && dy >= 0) - pixels[dy * w + dx] = px; - } - } - } } } void text_2x(int x, int y, const char* str, Color c) { if (fonts::system_font && fonts::system_font->valid) { fonts::system_font->draw_to_buffer(pixels, w, h, x, y, str, c, fonts::LARGE_SIZE); - return; - } - uint32_t px = c.to_pixel(); - for (int i = 0; str[i] && x + (i + 1) * FONT_WIDTH * 2 <= w; i++) { - const uint8_t* glyph = &font_data[(unsigned char)str[i] * FONT_HEIGHT]; - int cx = x + i * FONT_WIDTH * 2; - for (int fy = 0; fy < FONT_HEIGHT; fy++) { - uint8_t bits = glyph[fy]; - for (int fx = 0; fx < FONT_WIDTH; fx++) { - if (bits & (0x80 >> fx)) { - int dx = cx + fx * 2; - int dy = y + fy * 2; - for (int sy = 0; sy < 2; sy++) - for (int sx = 0; sx < 2; sx++) { - int pdx = dx + sx; - int pdy = dy + sy; - if (pdx >= 0 && pdx < w && pdy >= 0 && pdy < h) - pixels[pdy * w + pdx] = px; - } - } - } - } } } diff --git a/template/sysroot/include/gui/clipboard.hpp b/template/sysroot/include/gui/clipboard.hpp new file mode 100644 index 0000000..c5ab6e2 --- /dev/null +++ b/template/sysroot/include/gui/clipboard.hpp @@ -0,0 +1,65 @@ +/* + * clipboard.hpp + * Simple plain-text clipboard helpers for MontaukOS GUI apps + * Copyright (c) 2026 Daniel Hammer + */ + +#pragma once + +#include +#include +#include + +namespace gui { + + inline bool clipboard_set_text(const char* text, int len) { + if (len < 0) return false; + if (len > 0 && text == nullptr) return false; + return montauk::clipboard_set_text(text, (uint32_t)len) == 0; + } + + inline bool clipboard_set_text(const char* text) { + return clipboard_set_text(text, text ? montauk::slen(text) : 0); + } + + inline bool clipboard_get_info(Montauk::ClipboardInfo* out) { + if (out == nullptr) return false; + return montauk::clipboard_get_info(out) == 0; + } + + inline bool clipboard_has_text() { + Montauk::ClipboardInfo info = {}; + return clipboard_get_info(&info) && info.textBytes > 0; + } + + inline char* clipboard_get_text_alloc(int* out_len = nullptr, uint64_t* out_serial = nullptr) { + if (out_len) *out_len = 0; + if (out_serial) *out_serial = 0; + + Montauk::ClipboardInfo info = {}; + if (!clipboard_get_info(&info) || info.textBytes == 0) + return nullptr; + + uint32_t cap = info.textBytes + 1; + char* text = (char*)montauk::malloc(cap); + if (text == nullptr) return nullptr; + + uint32_t actual_len = 0; + uint64_t serial = 0; + if (montauk::clipboard_get_text(text, info.textBytes, &actual_len, &serial) != 0 || + actual_len > info.textBytes) { + montauk::mfree(text); + return nullptr; + } + + text[actual_len] = '\0'; + if (out_len) *out_len = (int)actual_len; + if (out_serial) *out_serial = serial; + return text; + } + + inline bool clipboard_clear() { + return montauk::clipboard_clear() == 0; + } + +} diff --git a/template/sysroot/include/gui/desktop.hpp b/template/sysroot/include/gui/desktop.hpp index df67fda..7bf6073 100644 --- a/template/sysroot/include/gui/desktop.hpp +++ b/template/sysroot/include/gui/desktop.hpp @@ -18,17 +18,37 @@ namespace gui { static constexpr int MAX_WINDOWS = 8; static constexpr int PANEL_HEIGHT = 32; static constexpr int MAX_EXTERNAL_APPS = 32; +static constexpr int MAX_LAUNCHER_ITEMS = 64; // External app discovered from 0:/apps/ manifest struct ExternalApp { char name[48]; char binary_path[128]; + char icon_path[128]; char category[24]; SvgIcon icon; bool menu_visible; bool launch_with_home; }; +enum LauncherItemKind : uint8_t { + LAUNCHER_ITEM_EXTERNAL_APP = 0, + LAUNCHER_ITEM_BUILTIN_FILES, + LAUNCHER_ITEM_COMMAND_REBOOT, + LAUNCHER_ITEM_COMMAND_SHUTDOWN, + LAUNCHER_ITEM_SPECIAL_FOLDER, +}; + +struct LauncherItem { + char name[64]; + char category[48]; + char path[128]; + char search_text[192]; + SvgIcon* icon; + LauncherItemKind kind; + int ref_index; +}; + struct DesktopSettings { // Background bool bg_gradient; // true = gradient, false = solid @@ -72,6 +92,17 @@ struct DesktopState { uint8_t prev_buttons; bool app_menu_open; + bool launcher_open; + char launcher_query[64]; + int launcher_query_len; + LauncherItem launcher_items[MAX_LAUNCHER_ITEMS]; + int launcher_item_count; + int launcher_results[MAX_LAUNCHER_ITEMS]; + int launcher_result_count; + int launcher_selected; + int launcher_scroll; + bool super_left_down; + bool super_right_down; SvgIcon icon_terminal; SvgIcon icon_filemanager; @@ -80,11 +111,11 @@ struct DesktopState { SvgIcon icon_folder; SvgIcon icon_file; SvgIcon icon_network; - SvgIcon icon_calculator; SvgIcon icon_go_up; SvgIcon icon_go_back; SvgIcon icon_go_forward; SvgIcon icon_home; + SvgIcon icon_refresh; SvgIcon icon_exec; SvgIcon icon_folder_lg; @@ -92,7 +123,26 @@ struct DesktopState { SvgIcon icon_exec_lg; SvgIcon icon_drive; SvgIcon icon_drive_lg; + SvgIcon icon_drive_usb; + SvgIcon icon_drive_usb_lg; SvgIcon icon_delete; + SvgIcon icon_copy; + SvgIcon icon_cut; + SvgIcon icon_paste; + SvgIcon icon_rename; + SvgIcon icon_folder_new; + SvgIcon icon_home_folder; + SvgIcon icon_home_folder_lg; + SvgIcon icon_apps; + SvgIcon icon_apps_lg; + SvgIcon icon_system_configuration_menu; + SvgIcon icon_system_configuration; + SvgIcon icon_system_configuration_lg; + + // Special user folder icons (16x16 and 48x48) + static constexpr int SPECIAL_FOLDER_COUNT = 6; + SvgIcon icon_special_folder[SPECIAL_FOLDER_COUNT]; + SvgIcon icon_special_folder_lg[SPECIAL_FOLDER_COUNT]; SvgIcon icon_settings; SvgIcon icon_reboot; @@ -121,8 +171,19 @@ struct DesktopState { int vol_pre_mute; // volume before mute bool vol_dragging; // slider drag in progress uint64_t vol_last_poll; + uint64_t vol_serial; // last seen mixer state serial + + // Temperature monitoring + static constexpr int MAX_THERMAL_ZONES = 8; + Montauk::ThermalInfo thermal_zones[MAX_THERMAL_ZONES]; + int thermal_zone_count; + uint64_t thermal_last_poll; + Rect temp_icon_rect; int screen_w, screen_h; + uint32_t* background_cache; + int background_cache_pitch; + bool background_cache_dirty; // IDs of external windows we've sent a close event to but that haven't // been destroyed yet by their owning process. Prevents the poll loop diff --git a/template/sysroot/include/gui/dialogs.hpp b/template/sysroot/include/gui/dialogs.hpp new file mode 100644 index 0000000..edcaa4f --- /dev/null +++ b/template/sysroot/include/gui/dialogs.hpp @@ -0,0 +1,248 @@ +/* + * dialogs.hpp + * Shared dialog request/result structures and client helpers + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include +#include + +#ifndef GUI_DIALOGS_LIBRARY_BUILD +#include +#endif + +namespace gui::dialogs { + +inline constexpr const char* LIBRARY_PATH = "0:/os/libdialogs.lib"; +inline constexpr const char* RUN_REQUEST_SYMBOL = "dialogs_run_request"; +inline constexpr const char* MESSAGE_BOX_SYMBOL = "dialogs_message_box"; + +enum RequestKind : uint8_t { + REQUEST_KIND_FILE = 1, + REQUEST_KIND_PRINT = 2, +}; + +enum FileDialogMode : uint8_t { + FILE_DIALOG_OPEN = 1, + FILE_DIALOG_SAVE = 2, +}; + +enum PrintDialogMode : uint8_t { + PRINT_DIALOG_SETUP = 1, + PRINT_DIALOG_SUBMIT = 2, +}; + +enum MessageBoxButtons : uint8_t { + MESSAGE_BOX_OK = 1, + MESSAGE_BOX_OK_CANCEL = 2, + MESSAGE_BOX_YES_NO = 3, + MESSAGE_BOX_YES_NO_CANCEL = 4, +}; + +enum MessageBoxResult : uint8_t { + MESSAGE_BOX_RESULT_NONE = 0, + MESSAGE_BOX_RESULT_OK = 1, + MESSAGE_BOX_RESULT_CANCEL = 2, + MESSAGE_BOX_RESULT_YES = 3, + MESSAGE_BOX_RESULT_NO = 4, +}; + +struct Request { + uint8_t kind; + uint8_t mode; + char title[96]; + char initial_path[256]; + char suggested_name[128]; + char source_path[256]; + char job_name[128]; + char printer_uri[256]; + uint32_t copies; +}; + +struct Result { + char status[16]; + char path[256]; + char job_id[64]; + char printer_uri[256]; + char printer_name[128]; + uint32_t copies; + char message[160]; +}; + +inline void safe_copy(char* dst, int dst_len, const char* src) { + if (!dst || dst_len <= 0) return; + if (!src) src = ""; + montauk::strncpy(dst, src, dst_len - 1); + dst[dst_len - 1] = '\0'; +} + +inline void reset_request(Request* req) { + if (!req) return; + montauk::memset(req, 0, sizeof(Request)); +} + +inline void reset_result(Result* res) { + if (!res) return; + montauk::memset(res, 0, sizeof(Result)); +} + +#ifndef GUI_DIALOGS_LIBRARY_BUILD + +using RunRequestFn = bool (*)(const Request*, Result*); +using MessageBoxFn = uint8_t (*)(const char*, const char*, uint8_t); + +struct Runtime { + LibHandle* handle; + RunRequestFn run_request; + MessageBoxFn message_box; +}; + +inline Runtime g_runtime = {}; + +inline bool ensure_handle(char* out_message, int out_message_len) { + if (g_runtime.handle) return true; + g_runtime.handle = libloader::dlopen(LIBRARY_PATH); + if (!g_runtime.handle) { + if (out_message && out_message_len > 0) + safe_copy(out_message, out_message_len, "failed to load dialog library"); + return false; + } + return true; +} + +inline RunRequestFn resolve_run_request(char* out_message, int out_message_len) { + if (g_runtime.run_request) return g_runtime.run_request; + if (!ensure_handle(out_message, out_message_len)) return nullptr; + g_runtime.run_request = (RunRequestFn)libloader::dlsym(g_runtime.handle, RUN_REQUEST_SYMBOL); + if (!g_runtime.run_request && out_message && out_message_len > 0) + safe_copy(out_message, out_message_len, "failed to resolve dialog entry point"); + return g_runtime.run_request; +} + +inline MessageBoxFn resolve_message_box(char* out_message, int out_message_len) { + if (g_runtime.message_box) return g_runtime.message_box; + if (!ensure_handle(out_message, out_message_len)) return nullptr; + g_runtime.message_box = (MessageBoxFn)libloader::dlsym(g_runtime.handle, MESSAGE_BOX_SYMBOL); + if (!g_runtime.message_box && out_message && out_message_len > 0) + safe_copy(out_message, out_message_len, "failed to resolve message box entry point"); + return g_runtime.message_box; +} + +inline bool run_request(const Request* req, Result& res, char* out_message, int out_message_len) { + if (out_message && out_message_len > 0) out_message[0] = '\0'; + if (!req) { + if (out_message && out_message_len > 0) + safe_copy(out_message, out_message_len, "invalid dialog request"); + return false; + } + + RunRequestFn run_fn = resolve_run_request(out_message, out_message_len); + if (!run_fn) return false; + if (!run_fn(req, &res)) { + if (out_message && out_message_len > 0 && !out_message[0]) + safe_copy(out_message, out_message_len, "dialog library invocation failed"); + return false; + } + + if (out_message && out_message_len > 0) + safe_copy(out_message, out_message_len, res.message); + return montauk::streq(res.status, "ok"); +} + +inline bool open_file(const char* title, + const char* initial_path, + char* out_path, int out_path_len, + char* out_message = nullptr, int out_message_len = 0) { + Request req = {}; + req.kind = REQUEST_KIND_FILE; + req.mode = FILE_DIALOG_OPEN; + safe_copy(req.title, sizeof(req.title), title ? title : "Open"); + safe_copy(req.initial_path, sizeof(req.initial_path), initial_path); + + Result res = {}; + bool ok = run_request(&req, res, out_message, out_message_len); + if (ok && out_path && out_path_len > 0) safe_copy(out_path, out_path_len, res.path); + return ok; +} + +inline bool save_file(const char* title, + const char* initial_path, + const char* suggested_name, + char* out_path, int out_path_len, + char* out_message = nullptr, int out_message_len = 0) { + Request req = {}; + req.kind = REQUEST_KIND_FILE; + req.mode = FILE_DIALOG_SAVE; + safe_copy(req.title, sizeof(req.title), title ? title : "Save"); + safe_copy(req.initial_path, sizeof(req.initial_path), initial_path); + safe_copy(req.suggested_name, sizeof(req.suggested_name), suggested_name); + + Result res = {}; + bool ok = run_request(&req, res, out_message, out_message_len); + if (ok && out_path && out_path_len > 0) safe_copy(out_path, out_path_len, res.path); + return ok; +} + +inline bool print_file(const char* title, + const char* source_path, + const char* job_name, + char* out_job_id, int out_job_id_len, + char* out_message = nullptr, int out_message_len = 0) { + Request req = {}; + req.kind = REQUEST_KIND_PRINT; + req.mode = PRINT_DIALOG_SUBMIT; + req.copies = 1; + safe_copy(req.title, sizeof(req.title), title ? title : "Print"); + safe_copy(req.source_path, sizeof(req.source_path), source_path); + safe_copy(req.job_name, sizeof(req.job_name), job_name); + + Result res = {}; + bool ok = run_request(&req, res, out_message, out_message_len); + if (ok && out_job_id && out_job_id_len > 0) safe_copy(out_job_id, out_job_id_len, res.job_id); + return ok; +} + +inline bool configure_print(const char* title, + const char* initial_printer_uri, + const char* job_name, + char* out_printer_uri, int out_printer_uri_len, + char* out_printer_name, int out_printer_name_len, + uint32_t* out_copies = nullptr, + char* out_message = nullptr, int out_message_len = 0) { + Request req = {}; + req.kind = REQUEST_KIND_PRINT; + req.mode = PRINT_DIALOG_SETUP; + req.copies = out_copies && *out_copies > 0 ? *out_copies : 1; + safe_copy(req.title, sizeof(req.title), title ? title : "Print"); + safe_copy(req.job_name, sizeof(req.job_name), job_name ? job_name : ""); + safe_copy(req.printer_uri, sizeof(req.printer_uri), initial_printer_uri); + + Result res = {}; + bool ok = run_request(&req, res, out_message, out_message_len); + if (ok && out_printer_uri && out_printer_uri_len > 0) safe_copy(out_printer_uri, out_printer_uri_len, res.printer_uri); + if (ok && out_printer_name && out_printer_name_len > 0) safe_copy(out_printer_name, out_printer_name_len, res.printer_name); + if (ok && out_copies) *out_copies = res.copies > 0 ? res.copies : 1; + return ok; +} + +inline MessageBoxResult message_box(const char* title, + const char* message, + MessageBoxButtons buttons = MESSAGE_BOX_OK, + char* out_message = nullptr, int out_message_len = 0) { + if (out_message && out_message_len > 0) out_message[0] = '\0'; + MessageBoxFn fn = resolve_message_box(out_message, out_message_len); + if (!fn) return MESSAGE_BOX_RESULT_NONE; + + uint8_t result = fn(title ? title : "Message", + message ? message : "", + (uint8_t)buttons); + if (result == MESSAGE_BOX_RESULT_NONE && out_message && out_message_len > 0 && !out_message[0]) + safe_copy(out_message, out_message_len, "message box invocation failed"); + return (MessageBoxResult)result; +} + +#endif + +} // namespace gui::dialogs diff --git a/template/sysroot/include/gui/draw.hpp b/template/sysroot/include/gui/draw.hpp index ab77a9c..a2875c8 100644 --- a/template/sysroot/include/gui/draw.hpp +++ b/template/sysroot/include/gui/draw.hpp @@ -12,16 +12,17 @@ namespace gui { // Fast horizontal line inline void draw_hline(Framebuffer& fb, int x, int y, int w, Color c) { - for (int i = 0; i < w; i++) fb.put_pixel(x + i, y, c); + fb.fill_rect(x, y, w, 1, c); } // Fast vertical line inline void draw_vline(Framebuffer& fb, int x, int y, int h, Color c) { - for (int i = 0; i < h; i++) fb.put_pixel(x, y + i, c); + fb.fill_rect(x, y, 1, h, c); } // Rectangle outline inline void draw_rect(Framebuffer& fb, int x, int y, int w, int h, Color c) { + if (w <= 0 || h <= 0) return; draw_hline(fb, x, y, w, c); draw_hline(fb, x, y + h - 1, w, c); draw_vline(fb, x, y, h, c); diff --git a/template/sysroot/include/gui/framebuffer.hpp b/template/sysroot/include/gui/framebuffer.hpp index 257bf3d..65bfb2b 100644 --- a/template/sysroot/include/gui/framebuffer.hpp +++ b/template/sysroot/include/gui/framebuffer.hpp @@ -19,6 +19,46 @@ class Framebuffer { int fb_height; int fb_pitch; // in bytes + static inline void fill_pixels(uint32_t* dst, int count, uint32_t pixel) { + if (!dst || count <= 0) return; + + uint64_t pixel64 = ((uint64_t)pixel << 32) | pixel; + if (((uint64_t)dst & 4) && count > 0) { + *dst++ = pixel; + count--; + } + + uint64_t* dst64 = (uint64_t*)dst; + int pairs = count / 2; + for (int i = 0; i < pairs; i++) { + dst64[i] = pixel64; + } + + if (count & 1) { + ((uint32_t*)(dst64 + pairs))[0] = pixel; + } + } + + static inline uint32_t blend_pixel(uint32_t dst, uint32_t src, uint32_t alpha) { + uint32_t inv_a = 255 - alpha; + uint32_t sr = (src >> 16) & 0xFF; + uint32_t sg = (src >> 8) & 0xFF; + uint32_t sb = src & 0xFF; + uint32_t dr = (dst >> 16) & 0xFF; + uint32_t dg = (dst >> 8) & 0xFF; + uint32_t db = dst & 0xFF; + + uint32_t rr = alpha * sr + inv_a * dr; + uint32_t gg = alpha * sg + inv_a * dg; + uint32_t bb = alpha * sb + inv_a * db; + + rr = (rr + 1 + (rr >> 8)) >> 8; + gg = (gg + 1 + (gg >> 8)) >> 8; + bb = (bb + 1 + (bb >> 8)) >> 8; + + return 0xFF000000 | (rr << 16) | (gg << 8) | bb; + } + public: Framebuffer() : hw_fb(nullptr), back_buf(nullptr), fb_width(0), fb_height(0), fb_pitch(0) { Montauk::FbInfo info; @@ -76,6 +116,8 @@ public: } inline void fill_rect(int x, int y, int w, int h, Color c) { + if (!back_buf) return; + // Clip to screen bounds int x0 = x < 0 ? 0 : x; int y0 = y < 0 ? 0 : y; @@ -89,9 +131,7 @@ public: for (int row = y0; row < y1; row++) { uint32_t* dst = (uint32_t*)((uint8_t*)back_buf + row * fb_pitch) + x0; - for (int col = 0; col < clipped_w; col++) { - dst[col] = pixel; - } + fill_pixels(dst, clipped_w, pixel); } } @@ -137,56 +177,84 @@ public: } inline void blit(int x, int y, int w, int h, const uint32_t* pixels) { - for (int row = 0; row < h; row++) { - int dy = y + row; - if (dy < 0 || dy >= fb_height) continue; - for (int col = 0; col < w; col++) { - int dx = x + col; - if (dx < 0 || dx >= fb_width) continue; - uint32_t* dst_row = (uint32_t*)((uint8_t*)back_buf + dy * fb_pitch); - dst_row[dx] = pixels[row * w + col]; - } + if (!back_buf || !pixels || w <= 0 || h <= 0) return; + + int src_x = 0; + int src_y = 0; + int dst_x = x; + int dst_y = y; + int copy_w = w; + int copy_h = h; + + if (dst_x < 0) { src_x = -dst_x; copy_w += dst_x; dst_x = 0; } + if (dst_y < 0) { src_y = -dst_y; copy_h += dst_y; dst_y = 0; } + if (dst_x + copy_w > fb_width) copy_w = fb_width - dst_x; + if (dst_y + copy_h > fb_height) copy_h = fb_height - dst_y; + if (copy_w <= 0 || copy_h <= 0) return; + + uint64_t row_bytes = (uint64_t)copy_w * sizeof(uint32_t); + for (int row = 0; row < copy_h; row++) { + uint32_t* dst = (uint32_t*)((uint8_t*)back_buf + (dst_y + row) * fb_pitch) + dst_x; + const uint32_t* src = pixels + (src_y + row) * w + src_x; + montauk::memcpy(dst, src, row_bytes); } } inline void blit_alpha(int x, int y, int w, int h, const uint32_t* pixels) { - for (int row = 0; row < h; row++) { - int dy = y + row; - if (dy < 0 || dy >= fb_height) continue; - for (int col = 0; col < w; col++) { - int dx = x + col; - if (dx < 0 || dx >= fb_width) continue; + if (!back_buf || !pixels || w <= 0 || h <= 0) return; - uint32_t src = pixels[row * w + col]; - uint8_t sa = (src >> 24) & 0xFF; + int src_x = 0; + int src_y = 0; + int dst_x = x; + int dst_y = y; + int copy_w = w; + int copy_h = h; + + if (dst_x < 0) { src_x = -dst_x; copy_w += dst_x; dst_x = 0; } + if (dst_y < 0) { src_y = -dst_y; copy_h += dst_y; dst_y = 0; } + if (dst_x + copy_w > fb_width) copy_w = fb_width - dst_x; + if (dst_y + copy_h > fb_height) copy_h = fb_height - dst_y; + if (copy_w <= 0 || copy_h <= 0) return; + + for (int row = 0; row < copy_h; row++) { + uint32_t* dst = (uint32_t*)((uint8_t*)back_buf + (dst_y + row) * fb_pitch) + dst_x; + const uint32_t* src = pixels + (src_y + row) * w + src_x; + for (int col = 0; col < copy_w; col++) { + uint32_t s = src[col]; + uint8_t sa = (s >> 24) & 0xFF; if (sa == 0) continue; - - uint8_t sr = (src >> 16) & 0xFF; - uint8_t sg = (src >> 8) & 0xFF; - uint8_t sb = src & 0xFF; - if (sa == 255) { - uint32_t* dst_row = (uint32_t*)((uint8_t*)back_buf + dy * fb_pitch); - dst_row[dx] = src; + dst[col] = s; continue; } - Color sc = {sr, sg, sb, sa}; - put_pixel_alpha(dx, dy, sc); + dst[col] = blend_pixel(dst[col], s, sa); } } } + inline void copy_from(const uint32_t* pixels, int src_pitch_bytes) { + if (!back_buf || !pixels || src_pitch_bytes <= 0) return; + uint64_t row_bytes = (uint64_t)fb_width * sizeof(uint32_t); + for (int row = 0; row < fb_height; row++) { + uint32_t* dst = (uint32_t*)((uint8_t*)back_buf + row * fb_pitch); + const uint32_t* src = (const uint32_t*)((const uint8_t*)pixels + row * src_pitch_bytes); + montauk::memcpy(dst, src, row_bytes); + } + } + inline void clear(Color c) { fill_rect(0, 0, fb_width, fb_height, c); } inline void flip() { + if (!hw_fb || !back_buf) return; + // Copy back buffer to hardware framebuffer, row by row (pitch may differ) uint64_t row_bytes = (uint64_t)fb_width * sizeof(uint32_t); for (int y = 0; y < fb_height; y++) { - void* src = (void*)((uint8_t*)back_buf + y * fb_pitch); - void* dst = (void*)((uint8_t*)hw_fb + y * fb_pitch); + uint32_t* src = (uint32_t*)((uint8_t*)back_buf + y * fb_pitch); + uint32_t* dst = (uint32_t*)((uint8_t*)hw_fb + y * fb_pitch); montauk::memcpy(dst, src, row_bytes); } } diff --git a/template/sysroot/include/gui/mtk.hpp b/template/sysroot/include/gui/mtk.hpp new file mode 100644 index 0000000..dabfbfd --- /dev/null +++ b/template/sysroot/include/gui/mtk.hpp @@ -0,0 +1,13 @@ +/* + * mtk.hpp + * Umbrella include for the Montauk Toolkit + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include "gui/mtk/theme.hpp" +#include "gui/mtk/widgets.hpp" +#include "gui/mtk/graph.hpp" +#include "gui/mtk/table.hpp" +#include "gui/mtk/hosts.hpp" diff --git a/template/sysroot/include/gui/mtk/graph.hpp b/template/sysroot/include/gui/mtk/graph.hpp new file mode 100644 index 0000000..d503820 --- /dev/null +++ b/template/sysroot/include/gui/mtk/graph.hpp @@ -0,0 +1,290 @@ +/* + * graph.hpp + * Montauk Toolkit graph helpers + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include "gui/mtk/widgets.hpp" + +namespace gui::mtk { + +struct GraphHistory { + uint64_t* samples; + int capacity; + int count; + int head; +}; + +struct GraphStyle { + Color background; + Color border; + Color plot_bg; + Color grid; + Color label; + Color value; + Color line; + Color fill; + int radius; + int padding; + int grid_x; + int grid_y; + int line_thickness; + bool fill_area; +}; + +inline GraphStyle make_graph_style(const Theme& theme, Color line) { + return { + theme.window_bg, + theme.border, + theme.surface_alt, + mix(theme.surface_alt, line, 18), + theme.text_subtle, + theme.text, + line, + lighten(line, 218), + theme.radius_md, + 8, + 4, + 4, + 2, + true, + }; +} + +inline void graph_history_init(GraphHistory* history, uint64_t* samples, int capacity) { + if (!history) return; + history->samples = samples; + history->capacity = capacity; + history->count = 0; + history->head = 0; +} + +inline void graph_history_clear(GraphHistory* history) { + if (!history) return; + history->count = 0; + history->head = 0; +} + +inline void graph_history_push(GraphHistory* history, uint64_t value) { + if (!history || !history->samples || history->capacity <= 0) return; + history->samples[history->head] = value; + history->head = (history->head + 1) % history->capacity; + if (history->count < history->capacity) + history->count++; +} + +inline uint64_t graph_history_at(const GraphHistory& history, int index) { + if (!history.samples || history.capacity <= 0 || + index < 0 || index >= history.count) { + return 0; + } + + int start = history.head - history.count; + while (start < 0) start += history.capacity; + return history.samples[(start + index) % history.capacity]; +} + +inline uint64_t graph_history_max(const GraphHistory& history) { + uint64_t max_value = 0; + for (int i = 0; i < history.count; i++) { + uint64_t value = graph_history_at(history, i); + if (value > max_value) max_value = value; + } + return max_value; +} + +inline int graph_sample_x(const Rect& plot, int index, int count) { + if (count <= 1) return plot.x + plot.w - 1; + return plot.x + (int)(((int64_t)index * (plot.w - 1)) / (count - 1)); +} + +inline int graph_sample_y(const Rect& plot, uint64_t sample, uint64_t max_value) { + if (plot.h <= 1) return plot.y; + if (max_value == 0) max_value = 1; + if (sample > max_value) sample = max_value; + uint64_t scaled = (sample * (uint64_t)(plot.h - 1)) / max_value; + return plot.y + plot.h - 1 - (int)scaled; +} + +inline void graph_draw_point(Canvas& c, + const Rect& clip, + int x, + int y, + Color color, + int thickness) { + thickness = gui_max(thickness, 1); + int radius = thickness / 2; + for (int py = y - radius; py <= y - radius + thickness - 1; py++) { + for (int px = x - radius; px <= x - radius + thickness - 1; px++) { + if (clip.contains(px, py)) + c.put_pixel(px, py, color); + } + } +} + +inline void graph_draw_line(Canvas& c, + const Rect& clip, + int x0, + int y0, + int x1, + int y1, + Color color, + int thickness) { + int dx = gui_abs(x1 - x0); + int sx = x0 < x1 ? 1 : -1; + int dy = -gui_abs(y1 - y0); + int sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + + for (;;) { + graph_draw_point(c, clip, x0, y0, color, thickness); + if (x0 == x1 && y0 == y1) break; + int e2 = 2 * err; + if (e2 >= dy) { + err += dy; + x0 += sx; + } + if (e2 <= dx) { + err += dx; + y0 += sy; + } + } +} + +inline void graph_fill_segment(Canvas& c, + const Rect& clip, + int x0, + int y0, + int x1, + int y1, + Color color) { + int bottom = clip.y + clip.h - 1; + if (x0 == x1) { + int y = gui_min(y0, y1); + if (clip.contains(x0, y)) + c.vline(x0, y, bottom - y + 1, color); + return; + } + + if (x1 < x0) { + int tx = x0; x0 = x1; x1 = tx; + int ty = y0; y0 = y1; y1 = ty; + } + + for (int x = x0; x <= x1; x++) { + if (x < clip.x || x >= clip.x + clip.w) continue; + int y = y0 + (int)(((int64_t)(y1 - y0) * (x - x0)) / (x1 - x0)); + if (y < clip.y) y = clip.y; + if (y > bottom) y = bottom; + c.vline(x, y, bottom - y + 1, color); + } +} + +inline void draw_line_graph(Canvas& c, + const Rect& bounds, + const GraphHistory& history, + uint64_t max_value, + const char* title, + const char* value_label, + const Theme& theme, + const GraphStyle& style) { + if (bounds.empty()) return; + + draw_rounded_frame(c, bounds, style.radius, style.background, style.border); + + int fh = system_font_height(); + int pad = gui_max(style.padding, 4); + int title_y = bounds.y + pad; + int title_x = bounds.x + pad; + + if (title && title[0]) + c.text(title_x, title_y, title, style.label); + + if (value_label && value_label[0]) { + int value_w = text_width(value_label); + int value_x = bounds.x + bounds.w - pad - value_w; + if (value_x > title_x) + c.text(value_x, title_y, value_label, style.value); + } + + Rect plot = { + bounds.x + pad, + bounds.y + pad + fh + 7, + bounds.w - pad * 2, + bounds.h - pad * 2 - fh - 7 + }; + if (plot.empty()) return; + + c.fill_rect(plot.x, plot.y, plot.w, plot.h, style.plot_bg); + + int sample_count = history.count; + if (sample_count > 0) { + if (max_value == 0) + max_value = graph_history_max(history); + if (max_value == 0) + max_value = 1; + + if (style.fill_area && sample_count > 1) { + int prev_x = graph_sample_x(plot, 0, sample_count); + int prev_y = graph_sample_y(plot, graph_history_at(history, 0), max_value); + for (int i = 1; i < sample_count; i++) { + int x = graph_sample_x(plot, i, sample_count); + int y = graph_sample_y(plot, graph_history_at(history, i), max_value); + graph_fill_segment(c, plot, prev_x, prev_y, x, y, style.fill); + prev_x = x; + prev_y = y; + } + } + } + + if (style.grid_y > 0) { + for (int i = 1; i < style.grid_y; i++) { + int y = plot.y + (plot.h * i) / style.grid_y; + c.hline(plot.x, y, plot.w, style.grid); + } + } + + if (style.grid_x > 0) { + for (int i = 1; i < style.grid_x; i++) { + int x = plot.x + (plot.w * i) / style.grid_x; + c.vline(x, plot.y, plot.h, style.grid); + } + } + + c.rect(plot.x, plot.y, plot.w, plot.h, style.border); + + if (sample_count == 1) { + int x = graph_sample_x(plot, 0, sample_count); + int y = graph_sample_y(plot, graph_history_at(history, 0), max_value); + graph_draw_point(c, plot, x, y, style.line, style.line_thickness + 1); + } else if (sample_count > 1) { + int prev_x = graph_sample_x(plot, 0, sample_count); + int prev_y = graph_sample_y(plot, graph_history_at(history, 0), max_value); + for (int i = 1; i < sample_count; i++) { + int x = graph_sample_x(plot, i, sample_count); + int y = graph_sample_y(plot, graph_history_at(history, i), max_value); + graph_draw_line(c, plot, prev_x, prev_y, x, y, + style.line, style.line_thickness); + prev_x = x; + prev_y = y; + } + } + + (void)theme; +} + +inline void draw_line_graph(Canvas& c, + const Rect& bounds, + const GraphHistory& history, + uint64_t max_value, + const char* title, + const char* value_label, + const Theme& theme, + Color line) { + GraphStyle style = make_graph_style(theme, line); + draw_line_graph(c, bounds, history, max_value, title, value_label, theme, style); +} + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/mtk/hosts.hpp b/template/sysroot/include/gui/mtk/hosts.hpp new file mode 100644 index 0000000..d0dcc32 --- /dev/null +++ b/template/sysroot/include/gui/mtk/hosts.hpp @@ -0,0 +1,63 @@ +/* + * hosts.hpp + * Montauk Toolkit host adapters for desktop and standalone apps + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include "gui/canvas.hpp" +#include "gui/standalone.hpp" +#include "gui/window.hpp" + +namespace gui::mtk { + +struct DesktopHost { + Window* window; + + explicit DesktopHost(Window* win) : window(win) {} + + Canvas canvas() const { + return window ? Canvas(window) : Canvas(nullptr, 0, 0); + } + + Rect bounds() const { + return {0, 0, window ? window->content_w : 0, window ? window->content_h : 0}; + } + + bool map_mouse(const MouseEvent& ev, int* out_x, int* out_y) const { + if (!window || !out_x || !out_y) return false; + Rect cr = window->content_rect(); + *out_x = ev.x - cr.x; + *out_y = ev.y - cr.y; + return true; + } + + void invalidate() const { + if (window) window->dirty = true; + } +}; + +struct StandaloneHost { + WsWindow* window; + + explicit StandaloneHost(WsWindow* win) : window(win) {} + + Canvas canvas() const { + return window ? window->canvas() : Canvas(nullptr, 0, 0); + } + + Rect bounds() const { + return {0, 0, window ? window->width : 0, window ? window->height : 0}; + } + + void present() const { + if (window) window->present(); + } + + void set_cursor(int cursor) const { + if (window) window->set_cursor(cursor); + } +}; + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/mtk/settings.hpp b/template/sysroot/include/gui/mtk/settings.hpp new file mode 100644 index 0000000..bc11cb8 --- /dev/null +++ b/template/sysroot/include/gui/mtk/settings.hpp @@ -0,0 +1,43 @@ +/* + * settings.hpp + * Montauk Toolkit helpers for loading desktop appearance settings + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include +#include +#include +#include "gui/gui.hpp" + +namespace gui::mtk { + +inline Color color_from_rgb_int(int64_t rgb, Color fallback = colors::ACCENT) { + if (rgb < 0) return fallback; + return Color::from_rgb((uint8_t)((rgb >> 16) & 0xFF), + (uint8_t)((rgb >> 8) & 0xFF), + (uint8_t)(rgb & 0xFF)); +} + +inline Color load_system_accent(Color fallback = colors::ACCENT) { + char user[64] = {}; + if (montauk::getuser(user, sizeof(user)) > 0 && user[0]) { + auto doc = montauk::config::load_user(user, "desktop"); + int64_t accent = doc.get_int("appearance.accent_color", -1); + if (accent >= 0) { + Color color = color_from_rgb_int(accent, fallback); + doc.destroy(); + return color; + } + doc.destroy(); + } + + auto doc = montauk::config::load("desktop"); + int64_t accent = doc.get_int("appearance.accent_color", -1); + Color color = color_from_rgb_int(accent, fallback); + doc.destroy(); + return color; +} + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/mtk/table.hpp b/template/sysroot/include/gui/mtk/table.hpp new file mode 100644 index 0000000..f240f3c --- /dev/null +++ b/template/sysroot/include/gui/mtk/table.hpp @@ -0,0 +1,150 @@ +/* + * table.hpp + * Montauk Toolkit table/list helpers + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include "gui/canvas.hpp" +#include "gui/mtk/theme.hpp" + +namespace gui::mtk { + +struct TableColumn { + const char* label; + int x; + int w; +}; + +struct TableLayout { + Rect header; + Rect body; + int row_h; +}; + +struct TableStyle { + Color header_bg; + Color header_border; + Color header_text; + Color row_selected_bg; + Color row_hover_bg; +}; + +inline TableStyle make_table_style(const Theme& theme) { + return { + theme.surface_alt, + theme.border, + theme.text_subtle, + theme.accent_soft, + colors::TRANSPARENT, + }; +} + +inline int table_visible_rows(const TableLayout& layout) { + if (layout.row_h <= 0 || layout.body.h <= 0) return 0; + return layout.body.h / layout.row_h; +} + +inline int table_max_scroll(const TableLayout& layout, int row_count) { + int visible = table_visible_rows(layout); + if (row_count > visible && visible > 0) return row_count - visible; + return 0; +} + +inline void clamp_table_scroll(int* scroll, const TableLayout& layout, int row_count) { + if (!scroll) return; + *scroll = gui_clamp(*scroll, 0, table_max_scroll(layout, row_count)); +} + +inline void ensure_table_row_visible(int* scroll, + const TableLayout& layout, + int row_count, + int selected) { + if (!scroll || selected < 0) return; + int visible = table_visible_rows(layout); + if (visible <= 0) return; + if (selected < *scroll) { + *scroll = selected; + } else if (selected >= *scroll + visible) { + *scroll = selected - visible + 1; + } + clamp_table_scroll(scroll, layout, row_count); +} + +inline Rect table_row_rect(const TableLayout& layout, int scroll, int row_index) { + return { + layout.body.x, + layout.body.y + (row_index - scroll) * layout.row_h, + layout.body.w, + layout.row_h + }; +} + +inline Rect table_cell_rect(const Rect& row_rect, const TableColumn& col) { + return {row_rect.x + col.x, row_rect.y, col.w, row_rect.h}; +} + +inline int table_hit_row(const TableLayout& layout, + int scroll, + int row_count, + int mx, + int my) { + if (!layout.body.contains(mx, my) || layout.row_h <= 0) return -1; + int row = (my - layout.body.y) / layout.row_h; + int index = scroll + row; + if (index < 0 || index >= row_count) return -1; + return index; +} + +using TableRowRenderer = void (*)(Canvas& c, + void* userdata, + int row_index, + const Rect& row_rect, + int text_y, + const TableColumn* cols, + int col_count, + const Theme& theme, + const TableStyle& style); + +inline void draw_table(Canvas& c, + const TableLayout& layout, + const TableColumn* cols, + int col_count, + int row_count, + int scroll, + int selected, + int hovered, + const Theme& theme, + const TableStyle& style, + TableRowRenderer draw_row, + void* userdata) { + c.fill_rect(layout.header.x, layout.header.y, layout.header.w, layout.header.h, style.header_bg); + c.hline(layout.header.x, layout.header.y + layout.header.h - 1, layout.header.w, style.header_border); + + int fh = system_font_height(); + int header_text_y = layout.header.y + (layout.header.h - fh) / 2; + for (int i = 0; i < col_count; i++) { + c.text(layout.header.x + cols[i].x, header_text_y, cols[i].label, style.header_text); + } + + int visible = table_visible_rows(layout); + for (int row = 0; row < visible; row++) { + int index = scroll + row; + if (index >= row_count) break; + + Rect row_rect = table_row_rect(layout, scroll, index); + if (index == selected) { + c.fill_rect(row_rect.x, row_rect.y, row_rect.w, row_rect.h, style.row_selected_bg); + } else if (index == hovered && style.row_hover_bg.a > 0) { + c.fill_rect(row_rect.x, row_rect.y, row_rect.w, row_rect.h, style.row_hover_bg); + } + + if (draw_row) { + int text_y = row_rect.y + (layout.row_h - fh) / 2; + draw_row(c, userdata, index, row_rect, text_y, cols, col_count, theme, style); + } + } +} + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/mtk/theme.hpp b/template/sysroot/include/gui/mtk/theme.hpp new file mode 100644 index 0000000..95c3638 --- /dev/null +++ b/template/sysroot/include/gui/mtk/theme.hpp @@ -0,0 +1,133 @@ +/* + * theme.hpp + * Montauk Toolkit theme tokens and color helpers + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include "gui/gui.hpp" +#include "gui/mtk/settings.hpp" + +namespace gui::mtk { + +inline Color mix(Color base, Color tint, uint8_t tint_alpha) { + auto blend = [tint_alpha](uint8_t a, uint8_t b) -> uint8_t { + return (uint8_t)((((uint16_t)a * (255 - tint_alpha)) + + ((uint16_t)b * tint_alpha) + 127) / 255); + }; + return Color::from_rgb(blend(base.r, tint.r), + blend(base.g, tint.g), + blend(base.b, tint.b)); +} + +inline Color lighten(Color c, uint8_t amount) { + return mix(c, colors::WHITE, amount); +} + +inline Color darken(Color c, uint8_t amount) { + return mix(c, colors::BLACK, amount); +} + +// Light selection/hover tint derived from the desktop accent. Returns the +// canonical MENU_HOVER for the default blue accent so existing visuals are +// preserved exactly; otherwise tints white with ~11% of the accent. +inline Color accent_hover_tint(Color accent) { + if (accent.r == colors::ACCENT.r && accent.g == colors::ACCENT.g + && accent.b == colors::ACCENT.b) + return colors::MENU_HOVER; + return mix(colors::WHITE, accent, 28); +} + +struct Theme { + Color window_bg; + Color surface; + Color surface_alt; + Color surface_hover; + Color border; + Color text; + Color text_muted; + Color text_subtle; + Color text_inverse; + + Color accent; + Color accent_hover; + Color accent_soft; + Color accent_fg; + Color selection; + Color text_selection; + + Color danger; + Color danger_hover; + Color danger_soft; + Color danger_fg; + + Color disabled_bg; + Color disabled_fg; + + Color badge_admin_bg; + Color badge_admin_fg; + Color badge_user_bg; + Color badge_user_fg; + + int radius_sm; + int radius_md; + int control_h; + int tab_h; + int gap_xs; + int gap_sm; + int gap_md; + int gap_lg; +}; + +inline Theme make_theme(Color accent) { + Theme theme {}; + theme.window_bg = colors::WINDOW_BG; + theme.surface = Color::from_rgb(0xF5, 0xF5, 0xF5); + theme.surface_alt = Color::from_rgb(0xF8, 0xF8, 0xF8); + theme.surface_hover = mix(theme.surface, accent, 18); + theme.border = colors::BORDER; + theme.text = colors::TEXT_COLOR; + theme.text_muted = Color::from_rgb(0x88, 0x88, 0x88); + theme.text_subtle = Color::from_rgb(0x66, 0x66, 0x66); + theme.text_inverse = colors::WHITE; + + theme.accent = accent; + theme.accent_hover = darken(accent, 32); + theme.accent_soft = lighten(accent, 214); + theme.accent_fg = colors::WHITE; + theme.selection = accent; + theme.text_selection = Color::from_rgb(0xB0, 0xD0, 0xF0); + + theme.danger = Color::from_rgb(0xD0, 0x3E, 0x3E); + theme.danger_hover = Color::from_rgb(0xDD, 0x44, 0x44); + theme.danger_soft = Color::from_rgb(0xF7, 0xDF, 0xDF); + theme.danger_fg = colors::WHITE; + + theme.disabled_bg = Color::from_rgb(0xCC, 0xCC, 0xCC); + theme.disabled_fg = colors::WHITE; + + theme.badge_admin_bg = Color::from_rgb(0xE8, 0xD8, 0xF0); + theme.badge_admin_fg = Color::from_rgb(0x7B, 0x3E, 0xB8); + theme.badge_user_bg = Color::from_rgb(0xE0, 0xE8, 0xF0); + theme.badge_user_fg = Color::from_rgb(0x36, 0x7B, 0xF0); + + theme.radius_sm = 3; + theme.radius_md = 4; + theme.control_h = 30; + theme.tab_h = 36; + theme.gap_xs = 2; + theme.gap_sm = 6; + theme.gap_md = 10; + theme.gap_lg = 16; + return theme; +} + +// Zero-arg overload pulls the accent from the desktop appearance settings, so +// MTK widgets (buttons, menus, etc.) automatically pick up the user's chosen +// accent without each caller having to plumb it through. +inline Theme make_theme() { + return make_theme(load_system_accent()); +} + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/mtk/widgets.hpp b/template/sysroot/include/gui/mtk/widgets.hpp new file mode 100644 index 0000000..03328db --- /dev/null +++ b/template/sysroot/include/gui/mtk/widgets.hpp @@ -0,0 +1,1122 @@ +/* + * widgets.hpp + * Montauk Toolkit immediate-mode widgets + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include + +#include "gui/canvas.hpp" +#include "gui/clipboard.hpp" +#include "gui/font.hpp" +#include "gui/mtk/theme.hpp" + +namespace gui::mtk { + +enum ButtonVariant : uint8_t { + BUTTON_PRIMARY = 0, + BUTTON_SECONDARY, + BUTTON_DANGER, + BUTTON_GHOST, + BUTTON_TONAL, +}; + +struct WidgetState { + bool active; + bool hovered; + bool enabled; +}; + +struct ContextMenuState { + bool open; + int x; + int y; + int hover; +}; + +struct ContextMenuItem { + const char* label; + int id; + bool enabled; +}; + +enum ContextMenuResult : int { + CONTEXT_MENU_NONE = -1, + CONTEXT_MENU_CONSUMED = -2, + CONTEXT_MENU_DISMISSED = -3, +}; + +static constexpr int CONTEXT_MENU_DEFAULT_W = 140; +static constexpr int CONTEXT_MENU_ITEM_H = 24; +static constexpr int CONTEXT_MENU_PAD_Y = 4; + +struct TextInputState { + int cursor; + int selection_anchor; + bool dragging; + ContextMenuState context; +}; + +using TextInputCharFilter = bool (*)(char ch, void* userdata); + +enum TextInputResult : uint8_t { + TEXT_INPUT_NONE = 0, + TEXT_INPUT_CONSUMED = 1, + TEXT_INPUT_CHANGED = 2, +}; + +enum TextInputContextItem : int { + TEXT_INPUT_CTX_CUT = 0, + TEXT_INPUT_CTX_COPY, + TEXT_INPUT_CTX_PASTE, + TEXT_INPUT_CTX_DELETE, + TEXT_INPUT_CTX_COUNT, +}; + +inline WidgetState widget_state(bool active = false, bool hovered = false, bool enabled = true) { + return {active, hovered, enabled}; +} + +struct ButtonColors { + Color bg; + Color border; + Color fg; +}; + +inline void context_menu_reset(ContextMenuState& state) { + state.open = false; + state.x = 0; + state.y = 0; + state.hover = -1; +} + +inline void context_menu_open(ContextMenuState& state, int x, int y) { + state.open = true; + state.x = x; + state.y = y; + state.hover = -1; +} + +inline void context_menu_close(ContextMenuState& state) { + state.open = false; + state.hover = -1; +} + +inline int context_menu_height(int item_count, + int item_h = CONTEXT_MENU_ITEM_H) { + return gui_max(item_count, 0) * item_h + CONTEXT_MENU_PAD_Y * 2; +} + +inline Rect context_menu_rect(const ContextMenuState& state, + int item_count, + int view_w, + int view_h, + int menu_w = CONTEXT_MENU_DEFAULT_W, + int item_h = CONTEXT_MENU_ITEM_H) { + int menu_h = context_menu_height(item_count, item_h); + int x = state.x; + int y = state.y; + if (x + menu_w > view_w) x = view_w - menu_w; + if (y + menu_h > view_h) y = view_h - menu_h; + if (x < 0) x = 0; + if (y < 0) y = 0; + return {x, y, menu_w, menu_h}; +} + +inline int context_menu_hit_item(const ContextMenuState& state, + int item_count, + int mx, + int my, + int view_w, + int view_h, + int menu_w = CONTEXT_MENU_DEFAULT_W, + int item_h = CONTEXT_MENU_ITEM_H) { + if (!state.open || item_count <= 0) return -1; + Rect menu = context_menu_rect(state, item_count, view_w, view_h, + menu_w, item_h); + Rect items = {menu.x + 2, menu.y + CONTEXT_MENU_PAD_Y, + menu.w - 4, item_count * item_h}; + if (!items.contains(mx, my)) return -1; + return (my - items.y) / item_h; +} + +inline int context_menu_handle_mouse(ContextMenuState& state, + const ContextMenuItem* items, + int item_count, + int mx, + int my, + uint8_t buttons, + uint8_t prev_buttons, + int view_w, + int view_h, + int menu_w = CONTEXT_MENU_DEFAULT_W, + int item_h = CONTEXT_MENU_ITEM_H) { + if (!state.open) return CONTEXT_MENU_NONE; + + bool left_pressed = (buttons & 1) && !(prev_buttons & 1); + bool right_pressed = (buttons & 2) && !(prev_buttons & 2); + state.hover = context_menu_hit_item(state, item_count, mx, my, + view_w, view_h, menu_w, item_h); + + if (left_pressed) { + int hover = state.hover; + context_menu_close(state); + if (hover >= 0 && hover < item_count && items && items[hover].enabled) + return items[hover].id; + return CONTEXT_MENU_DISMISSED; + } + + if (right_pressed) { + context_menu_close(state); + return CONTEXT_MENU_DISMISSED; + } + + return CONTEXT_MENU_CONSUMED; +} + +inline int context_menu_label_height(TrueTypeFont* font = nullptr, + int font_size = 0) { + if (font && font->valid && font_size > 0) + return font->get_line_height(font_size); + return system_font_height(); +} + +inline void context_menu_draw_label(Canvas& c, + int x, + int y, + const char* label, + Color color, + TrueTypeFont* font = nullptr, + int font_size = 0) { + if (font && font->valid && font_size > 0) { + font->draw_to_buffer(c.pixels, c.w, c.h, x, y, label, color, font_size); + return; + } + c.text(x, y, label, color); +} + +inline void draw_context_menu(Canvas& c, + const ContextMenuState& state, + const ContextMenuItem* items, + int item_count, + const Theme& theme, + int menu_w = CONTEXT_MENU_DEFAULT_W, + int item_h = CONTEXT_MENU_ITEM_H, + TrueTypeFont* font = nullptr, + int font_size = 0) { + if (!state.open || !items || item_count <= 0) return; + + Rect menu = context_menu_rect(state, item_count, c.w, c.h, + menu_w, item_h); + c.fill_rect(menu.x + 2, menu.y + 2, menu.w, menu.h, + Color::from_rgb(0x80, 0x80, 0x80)); + c.fill_rounded_rect(menu.x, menu.y, menu.w, menu.h, 4, + colors::MENU_BG); + c.rect(menu.x, menu.y, menu.w, menu.h, theme.border); + + int fh = context_menu_label_height(font, font_size); + for (int i = 0; i < item_count; i++) { + Rect item = {menu.x + 2, menu.y + CONTEXT_MENU_PAD_Y + i * item_h, + menu.w - 4, item_h}; + if (state.hover == i) + c.fill_rect(item.x, item.y, item.w, item.h, accent_hover_tint(theme.accent)); + + Color label_color = items[i].enabled ? theme.text : theme.text_muted; + context_menu_draw_label(c, menu.x + 12, item.y + (item.h - fh) / 2, + items[i].label, label_color, font, font_size); + } +} + +inline int text_len(const char* text) { + int len = 0; + while (text && text[len]) len++; + return len; +} + +inline int text_input_len(const char* text, int cap = 0) { + int len = 0; + int limit = cap > 0 ? cap - 1 : 0x7FFFFFFF; + while (text && text[len] && len < limit) len++; + return len; +} + +inline int text_input_clamp_cursor(int cursor, int len) { + return gui_clamp(cursor, 0, gui_max(len, 0)); +} + +inline void text_input_reset(TextInputState& state, int cursor = 0) { + state.cursor = gui_max(cursor, 0); + state.selection_anchor = state.cursor; + state.dragging = false; + context_menu_reset(state.context); +} + +inline void text_input_set_cursor(TextInputState& state, int len, int cursor, bool selecting = false) { + state.cursor = text_input_clamp_cursor(cursor, len); + state.selection_anchor = selecting + ? text_input_clamp_cursor(state.selection_anchor, len) + : state.cursor; +} + +inline bool text_input_has_selection(const TextInputState& state) { + return state.cursor != state.selection_anchor; +} + +inline int text_input_selection_start(const TextInputState& state, int len) { + int cursor = text_input_clamp_cursor(state.cursor, len); + int anchor = text_input_clamp_cursor(state.selection_anchor, len); + return cursor < anchor ? cursor : anchor; +} + +inline int text_input_selection_end(const TextInputState& state, int len) { + int cursor = text_input_clamp_cursor(state.cursor, len); + int anchor = text_input_clamp_cursor(state.selection_anchor, len); + return cursor > anchor ? cursor : anchor; +} + +inline bool text_input_has_selection(const TextInputState& state, const char* text, int cap = 0) { + int len = text_input_len(text, cap); + return text_input_selection_start(state, len) != text_input_selection_end(state, len); +} + +inline int text_input_prefix_width(const char* text, int count, bool masked) { + char prefix[512]; + int len = 0; + while (text && text[len] && len < count && len < (int)sizeof(prefix) - 1) { + prefix[len] = masked ? '*' : text[len]; + len++; + } + prefix[len] = '\0'; + return text_width(prefix); +} + +inline int text_input_index_from_x(const Rect& bounds, const char* value, + int mx, bool masked = false) { + int rel_x = mx - (bounds.x + 8); + if (rel_x <= 0) return 0; + + int len = text_input_len(value); + int prev_w = 0; + for (int i = 0; i < len; i++) { + int cur_w = text_input_prefix_width(value, i + 1, masked); + int midpoint = prev_w + (cur_w - prev_w) / 2; + if (rel_x < midpoint) return i; + prev_w = cur_w; + } + return len; +} + +inline int text_input_mouse(TextInputState& state, + const Rect& bounds, + const char* value, + int mx, int my, + uint8_t buttons, + uint8_t prev_buttons, + bool focused, + bool masked = false) { + bool left_down = (buttons & 1) != 0; + bool left_pressed = (buttons & 1) && !(prev_buttons & 1); + bool left_released = !(buttons & 1) && (prev_buttons & 1); + + if (left_pressed && bounds.contains(mx, my)) { + int cursor = text_input_index_from_x(bounds, value, mx, masked); + state.cursor = cursor; + state.selection_anchor = cursor; + state.dragging = true; + return TEXT_INPUT_CONSUMED; + } + + if (focused && state.dragging && left_down) { + int cursor = text_input_index_from_x(bounds, value, mx, masked); + if (state.cursor != cursor) { + state.cursor = cursor; + return TEXT_INPUT_CONSUMED; + } + return TEXT_INPUT_CONSUMED; + } + + if (state.dragging && left_released) { + state.dragging = false; + return TEXT_INPUT_CONSUMED; + } + + return TEXT_INPUT_NONE; +} + +inline bool text_input_word_char(char ch) { + return (ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '_'; +} + +inline int text_input_prev_word_boundary(const char* text, int cursor) { + int pos = cursor; + if (pos <= 0) return 0; + pos--; + while (pos > 0 && !text_input_word_char(text[pos])) pos--; + while (pos > 0 && text_input_word_char(text[pos - 1])) pos--; + return pos; +} + +inline int text_input_next_word_boundary(const char* text, int cursor) { + int len = text_input_len(text); + int pos = text_input_clamp_cursor(cursor, len); + if (pos >= len) return len; + while (pos < len && text_input_word_char(text[pos])) pos++; + while (pos < len && !text_input_word_char(text[pos])) pos++; + return pos; +} + +inline void text_input_delete_range(char* text, int* len, int start, int end) { + if (!text || !len || start >= end) return; + for (int i = start; i <= *len - (end - start); i++) + text[i] = text[i + (end - start)]; + *len -= (end - start); +} + +inline bool text_input_char_allowed(char ch, TextInputCharFilter filter = nullptr, + void* userdata = nullptr) { + unsigned char u = (unsigned char)ch; + if (u < 0x20 || u >= 0x7F) return false; + return filter == nullptr || filter(ch, userdata); +} + +inline bool text_input_delete_selection(TextInputState& state, char* text, int cap) { + int len = text_input_len(text, cap); + int sel_start = text_input_selection_start(state, len); + int sel_end = text_input_selection_end(state, len); + if (sel_start == sel_end) return false; + + text_input_delete_range(text, &len, sel_start, sel_end); + state.cursor = sel_start; + state.selection_anchor = sel_start; + return true; +} + +inline bool text_input_copy_selection(const TextInputState& state, const char* text, + int cap, bool masked = false) { + if (masked) return false; + int len = text_input_len(text, cap); + int sel_start = text_input_selection_start(state, len); + int sel_end = text_input_selection_end(state, len); + if (sel_start == sel_end) return false; + return gui::clipboard_set_text(text + sel_start, sel_end - sel_start); +} + +inline bool text_input_replace_selection_with_text(TextInputState& state, + char* text, + int cap, + const char* insert, + int insert_len, + TextInputCharFilter filter = nullptr, + void* userdata = nullptr) { + if (!text || !insert || cap <= 0 || insert_len < 0) return false; + + for (int i = 0; i < insert_len; i++) { + if (!text_input_char_allowed(insert[i], filter, userdata)) + return false; + } + + int len = text_input_len(text, cap); + state.cursor = text_input_clamp_cursor(state.cursor, len); + state.selection_anchor = text_input_clamp_cursor(state.selection_anchor, len); + + int sel_start = text_input_selection_start(state, len); + int sel_end = text_input_selection_end(state, len); + int replaced = sel_end - sel_start; + if (len - replaced + insert_len >= cap) return false; + + if (replaced > 0) + text_input_delete_range(text, &len, sel_start, sel_end); + + for (int i = len; i >= sel_start; i--) + text[i + insert_len] = text[i]; + for (int i = 0; i < insert_len; i++) + text[sel_start + i] = insert[i]; + + state.cursor = sel_start + insert_len; + state.selection_anchor = state.cursor; + return replaced > 0 || insert_len > 0; +} + +inline bool text_input_paste_clipboard(TextInputState& state, + char* text, + int cap, + TextInputCharFilter filter = nullptr, + void* userdata = nullptr) { + int paste_len = 0; + char* paste = gui::clipboard_get_text_alloc(&paste_len); + if (paste == nullptr || paste_len <= 0) { + if (paste) montauk::mfree(paste); + return false; + } + + bool changed = text_input_replace_selection_with_text(state, text, cap, + paste, paste_len, + filter, userdata); + montauk::mfree(paste); + return changed; +} + +inline bool text_input_cut_selection(TextInputState& state, char* text, + int cap, bool masked = false) { + if (!text_input_copy_selection(state, text, cap, masked)) + return false; + return text_input_delete_selection(state, text, cap); +} + +inline Rect text_input_context_menu_rect(const TextInputState& state, int view_w, int view_h) { + return context_menu_rect(state.context, TEXT_INPUT_CTX_COUNT, view_w, view_h); +} + +inline void text_input_context_items(ContextMenuItem items[TEXT_INPUT_CTX_COUNT], + bool has_selection, + bool masked) { + bool paste_enabled = gui::clipboard_has_text(); + items[TEXT_INPUT_CTX_CUT] = {"Cut", TEXT_INPUT_CTX_CUT, + has_selection && !masked}; + items[TEXT_INPUT_CTX_COPY] = {"Copy", TEXT_INPUT_CTX_COPY, + has_selection && !masked}; + items[TEXT_INPUT_CTX_PASTE] = {"Paste", TEXT_INPUT_CTX_PASTE, + paste_enabled}; + items[TEXT_INPUT_CTX_DELETE] = {"Delete", TEXT_INPUT_CTX_DELETE, + has_selection}; +} + +inline int text_input_handle_mouse(TextInputState& state, + const Rect& bounds, + char* text, + int cap, + int mx, + int my, + uint8_t buttons, + uint8_t prev_buttons, + int view_w, + int view_h, + bool focused, + bool masked = false, + TextInputCharFilter filter = nullptr, + void* userdata = nullptr) { + bool right_pressed = (buttons & 2) && !(prev_buttons & 2); + + if (state.context.open) { + bool has_selection = text_input_has_selection(state, text, cap); + ContextMenuItem items[TEXT_INPUT_CTX_COUNT]; + text_input_context_items(items, has_selection, masked); + + int action = context_menu_handle_mouse(state.context, items, + TEXT_INPUT_CTX_COUNT, + mx, my, buttons, prev_buttons, + view_w, view_h); + if (action == CONTEXT_MENU_NONE) return TEXT_INPUT_NONE; + int result = TEXT_INPUT_CONSUMED; + switch (action) { + case TEXT_INPUT_CTX_CUT: + if (text_input_cut_selection(state, text, cap, masked)) + result |= TEXT_INPUT_CHANGED; + break; + case TEXT_INPUT_CTX_COPY: + text_input_copy_selection(state, text, cap, masked); + break; + case TEXT_INPUT_CTX_PASTE: + if (text_input_paste_clipboard(state, text, cap, filter, userdata)) + result |= TEXT_INPUT_CHANGED; + break; + case TEXT_INPUT_CTX_DELETE: + if (text_input_delete_selection(state, text, cap)) + result |= TEXT_INPUT_CHANGED; + break; + } + return result; + } + + if (right_pressed && bounds.contains(mx, my)) { + int len = text_input_len(text, cap); + int cursor = text_input_index_from_x(bounds, text, mx, masked); + int sel_start = text_input_selection_start(state, len); + int sel_end = text_input_selection_end(state, len); + if (sel_start == sel_end || cursor < sel_start || cursor > sel_end) + text_input_set_cursor(state, len, cursor, false); + state.dragging = false; + context_menu_open(state.context, mx, my); + return TEXT_INPUT_CONSUMED; + } + + return text_input_mouse(state, bounds, text, mx, my, buttons, prev_buttons, + focused, masked); +} + +inline int text_input_key(TextInputState& state, + char* text, + int cap, + const Montauk::KeyEvent& key, + TextInputCharFilter filter = nullptr, + void* userdata = nullptr, + bool masked = false) { + if (!key.pressed || !text || cap <= 0) return TEXT_INPUT_NONE; + + int len = text_input_len(text, cap); + state.cursor = text_input_clamp_cursor(state.cursor, len); + state.selection_anchor = text_input_clamp_cursor(state.selection_anchor, len); + + if (state.context.open) { + context_menu_close(state.context); + if (key.scancode == 0x01) return TEXT_INPUT_CONSUMED; + } + + if (key.ctrl && (key.scancode == 0x1E || key.ascii == 'a' || key.ascii == 'A')) { + state.selection_anchor = 0; + state.cursor = len; + return TEXT_INPUT_CONSUMED; + } + + int sel_start = text_input_selection_start(state, len); + int sel_end = text_input_selection_end(state, len); + + if (key.ctrl && !key.alt && (key.ascii == 'c' || key.ascii == 'C')) { + text_input_copy_selection(state, text, cap, masked); + return TEXT_INPUT_CONSUMED; + } + + if (key.ctrl && !key.alt && (key.ascii == 'x' || key.ascii == 'X')) { + bool changed = text_input_cut_selection(state, text, cap, masked); + return TEXT_INPUT_CONSUMED | (changed ? TEXT_INPUT_CHANGED : 0); + } + + if (key.ctrl && !key.alt && (key.ascii == 'v' || key.ascii == 'V')) { + bool changed = text_input_paste_clipboard(state, text, cap, filter, userdata); + return TEXT_INPUT_CONSUMED | (changed ? TEXT_INPUT_CHANGED : 0); + } + + if (key.scancode == 0x4B || key.scancode == 0x4D || + key.scancode == 0x47 || key.scancode == 0x4F) { + int next = state.cursor; + if (!key.shift && sel_start != sel_end && key.scancode == 0x4B) + next = sel_start; + else if (!key.shift && sel_start != sel_end && key.scancode == 0x4D) + next = sel_end; + else if (key.scancode == 0x4B) + next = key.ctrl ? text_input_prev_word_boundary(text, state.cursor) : state.cursor - 1; + else if (key.scancode == 0x4D) + next = key.ctrl ? text_input_next_word_boundary(text, state.cursor) : state.cursor + 1; + else if (key.scancode == 0x47) + next = 0; + else if (key.scancode == 0x4F) + next = len; + + text_input_set_cursor(state, len, next, key.shift); + return TEXT_INPUT_CONSUMED; + } + + bool changed = false; + + if (key.ascii == '\b' || key.scancode == 0x0E) { + if (sel_start != sel_end) { + text_input_delete_range(text, &len, sel_start, sel_end); + state.cursor = sel_start; + changed = true; + } else if (key.ctrl) { + int start = text_input_prev_word_boundary(text, state.cursor); + if (start != state.cursor) { + text_input_delete_range(text, &len, start, state.cursor); + state.cursor = start; + changed = true; + } + } else if (state.cursor > 0) { + text_input_delete_range(text, &len, state.cursor - 1, state.cursor); + state.cursor--; + changed = true; + } + state.selection_anchor = state.cursor; + return TEXT_INPUT_CONSUMED | (changed ? TEXT_INPUT_CHANGED : 0); + } + + if (key.scancode == 0x53) { + if (sel_start != sel_end) { + text_input_delete_range(text, &len, sel_start, sel_end); + state.cursor = sel_start; + changed = true; + } else if (key.ctrl) { + int end = text_input_next_word_boundary(text, state.cursor); + if (end != state.cursor) { + text_input_delete_range(text, &len, state.cursor, end); + changed = true; + } + } else if (state.cursor < len) { + text_input_delete_range(text, &len, state.cursor, state.cursor + 1); + changed = true; + } + state.selection_anchor = state.cursor; + return TEXT_INPUT_CONSUMED | (changed ? TEXT_INPUT_CHANGED : 0); + } + + if (key.ctrl || key.alt || !text_input_char_allowed(key.ascii, filter, userdata)) + return TEXT_INPUT_NONE; + + if (sel_start != sel_end) { + text_input_delete_range(text, &len, sel_start, sel_end); + state.cursor = sel_start; + changed = true; + } + + if (len < cap - 1) { + for (int i = len; i >= state.cursor; i--) + text[i + 1] = text[i]; + text[state.cursor++] = key.ascii; + len++; + changed = true; + } + + state.selection_anchor = state.cursor; + return TEXT_INPUT_CONSUMED | (changed ? TEXT_INPUT_CHANGED : 0); +} + +inline bool same_color(Color a, Color b) { + return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a; +} + +inline void draw_rounded_frame(Canvas& c, + const Rect& bounds, + int radius, + Color fill, + Color border, + int border_w = 1) { + if (bounds.empty()) return; + if (border_w <= 0 || same_color(fill, border)) { + c.fill_rounded_rect(bounds.x, bounds.y, bounds.w, bounds.h, gui_max(radius, 0), fill); + return; + } + + c.fill_rounded_rect(bounds.x, bounds.y, bounds.w, bounds.h, gui_max(radius, 0), border); + int inner_w = bounds.w - border_w * 2; + int inner_h = bounds.h - border_w * 2; + if (inner_w <= 0 || inner_h <= 0) return; + c.fill_rounded_rect(bounds.x + border_w, bounds.y + border_w, + inner_w, inner_h, gui_max(radius - border_w, 0), fill); +} + +inline ButtonColors resolve_button_colors(ButtonVariant variant, + const WidgetState& state, + const Theme& theme) { + if (!state.enabled) { + return {theme.disabled_bg, theme.disabled_bg, theme.disabled_fg}; + } + + switch (variant) { + case BUTTON_PRIMARY: + return { + state.hovered ? theme.accent_hover : theme.accent, + state.hovered ? theme.accent_hover : theme.accent, + theme.accent_fg + }; + case BUTTON_DANGER: + return { + state.hovered ? theme.danger_hover : theme.danger, + state.hovered ? theme.danger_hover : theme.danger, + theme.danger_fg + }; + case BUTTON_GHOST: + if (state.active) { + return {theme.accent_soft, theme.accent_soft, theme.accent}; + } + return { + state.hovered ? theme.surface_hover : theme.window_bg, + theme.border, + theme.text + }; + case BUTTON_TONAL: + { + Color fill = state.hovered ? mix(theme.surface, theme.accent, 40) + : mix(theme.surface, theme.accent, 24); + return {fill, fill, theme.text}; + } + case BUTTON_SECONDARY: + default: + if (state.active) { + return { + state.hovered ? theme.accent_hover : theme.accent, + state.hovered ? theme.accent_hover : theme.accent, + theme.accent_fg + }; + } + return { + state.hovered ? theme.surface_hover : theme.window_bg, + theme.border, + theme.text + }; + } +} + +inline void draw_button(Canvas& c, + const Rect& bounds, + const char* label, + ButtonVariant variant, + const WidgetState& state, + const Theme& theme) { + if (bounds.empty()) return; + + ButtonColors colors = resolve_button_colors(variant, state, theme); + draw_rounded_frame(c, bounds, theme.radius_md, colors.bg, colors.border); + + if (label && label[0]) { + int tw = text_width(label); + int fh = system_font_height(); + int tx = bounds.x + (bounds.w - tw) / 2; + int ty = bounds.y + (bounds.h - fh) / 2; + c.text(tx, ty, label, colors.fg); + } +} + +inline void draw_separator(Canvas& c, int x, int y, int w, const Theme& theme) { + c.hline(x, y, w, theme.border); +} + +static constexpr int SCROLLBAR_W = 12; +static constexpr int SCROLLBAR_OUTER_PAD = 0; +static constexpr int SCROLLBAR_TRACK_PAD = 0; +static constexpr int SCROLLBAR_THUMB_INSET = 1; +static constexpr int SCROLLBAR_MIN_THUMB = 20; + +inline bool scrollbar_needed(int content_extent, int view_extent) { + return content_extent > view_extent && view_extent > 0; +} + +inline int scrollbar_max_offset(int content_extent, int view_extent) { + int max_offset = content_extent - view_extent; + return max_offset > 0 ? max_offset : 0; +} + +inline Rect scrollbar_track_rect(const Rect& viewport, + int width = SCROLLBAR_W, + int outer_pad = SCROLLBAR_OUTER_PAD, + int track_pad = SCROLLBAR_TRACK_PAD) { + int h = gui_max(viewport.h - track_pad * 2, 0); + int usable_w = viewport.w - outer_pad; + if (usable_w <= 0 || h <= 0) return {0, 0, 0, 0}; + int actual_w = gui_clamp(width, 1, usable_w); + return { + viewport.x + viewport.w - actual_w - outer_pad, + viewport.y + track_pad, + actual_w, + h + }; +} + +inline int scrollbar_thumb_extent(int content_extent, + int view_extent, + int track_extent, + int min_thumb = SCROLLBAR_MIN_THUMB) { + if (!scrollbar_needed(content_extent, view_extent) || track_extent <= 0) + return track_extent; + + int thumb = (int)(((int64_t)view_extent * track_extent) / content_extent); + return gui_clamp(thumb, gui_min(min_thumb, track_extent), track_extent); +} + +inline Rect scrollbar_thumb_rect(const Rect& track, + int content_extent, + int view_extent, + int offset, + int min_thumb = SCROLLBAR_MIN_THUMB, + int thumb_inset = SCROLLBAR_THUMB_INSET) { + if (track.empty() || !scrollbar_needed(content_extent, view_extent)) + return {0, 0, 0, 0}; + + int max_offset = scrollbar_max_offset(content_extent, view_extent); + int thumb_h = scrollbar_thumb_extent(content_extent, view_extent, + track.h, min_thumb); + int travel = gui_max(track.h - thumb_h, 0); + int clamped_offset = gui_clamp(offset, 0, max_offset); + int thumb_y = track.y + (max_offset > 0 + ? (int)(((int64_t)clamped_offset * travel) / max_offset) + : 0); + int thumb_w = gui_max(track.w - thumb_inset * 2, 1); + return {track.x + thumb_inset, thumb_y, thumb_w, thumb_h}; +} + +inline int scrollbar_offset_from_thumb_top(const Rect& track, + int content_extent, + int view_extent, + int thumb_extent, + int thumb_top) { + int max_offset = scrollbar_max_offset(content_extent, view_extent); + int travel = gui_max(track.h - thumb_extent, 0); + if (track.empty() || max_offset <= 0 || travel <= 0) + return 0; + + int rel = gui_clamp(thumb_top - track.y, 0, travel); + return (int)(((int64_t)rel * max_offset + travel / 2) / travel); +} + +inline Color scrollbar_thumb_color(const Theme& /*theme*/, + bool hovered, + bool dragging) { + if (hovered || dragging) return Color::from_rgb(0xA0, 0xA0, 0xA0); + return colors::SCROLLBAR_FG; +} + +inline void draw_scrollbar(Canvas& c, + const Rect& track, + const Rect& thumb, + bool hovered, + bool dragging, + const Theme& theme) { + if (track.empty() || thumb.empty()) return; + + c.fill_rect(track.x, track.y, track.w, track.h, colors::SCROLLBAR_BG); + Color thumb_fill = scrollbar_thumb_color(theme, hovered, dragging); + c.fill_rect(thumb.x, thumb.y, thumb.w, thumb.h, thumb_fill); +} + +inline Rect tab_rect(const Rect& bar, int count, int index) { + if (count <= 0) return {bar.x, bar.y, 0, bar.h}; + int slot_w = bar.w / count; + int rx = bar.x + slot_w * index; + int rw = (index == count - 1) ? (bar.w - slot_w * index) : slot_w; + return {rx, bar.y, rw, bar.h}; +} + +inline void draw_tab_bar(Canvas& c, + const Rect& bar, + const char* const* labels, + int count, + int active, + const Theme& theme) { + c.fill_rect(bar.x, bar.y, bar.w, bar.h, theme.surface); + c.hline(bar.x, bar.y + bar.h - 1, bar.w, theme.border); + + int fh = system_font_height(); + for (int i = 0; i < count; i++) { + Rect item = tab_rect(bar, count, i); + bool is_active = (i == active); + if (is_active) { + c.fill_rect(item.x, item.y, item.w, item.h, theme.window_bg); + if (item.w > 8) { + c.fill_rect(item.x + 4, item.y + item.h - 3, item.w - 8, 3, theme.selection); + } + } + + Color tc = is_active ? theme.accent : theme.text_subtle; + int tw = text_width(labels[i]); + c.text(item.x + (item.w - tw) / 2, + item.y + (item.h - fh) / 2, + labels[i], tc); + } +} + +inline int hit_tab_bar(const Rect& bar, int count, int mx, int my) { + if (!bar.contains(mx, my) || count <= 0) return -1; + for (int i = 0; i < count; i++) { + if (tab_rect(bar, count, i).contains(mx, my)) return i; + } + return -1; +} + +inline Rect radio_indicator_rect(const Rect& option) { + int size = 14; + return {option.x, option.y + (option.h - size) / 2, size, size}; +} + +inline void draw_radio(Canvas& c, + const Rect& option, + const char* label, + bool selected, + const Theme& theme) { + Rect bubble = radio_indicator_rect(option); + int radius = bubble.w / 2; + c.fill_rounded_rect(bubble.x, bubble.y, bubble.w, bubble.h, radius, theme.border); + c.fill_rounded_rect(bubble.x + 1, bubble.y + 1, bubble.w - 2, bubble.h - 2, + gui_max(radius - 1, 1), colors::WHITE); + if (selected) { + int inner = gui_max(bubble.w - 8, 2); + c.fill_rounded_rect(bubble.x + 4, bubble.y + 4, inner, inner, + gui_max(inner / 2, 1), theme.accent); + } + + int fh = system_font_height(); + c.text(bubble.x + bubble.w + theme.gap_sm, + option.y + (option.h - fh) / 2, + label, theme.text); +} + +inline Rect swatch_rect(int row_x, int row_y, int index, int size = 24, int gap = 6) { + return {row_x + index * (size + gap), row_y, size, size}; +} + +inline int hit_swatch_row(int mx, int my, + int row_x, int row_y, + int count, int size = 24, int gap = 6) { + for (int i = 0; i < count; i++) { + if (swatch_rect(row_x, row_y, i, size, gap).contains(mx, my)) return i; + } + return -1; +} + +inline void draw_swatch_row(Canvas& c, + int row_x, int row_y, + const Color* palette, + int count, + int selected_index, + const Theme& theme, + int size = 24, + int gap = 6) { + for (int i = 0; i < count; i++) { + Rect swatch = swatch_rect(row_x, row_y, i, size, gap); + if (i == selected_index) { + c.fill_rounded_rect(swatch.x - 2, swatch.y - 2, + swatch.w + 4, swatch.h + 4, 4, theme.accent); + } + c.fill_rounded_rect(swatch.x, swatch.y, swatch.w, swatch.h, 3, palette[i]); + c.rect(swatch.x, swatch.y, swatch.w, swatch.h, Color::from_rgb(0xCC, 0xCC, 0xCC)); + } +} + +inline void draw_list_row(Canvas& c, + const Rect& row, + bool selected, + bool alternate, + const Theme& theme) { + if (selected) { + c.fill_rounded_rect(row.x, row.y, row.w, row.h, theme.radius_md, theme.selection); + } else if (alternate) { + c.fill_rounded_rect(row.x, row.y, row.w, row.h, theme.radius_md, theme.surface_alt); + } +} + +inline int badge_width(const char* label, const Theme& theme) { + return text_width(label) + theme.gap_sm * 2; +} + +inline int badge_height() { + return system_font_height() + 4; +} + +inline void draw_badge(Canvas& c, + int x, int y, + const char* label, + Color bg, Color fg, + const Theme& theme) { + int bw = badge_width(label, theme); + int bh = badge_height(); + c.fill_rounded_rect(x, y, bw, bh, bh / 2, bg); + c.text(x + theme.gap_sm, y + 2, label, fg); +} + +inline const char* mask_text(const char* value, char* buffer, int cap) { + int len = 0; + while (value && value[len] && len < cap - 1) { + buffer[len] = '*'; + len++; + } + buffer[len] = '\0'; + return buffer; +} + +inline void copy_prefix(char* buffer, int cap, const char* value, int count, bool masked) { + if (cap <= 0) return; + int len = 0; + while (value && value[len] && len < count && len < cap - 1) { + buffer[len] = masked ? '*' : value[len]; + len++; + } + buffer[len] = '\0'; +} + +inline void draw_text_field(Canvas& c, + const Rect& bounds, + const char* value, + int cursor, + bool focused, + bool masked, + const Theme& theme, + int selection_anchor = -1) { + const char* text = value ? value : ""; + char masked_text[65]; + const char* shown = masked ? mask_text(text, masked_text, (int)sizeof(masked_text)) : text; + int len = text_len(text); + + draw_rounded_frame(c, bounds, theme.radius_sm, theme.surface, + focused ? theme.accent : theme.border); + + int fh = system_font_height(); + int tx = bounds.x + 8; + int ty = bounds.y + (bounds.h - fh) / 2; + + if (focused && selection_anchor >= 0) { + int cur = text_input_clamp_cursor(cursor, len); + int anchor = text_input_clamp_cursor(selection_anchor, len); + if (cur != anchor) { + int start = cur < anchor ? cur : anchor; + int end = cur > anchor ? cur : anchor; + int sx = tx + text_input_prefix_width(text, start, masked); + int ex = tx + text_input_prefix_width(text, end, masked); + int clip_x = gui_max(sx, bounds.x + 3); + int clip_r = gui_min(ex, bounds.x + bounds.w - 3); + if (clip_r > clip_x) + c.fill_rect(clip_x, bounds.y + 4, clip_r - clip_x, + gui_max(bounds.h - 8, 1), theme.text_selection); + } + } + + c.text(tx, ty, shown, theme.text); + + if (focused) { + int clamped = gui_clamp(cursor, 0, len); + int cx = tx + text_input_prefix_width(text, clamped, masked); + c.fill_rect(cx, bounds.y + 6, 2, gui_max(bounds.h - 12, 1), theme.accent); + } +} + +inline void draw_text_input_context_menu(Canvas& c, + const TextInputState& state, + const Theme& theme, + bool has_selection = true, + bool masked = false) { + ContextMenuItem items[TEXT_INPUT_CTX_COUNT]; + text_input_context_items(items, has_selection, masked); + draw_context_menu(c, state.context, items, TEXT_INPUT_CTX_COUNT, theme); +} + +inline Rect labeled_text_input_rect(int x, int y, int w, const Theme& theme, int field_h = 0) { + if (field_h <= 0) field_h = theme.control_h; + return {x, y + system_font_height() + theme.gap_xs, w, field_h}; +} + +inline int labeled_text_height(const Theme& theme, int field_h = 0) { + if (field_h <= 0) field_h = theme.control_h; + return system_font_height() + theme.gap_xs + field_h; +} + +inline void draw_labeled_text_field(Canvas& c, + int x, int y, int w, + const char* label, + const char* value, + int cursor, + bool focused, + bool masked, + const Theme& theme, + int field_h = 0, + int selection_anchor = -1) { + if (field_h <= 0) field_h = theme.control_h; + c.text(x, y, label, theme.text_muted); + draw_text_field(c, labeled_text_input_rect(x, y, w, theme, field_h), + value, cursor, focused, masked, theme, selection_anchor); +} + +inline void draw_modal_actions(Canvas& c, + const Rect& primary, + const char* primary_label, + ButtonVariant primary_variant, + const WidgetState& primary_state, + const Rect& secondary, + const char* secondary_label, + const WidgetState& secondary_state, + const Theme& theme) { + draw_button(c, primary, primary_label, primary_variant, primary_state, theme); + draw_button(c, secondary, secondary_label, BUTTON_SECONDARY, secondary_state, theme); +} + +} // namespace gui::mtk diff --git a/template/sysroot/include/gui/stb_image_write.h b/template/sysroot/include/gui/stb_image_write.h new file mode 100644 index 0000000..e4b32ed --- /dev/null +++ b/template/sysroot/include/gui/stb_image_write.h @@ -0,0 +1,1724 @@ +/* stb_image_write - v1.16 - public domain - http://nothings.org/stb + writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 + no warranty implied; use at your own risk + + Before #including, + + #define STB_IMAGE_WRITE_IMPLEMENTATION + + in the file that you want to have the implementation. + + Will probably not work correctly with strict-aliasing optimizations. + +ABOUT: + + This header file is a library for writing images to C stdio or a callback. + + The PNG output is not optimal; it is 20-50% larger than the file + written by a decent optimizing implementation; though providing a custom + zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. + This library is designed for source code compactness and simplicity, + not optimal image file size or run-time performance. + +BUILDING: + + You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. + You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace + malloc,realloc,free. + You can #define STBIW_MEMMOVE() to replace memmove() + You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function + for PNG compression (instead of the builtin one), it must have the following signature: + unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); + The returned data will be freed with STBIW_FREE() (free() by default), + so it must be heap allocated with STBIW_MALLOC() (malloc() by default), + +UNICODE: + + If compiling for Windows and you wish to use Unicode filenames, compile + with + #define STBIW_WINDOWS_UTF8 + and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert + Windows wchar_t filenames to utf8. + +USAGE: + + There are five functions, one for each image file format: + + int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); + int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); + + void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically + + There are also five equivalent functions that use an arbitrary write function. You are + expected to open/close your file-equivalent before and after calling these: + + int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + + where the callback is: + void stbi_write_func(void *context, void *data, int size); + + You can configure it with these global variables: + int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE + int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression + int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode + + + You can define STBI_WRITE_NO_STDIO to disable the file variant of these + functions, so the library will not use stdio.h at all. However, this will + also disable HDR writing, because it requires stdio for formatted output. + + Each function returns 0 on failure and non-0 on success. + + The functions create an image file defined by the parameters. The image + is a rectangle of pixels stored from left-to-right, top-to-bottom. + Each pixel contains 'comp' channels of data stored interleaved with 8-bits + per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is + monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. + The *data pointer points to the first byte of the top-left-most pixel. + For PNG, "stride_in_bytes" is the distance in bytes from the first byte of + a row of pixels to the first byte of the next row of pixels. + + PNG creates output files with the same number of components as the input. + The BMP format expands Y to RGB in the file format and does not + output alpha. + + PNG supports writing rectangles of data even when the bytes storing rows of + data are not consecutive in memory (e.g. sub-rectangles of a larger image), + by supplying the stride between the beginning of adjacent rows. The other + formats do not. (Thus you cannot write a native-format BMP through the BMP + writer, both because it is in BGR order and because it may have padding + at the end of the line.) + + PNG allows you to set the deflate compression level by setting the global + variable 'stbi_write_png_compression_level' (it defaults to 8). + + HDR expects linear float data. Since the format is always 32-bit rgb(e) + data, alpha (if provided) is discarded, and for monochrome data it is + replicated across all three channels. + + TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed + data, set the global variable 'stbi_write_tga_with_rle' to 0. + + JPEG does ignore alpha channels in input data; quality is between 1 and 100. + Higher quality looks better but results in a bigger image. + JPEG baseline (no JPEG progressive). + +CREDITS: + + + Sean Barrett - PNG/BMP/TGA + Baldur Karlsson - HDR + Jean-Sebastien Guay - TGA monochrome + Tim Kelsey - misc enhancements + Alan Hickman - TGA RLE + Emmanuel Julien - initial file IO callback implementation + Jon Olick - original jo_jpeg.cpp code + Daniel Gibson - integrate JPEG, allow external zlib + Aarni Koskela - allow choosing PNG filter + + bugfixes: + github:Chribba + Guillaume Chereau + github:jry2 + github:romigrou + Sergio Gonzalez + Jonas Karlsson + Filip Wasil + Thatcher Ulrich + github:poppolopoppo + Patrick Boettcher + github:xeekworx + Cap Petschulat + Simon Rodriguez + Ivan Tikhonov + github:ignotion + Adam Schackart + Andrew Kensler + +LICENSE + + See end of file for license information. + +*/ + +#ifndef INCLUDE_STB_IMAGE_WRITE_H +#define INCLUDE_STB_IMAGE_WRITE_H + +#include + +// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' +#ifndef STBIWDEF +#ifdef STB_IMAGE_WRITE_STATIC +#define STBIWDEF static +#else +#ifdef __cplusplus +#define STBIWDEF extern "C" +#else +#define STBIWDEF extern +#endif +#endif +#endif + +#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations +STBIWDEF int stbi_write_tga_with_rle; +STBIWDEF int stbi_write_png_compression_level; +STBIWDEF int stbi_write_force_png_filter; +#endif + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); + +#ifdef STBIW_WINDOWS_UTF8 +STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif +#endif + +typedef void stbi_write_func(void *context, void *data, int size); + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + +STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); + +#endif//INCLUDE_STB_IMAGE_WRITE_H + +#ifdef STB_IMAGE_WRITE_IMPLEMENTATION + +#ifdef _WIN32 + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif +#endif + +#ifndef STBI_WRITE_NO_STDIO +#include +#endif // STBI_WRITE_NO_STDIO + +#include +#include +#include +#include + +#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) +// ok +#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." +#endif + +#ifndef STBIW_MALLOC +#define STBIW_MALLOC(sz) malloc(sz) +#define STBIW_REALLOC(p,newsz) realloc(p,newsz) +#define STBIW_FREE(p) free(p) +#endif + +#ifndef STBIW_REALLOC_SIZED +#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) +#endif + + +#ifndef STBIW_MEMMOVE +#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) +#endif + + +#ifndef STBIW_ASSERT +#include +#define STBIW_ASSERT(x) assert(x) +#endif + +#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) + +#ifdef STB_IMAGE_WRITE_STATIC +static int stbi_write_png_compression_level = 8; +static int stbi_write_tga_with_rle = 1; +static int stbi_write_force_png_filter = -1; +#else +int stbi_write_png_compression_level = 8; +int stbi_write_tga_with_rle = 1; +int stbi_write_force_png_filter = -1; +#endif + +static int stbi__flip_vertically_on_write = 0; + +STBIWDEF void stbi_flip_vertically_on_write(int flag) +{ + stbi__flip_vertically_on_write = flag; +} + +typedef struct +{ + stbi_write_func *func; + void *context; + unsigned char buffer[64]; + int buf_used; +} stbi__write_context; + +// initialize a callback-based context +static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) +{ + s->func = c; + s->context = context; +} + +#ifndef STBI_WRITE_NO_STDIO + +static void stbi__stdio_write(void *context, void *data, int size) +{ + fwrite(data,1,size,(FILE*) context); +} + +#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) +#ifdef __cplusplus +#define STBIW_EXTERN extern "C" +#else +#define STBIW_EXTERN extern +#endif +STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBIW_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); + +STBIWDEF int stbiw_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 *stbiw__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBIW_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; +} + +static int stbi__start_write_file(stbi__write_context *s, const char *filename) +{ + FILE *f = stbiw__fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; +} + +static void stbi__end_write_file(stbi__write_context *s) +{ + fclose((FILE *)s->context); +} + +#endif // !STBI_WRITE_NO_STDIO + +typedef unsigned int stbiw_uint32; +typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; + +static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) +{ + while (*fmt) { + switch (*fmt++) { + case ' ': break; + case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); + s->func(s->context,&x,1); + break; } + case '2': { int x = va_arg(v,int); + unsigned char b[2]; + b[0] = STBIW_UCHAR(x); + b[1] = STBIW_UCHAR(x>>8); + s->func(s->context,b,2); + break; } + case '4': { stbiw_uint32 x = va_arg(v,int); + unsigned char b[4]; + b[0]=STBIW_UCHAR(x); + b[1]=STBIW_UCHAR(x>>8); + b[2]=STBIW_UCHAR(x>>16); + b[3]=STBIW_UCHAR(x>>24); + s->func(s->context,b,4); + break; } + default: + STBIW_ASSERT(0); + return; + } + } +} + +static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) +{ + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); +} + +static void stbiw__write_flush(stbi__write_context *s) +{ + if (s->buf_used) { + s->func(s->context, &s->buffer, s->buf_used); + s->buf_used = 0; + } +} + +static void stbiw__putc(stbi__write_context *s, unsigned char c) +{ + s->func(s->context, &c, 1); +} + +static void stbiw__write1(stbi__write_context *s, unsigned char a) +{ + if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) + stbiw__write_flush(s); + s->buffer[s->buf_used++] = a; +} + +static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) +{ + int n; + if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) + stbiw__write_flush(s); + n = s->buf_used; + s->buf_used = n+3; + s->buffer[n+0] = a; + s->buffer[n+1] = b; + s->buffer[n+2] = c; +} + +static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) +{ + unsigned char bg[3] = { 255, 0, 255}, px[3]; + int k; + + if (write_alpha < 0) + stbiw__write1(s, d[comp - 1]); + + switch (comp) { + case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case + case 1: + if (expand_mono) + stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp + else + stbiw__write1(s, d[0]); // monochrome TGA + break; + case 4: + if (!write_alpha) { + // composite against pink background + for (k = 0; k < 3; ++k) + px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; + stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); + break; + } + /* FALLTHROUGH */ + case 3: + stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); + break; + } + if (write_alpha > 0) + stbiw__write1(s, d[comp - 1]); +} + +static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) +{ + stbiw_uint32 zero = 0; + int i,j, j_end; + + if (y <= 0) + return; + + if (stbi__flip_vertically_on_write) + vdir *= -1; + + if (vdir < 0) { + j_end = -1; j = y-1; + } else { + j_end = y; j = 0; + } + + for (; j != j_end; j += vdir) { + for (i=0; i < x; ++i) { + unsigned char *d = (unsigned char *) data + (j*x+i)*comp; + stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); + } + stbiw__write_flush(s); + s->func(s->context, &zero, scanline_pad); + } +} + +static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) +{ + if (y < 0 || x < 0) { + return 0; + } else { + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); + stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); + return 1; + } +} + +static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) +{ + if (comp != 4) { + // write RGB bitmap + int pad = (-x*3) & 3; + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, + "11 4 22 4" "4 44 22 444444", + 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header + 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header + } else { + // RGBA bitmaps need a v4 header + // use BI_BITFIELDS mode with 32bpp and alpha mask + // (straight BI_RGB with alpha mask doesn't work in most readers) + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, + "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", + 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header + 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header + } +} + +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_bmp_core(&s, x, y, comp, data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_bmp_core(&s, x, y, comp, data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif //!STBI_WRITE_NO_STDIO + +static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) +{ + int has_alpha = (comp == 2 || comp == 4); + int colorbytes = has_alpha ? comp-1 : comp; + int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + + if (y < 0 || x < 0) + return 0; + + if (!stbi_write_tga_with_rle) { + return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, + "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); + } else { + int i,j,k; + int jend, jdir; + + stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); + + if (stbi__flip_vertically_on_write) { + j = 0; + jend = y; + jdir = 1; + } else { + j = y-1; + jend = -1; + jdir = -1; + } + for (; j != jend; j += jdir) { + unsigned char *row = (unsigned char *) data + j * x * comp; + int len; + + for (i = 0; i < x; i += len) { + unsigned char *begin = row + i * comp; + int diff = 1; + len = 1; + + if (i < x - 1) { + ++len; + diff = memcmp(begin, row + (i + 1) * comp, comp); + if (diff) { + const unsigned char *prev = begin; + for (k = i + 2; k < x && len < 128; ++k) { + if (memcmp(prev, row + k * comp, comp)) { + prev += comp; + ++len; + } else { + --len; + break; + } + } + } else { + for (k = i + 2; k < x && len < 128; ++k) { + if (!memcmp(begin, row + k * comp, comp)) { + ++len; + } else { + break; + } + } + } + } + + if (diff) { + unsigned char header = STBIW_UCHAR(len - 1); + stbiw__write1(s, header); + for (k = 0; k < len; ++k) { + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); + } + } else { + unsigned char header = STBIW_UCHAR(len - 129); + stbiw__write1(s, header); + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); + } + } + } + stbiw__write_flush(s); + } + return 1; +} + +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_tga_core(&s, x, y, comp, (void *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR writer +// by Baldur Karlsson + +#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) + +#ifndef STBI_WRITE_NO_STDIO + +static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) +{ + int exponent; + float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + + if (maxcomp < 1e-32f) { + rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; + } else { + float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + + rgbe[0] = (unsigned char)(linear[0] * normalize); + rgbe[1] = (unsigned char)(linear[1] * normalize); + rgbe[2] = (unsigned char)(linear[2] * normalize); + rgbe[3] = (unsigned char)(exponent + 128); + } +} + +static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) +{ + unsigned char lengthbyte = STBIW_UCHAR(length+128); + STBIW_ASSERT(length+128 <= 255); + s->func(s->context, &lengthbyte, 1); + s->func(s->context, &databyte, 1); +} + +static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) +{ + unsigned char lengthbyte = STBIW_UCHAR(length); + STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code + s->func(s->context, &lengthbyte, 1); + s->func(s->context, data, length); +} + +static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) +{ + unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; + unsigned char rgbe[4]; + float linear[3]; + int x; + + scanlineheader[2] = (width&0xff00)>>8; + scanlineheader[3] = (width&0x00ff); + + /* skip RLE for images too small or large */ + if (width < 8 || width >= 32768) { + for (x=0; x < width; x++) { + switch (ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + s->func(s->context, rgbe, 4); + } + } else { + int c,r; + /* encode into scratch buffer */ + for (x=0; x < width; x++) { + switch(ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + scratch[x + width*0] = rgbe[0]; + scratch[x + width*1] = rgbe[1]; + scratch[x + width*2] = rgbe[2]; + scratch[x + width*3] = rgbe[3]; + } + + s->func(s->context, scanlineheader, 4); + + /* RLE each component separately */ + for (c=0; c < 4; c++) { + unsigned char *comp = &scratch[width*c]; + + x = 0; + while (x < width) { + // find first run + r = x; + while (r+2 < width) { + if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) + break; + ++r; + } + if (r+2 >= width) + r = width; + // dump up to first run + while (x < r) { + int len = r-x; + if (len > 128) len = 128; + stbiw__write_dump_data(s, len, &comp[x]); + x += len; + } + // if there's a run, output it + if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd + // find next byte after run + while (r < width && comp[r] == comp[x]) + ++r; + // output run up to r + while (x < r) { + int len = r-x; + if (len > 127) len = 127; + stbiw__write_run_data(s, len, comp[x]); + x += len; + } + } + } + } + } +} + +static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) +{ + if (y <= 0 || x <= 0 || data == NULL) + return 0; + else { + // Each component is stored separately. Allocate scratch space for full output scanline. + unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); + int i, len; + char buffer[128]; + char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; + s->func(s->context, header, sizeof(header)-1); + +#ifdef __STDC_LIB_EXT1__ + len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#else + len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#endif + s->func(s->context, buffer, len); + + for(i=0; i < y; i++) + stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); + STBIW_FREE(scratch); + return 1; + } +} + +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_hdr_core(&s, x, y, comp, (float *) data); +} + +STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif // STBI_WRITE_NO_STDIO + + +////////////////////////////////////////////////////////////////////////////// +// +// PNG writer +// + +#ifndef STBIW_ZLIB_COMPRESS +// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() +#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) +#define stbiw__sbm(a) stbiw__sbraw(a)[0] +#define stbiw__sbn(a) stbiw__sbraw(a)[1] + +#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) +#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) +#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) + +#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) +#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) +#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) + +static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) +{ + int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); + STBIW_ASSERT(p); + if (p) { + if (!*arr) ((int *) p)[1] = 0; + *arr = (void *) ((int *) p + 2); + stbiw__sbm(*arr) = m; + } + return *arr; +} + +static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) +{ + while (*bitcount >= 8) { + stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); + *bitbuffer >>= 8; + *bitcount -= 8; + } + return data; +} + +static int stbiw__zlib_bitrev(int code, int codebits) +{ + int res=0; + while (codebits--) { + res = (res << 1) | (code & 1); + code >>= 1; + } + return res; +} + +static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) +{ + int i; + for (i=0; i < limit && i < 258; ++i) + if (a[i] != b[i]) break; + return i; +} + +static unsigned int stbiw__zhash(unsigned char *data) +{ + stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + return hash; +} + +#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) +#define stbiw__zlib_add(code,codebits) \ + (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) +#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) +// default huffman tables +#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) +#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) +#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) +#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) +#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) +#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) + +#define stbiw__ZHASH 16384 + +#endif // STBIW_ZLIB_COMPRESS + +STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) +{ +#ifdef STBIW_ZLIB_COMPRESS + // user provided a zlib compress implementation, use that + return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); +#else // use builtin + static unsigned short lengthc[] = { 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, 259 }; + static unsigned char lengtheb[]= { 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 }; + static unsigned short distc[] = { 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, 32768 }; + static unsigned char disteb[] = { 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 }; + unsigned int bitbuf=0; + int i,j, bitcount=0; + unsigned char *out = NULL; + unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); + if (hash_table == NULL) + return NULL; + if (quality < 5) quality = 5; + + stbiw__sbpush(out, 0x78); // DEFLATE 32K window + stbiw__sbpush(out, 0x5e); // FLEVEL = 1 + stbiw__zlib_add(1,1); // BFINAL = 1 + stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman + + for (i=0; i < stbiw__ZHASH; ++i) + hash_table[i] = NULL; + + i=0; + while (i < data_len-3) { + // hash next 3 bytes of data to be compressed + int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; + unsigned char *bestloc = 0; + unsigned char **hlist = hash_table[h]; + int n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32768) { // if entry lies within window + int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); + if (d >= best) { best=d; bestloc=hlist[j]; } + } + } + // when hash table entry is too long, delete half the entries + if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { + STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); + stbiw__sbn(hash_table[h]) = quality; + } + stbiw__sbpush(hash_table[h],data+i); + + if (bestloc) { + // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal + h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); + hlist = hash_table[h]; + n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32767) { + int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); + if (e > best) { // if next match is better, bail on current match + bestloc = NULL; + break; + } + } + } + } + + if (bestloc) { + int d = (int) (data+i - bestloc); // distance back + STBIW_ASSERT(d <= 32767 && best <= 258); + for (j=0; best > lengthc[j+1]-1; ++j); + stbiw__zlib_huff(j+257); + if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); + for (j=0; d > distc[j+1]-1; ++j); + stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); + if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); + i += best; + } else { + stbiw__zlib_huffb(data[i]); + ++i; + } + } + // write out final bytes + for (;i < data_len; ++i) + stbiw__zlib_huffb(data[i]); + stbiw__zlib_huff(256); // end of block + // pad with 0 bits to byte boundary + while (bitcount) + stbiw__zlib_add(0,1); + + for (i=0; i < stbiw__ZHASH; ++i) + (void) stbiw__sbfree(hash_table[i]); + STBIW_FREE(hash_table); + + // store uncompressed instead if compression was worse + if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { + stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 + for (j = 0; j < data_len;) { + int blocklen = data_len - j; + if (blocklen > 32767) blocklen = 32767; + stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression + stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN + stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN + stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); + memcpy(out+stbiw__sbn(out), data+j, blocklen); + stbiw__sbn(out) += blocklen; + j += blocklen; + } + } + + { + // compute adler32 on input + unsigned int s1=1, s2=0; + int blocklen = (int) (data_len % 5552); + j=0; + while (j < data_len) { + for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } + s1 %= 65521; s2 %= 65521; + j += blocklen; + blocklen = 5552; + } + stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s2)); + stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s1)); + } + *out_len = stbiw__sbn(out); + // make returned pointer freeable + STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); + return (unsigned char *) stbiw__sbraw(out); +#endif // STBIW_ZLIB_COMPRESS +} + +static unsigned int stbiw__crc32(unsigned char *buffer, int len) +{ +#ifdef STBIW_CRC32 + return STBIW_CRC32(buffer, len); +#else + static unsigned int 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 + }; + + unsigned int crc = ~0u; + int i; + for (i=0; i < len; ++i) + crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; + return ~crc; +#endif +} + +#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) +#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); +#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) + +static void stbiw__wpcrc(unsigned char **data, int len) +{ + unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + stbiw__wp32(*data, crc); +} + +static unsigned char stbiw__paeth(int a, int b, int c) +{ + int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); + if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); + if (pb <= pc) return STBIW_UCHAR(b); + return STBIW_UCHAR(c); +} + +// @OPTIMIZE: provide an option that always forces left-predict or paeth predict +static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) +{ + static int mapping[] = { 0,1,2,3,4 }; + static int firstmap[] = { 0,1,0,5,6 }; + int *mymap = (y != 0) ? mapping : firstmap; + int i; + int type = mymap[filter_type]; + unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); + int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; + + if (type==0) { + memcpy(line_buffer, z, width*n); + return; + } + + // first loop isn't optimized since it's just one pixel + for (i = 0; i < n; ++i) { + switch (type) { + case 1: line_buffer[i] = z[i]; break; + case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; + case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; + case 5: line_buffer[i] = z[i]; break; + case 6: line_buffer[i] = z[i]; break; + } + } + switch (type) { + case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; + case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; + case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; + case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; + case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; + } +} + +STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) +{ + int force_filter = stbi_write_force_png_filter; + int ctype[5] = { -1, 0, 4, 2, 6 }; + unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + unsigned char *out,*o, *filt, *zlib; + signed char *line_buffer; + int j,zlen; + + if (stride_bytes == 0) + stride_bytes = x * n; + + if (force_filter >= 5) { + force_filter = -1; + } + + filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; + line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } + for (j=0; j < y; ++j) { + int filter_type; + if (force_filter > -1) { + filter_type = force_filter; + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); + } else { // Estimate the best filter by running through all of them: + int best_filter = 0, best_filter_val = 0x7fffffff, est, i; + for (filter_type = 0; filter_type < 5; filter_type++) { + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); + + // Estimate the entropy of the line using this filter; the less, the better. + est = 0; + for (i = 0; i < x*n; ++i) { + est += abs((signed char) line_buffer[i]); + } + if (est < best_filter_val) { + best_filter_val = est; + best_filter = filter_type; + } + } + if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); + filter_type = best_filter; + } + } + // when we get here, filter_type contains the filter type, and line_buffer contains the data + filt[j*(x*n+1)] = (unsigned char) filter_type; + STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); + } + STBIW_FREE(line_buffer); + zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); + STBIW_FREE(filt); + if (!zlib) return 0; + + // each tag requires 12 bytes of overhead + out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); + if (!out) return 0; + *out_len = 8 + 12+13 + 12+zlen + 12; + + o=out; + STBIW_MEMMOVE(o,sig,8); o+= 8; + stbiw__wp32(o, 13); // header length + stbiw__wptag(o, "IHDR"); + stbiw__wp32(o, x); + stbiw__wp32(o, y); + *o++ = 8; + *o++ = STBIW_UCHAR(ctype[n]); + *o++ = 0; + *o++ = 0; + *o++ = 0; + stbiw__wpcrc(&o,13); + + stbiw__wp32(o, zlen); + stbiw__wptag(o, "IDAT"); + STBIW_MEMMOVE(o, zlib, zlen); + o += zlen; + STBIW_FREE(zlib); + stbiw__wpcrc(&o, zlen); + + stbiw__wp32(o,0); + stbiw__wptag(o, "IEND"); + stbiw__wpcrc(&o,0); + + STBIW_ASSERT(o == out + *out_len); + + return out; +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) +{ + FILE *f; + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + + f = stbiw__fopen(filename, "wb"); + if (!f) { STBIW_FREE(png); return 0; } + fwrite(png, 1, len, f); + fclose(f); + STBIW_FREE(png); + return 1; +} +#endif + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) +{ + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + func(context, png, len); + STBIW_FREE(png); + return 1; +} + + +/* *************************************************************************** + * + * JPEG writer + * + * This is based on Jon Olick's jo_jpeg.cpp: + * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html + */ + +static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, + 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; + +static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { + int bitBuf = *bitBufP, bitCnt = *bitCntP; + bitCnt += bs[1]; + bitBuf |= bs[0] << (24 - bitCnt); + while(bitCnt >= 8) { + unsigned char c = (bitBuf >> 16) & 255; + stbiw__putc(s, c); + if(c == 255) { + stbiw__putc(s, 0); + } + bitBuf <<= 8; + bitCnt -= 8; + } + *bitBufP = bitBuf; + *bitCntP = bitCnt; +} + +static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { + float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; + float z1, z2, z3, z4, z5, z11, z13; + + float tmp0 = d0 + d7; + float tmp7 = d0 - d7; + float tmp1 = d1 + d6; + float tmp6 = d1 - d6; + float tmp2 = d2 + d5; + float tmp5 = d2 - d5; + float tmp3 = d3 + d4; + float tmp4 = d3 - d4; + + // Even part + float tmp10 = tmp0 + tmp3; // phase 2 + float tmp13 = tmp0 - tmp3; + float tmp11 = tmp1 + tmp2; + float tmp12 = tmp1 - tmp2; + + d0 = tmp10 + tmp11; // phase 3 + d4 = tmp10 - tmp11; + + z1 = (tmp12 + tmp13) * 0.707106781f; // c4 + d2 = tmp13 + z1; // phase 5 + d6 = tmp13 - z1; + + // Odd part + tmp10 = tmp4 + tmp5; // phase 2 + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + // The rotator is modified from fig 4-8 to avoid extra negations. + z5 = (tmp10 - tmp12) * 0.382683433f; // c6 + z2 = tmp10 * 0.541196100f + z5; // c2-c6 + z4 = tmp12 * 1.306562965f + z5; // c2+c6 + z3 = tmp11 * 0.707106781f; // c4 + + z11 = tmp7 + z3; // phase 5 + z13 = tmp7 - z3; + + *d5p = z13 + z2; // phase 6 + *d3p = z13 - z2; + *d1p = z11 + z4; + *d7p = z11 - z4; + + *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; +} + +static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { + int tmp1 = val < 0 ? -val : val; + val = val < 0 ? val-1 : val; + bits[1] = 1; + while(tmp1 >>= 1) { + ++bits[1]; + } + bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { + } + // end0pos = first element in reverse order !=0 + if(end0pos == 0) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + return DU[0]; + } + for(i = 1; i <= end0pos; ++i) { + int startpos = i; + int nrzeroes; + unsigned short bits[2]; + for (; DU[i]==0 && i<=end0pos; ++i) { + } + nrzeroes = i-startpos; + if ( nrzeroes >= 16 ) { + int lng = nrzeroes>>4; + int nrmarker; + for (nrmarker=1; nrmarker <= lng; ++nrmarker) + stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); + nrzeroes &= 15; + } + stbiw__jpg_calcBits(DU[i], bits); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); + } + if(end0pos != 63) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + } + return DU[0]; +} + +static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { + // Constants that don't pollute global namespace + static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; + static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; + static const unsigned char std_ac_luminance_values[] = { + 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, + 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, + 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, + 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, + 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, + 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, + 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; + static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; + static const unsigned char std_ac_chrominance_values[] = { + 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, + 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, + 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, + 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, + 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, + 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, + 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + // Huffman tables + static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; + static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; + static const unsigned short YAC_HT[256][2] = { + {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const unsigned short UVAC_HT[256][2] = { + {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, + 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; + static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, + 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; + static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, + 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; + + int row, col, i, k, subsample; + float fdtbl_Y[64], fdtbl_UV[64]; + unsigned char YTable[64], UVTable[64]; + + if(!data || !width || !height || comp > 4 || comp < 1) { + return 0; + } + + quality = quality ? quality : 90; + subsample = quality <= 90 ? 1 : 0; + quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; + quality = quality < 50 ? 5000 / quality : 200 - quality * 2; + + for(i = 0; i < 64; ++i) { + int uvti, yti = (YQT[i]*quality+50)/100; + YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); + uvti = (UVQT[i]*quality+50)/100; + UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); + } + + for(row = 0, k = 0; row < 8; ++row) { + for(col = 0; col < 8; ++col, ++k) { + fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + } + } + + // Write Headers + { + static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; + static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; + const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), + 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; + s->func(s->context, (void*)head0, sizeof(head0)); + s->func(s->context, (void*)YTable, sizeof(YTable)); + stbiw__putc(s, 1); + s->func(s->context, UVTable, sizeof(UVTable)); + s->func(s->context, (void*)head1, sizeof(head1)); + s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); + s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); + stbiw__putc(s, 0x10); // HTYACinfo + s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); + s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); + stbiw__putc(s, 1); // HTUDCinfo + s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); + stbiw__putc(s, 0x11); // HTUACinfo + s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); + s->func(s->context, (void*)head2, sizeof(head2)); + } + + // Encode 8x8 macroblocks + { + static const unsigned short fillBits[] = {0x7F, 7}; + int DCY=0, DCU=0, DCV=0; + int bitBuf=0, bitCnt=0; + // comp == 2 is grey+alpha (alpha is ignored) + int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; + const unsigned char *dataR = (const unsigned char *)data; + const unsigned char *dataG = dataR + ofsG; + const unsigned char *dataB = dataR + ofsB; + int x, y, pos; + if(subsample) { + for(y = 0; y < height; y += 16) { + for(x = 0; x < width; x += 16) { + float Y[256], U[256], V[256]; + for(row = y, pos = 0; row < y+16; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+16; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + + // subsample U,V + { + float subU[64], subV[64]; + int yy, xx; + for(yy = 0, pos = 0; yy < 8; ++yy) { + for(xx = 0; xx < 8; ++xx, ++pos) { + int j = yy*32+xx*2; + subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; + subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; + } + } + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + } else { + for(y = 0; y < height; y += 8) { + for(x = 0; x < width; x += 8) { + float Y[64], U[64], V[64]; + for(row = y, pos = 0; row < y+8; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+8; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + + // Do the bit alignment of the EOI marker + stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); + } + + // EOI + stbiw__putc(s, 0xFF); + stbiw__putc(s, 0xD9); + + return 1; +} + +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); +} + + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +#endif // STB_IMAGE_WRITE_IMPLEMENTATION + +/* Revision history + 1.16 (2021-07-11) + make Deflate code emit uncompressed blocks when it would otherwise expand + support writing BMPs with alpha channel + 1.15 (2020-07-13) unknown + 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels + 1.13 + 1.12 + 1.11 (2019-08-11) + + 1.10 (2019-02-07) + support utf8 filenames in Windows; fix warnings and platform ifdefs + 1.09 (2018-02-11) + fix typo in zlib quality API, improve STB_I_W_STATIC in C++ + 1.08 (2018-01-29) + add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter + 1.07 (2017-07-24) + doc fix + 1.06 (2017-07-23) + writing JPEG (using Jon Olick's code) + 1.05 ??? + 1.04 (2017-03-03) + monochrome BMP expansion + 1.03 ??? + 1.02 (2016-04-02) + avoid allocating large structures on the stack + 1.01 (2016-01-16) + STBIW_REALLOC_SIZED: support allocators with no realloc support + avoid race-condition in crc initialization + minor compile issues + 1.00 (2015-09-14) + installable file IO function + 0.99 (2015-09-13) + warning fixes; TGA rle support + 0.98 (2015-04-08) + added STBIW_MALLOC, STBIW_ASSERT etc + 0.97 (2015-01-18) + fixed HDR asserts, rewrote HDR rle logic + 0.96 (2015-01-17) + add HDR output + fix monochrome BMP + 0.95 (2014-08-17) + add monochrome TGA output + 0.94 (2014-05-31) + rename private functions to avoid conflicts with stb_image.h + 0.93 (2014-05-27) + warning fixes + 0.92 (2010-08-01) + casts to unsigned char to fix warnings + 0.91 (2010-07-17) + first public release + 0.90 first internal 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/template/sysroot/include/gui/svg.hpp b/template/sysroot/include/gui/svg.hpp index 5b821cf..7f99a9d 100644 --- a/template/sysroot/include/gui/svg.hpp +++ b/template/sysroot/include/gui/svg.hpp @@ -123,6 +123,34 @@ struct SvgCssTable { } }; +// --------------------------------------------------------------------------- +// Integer sqrt (binary method, no floating point). +// Returns floor(sqrt(n)) for any uint64. +// --------------------------------------------------------------------------- +inline uint64_t svg_int64_sqrt(uint64_t n) { + if (n == 0) return 0; + uint64_t r = 0; + uint64_t bit = (uint64_t)1 << 62; + while (bit > n) bit >>= 2; + while (bit != 0) { + if (n >= r + bit) { + n -= r + bit; + r = (r >> 1) + bit; + } else { + r >>= 1; + } + bit >>= 2; + } + return r; +} + +// 16.16 fixed-point hypotenuse: sqrt(x*x + y*y). +inline fixed_t svg_fixed_hypot(fixed_t x, fixed_t y) { + int64_t sq = (int64_t)x * x + (int64_t)y * y; + if (sq < 0) sq = 0; + return (fixed_t)svg_int64_sqrt((uint64_t)sq); +} + // --------------------------------------------------------------------------- // Fixed-point number parser (NO floating point) // Parses strings like "3.25", "-0.5", ".1115", "16" @@ -566,6 +594,47 @@ inline void svg_path_to_edges(SvgEdgeList& el, const char* d, int dLen, *oy = fixed_mul(y - off_y, scale_y); }; + // Emit a circular arc on (cx, cy, r) from p1 to p2 by recursive + // chord-midpoint subdivision. Assumes the arc is <= 180deg; callers split + // large arcs at the far point first. Stack-based to avoid recursive lambdas. + auto emit_small_arc = [&](fixed_t cx, fixed_t cy, fixed_t r, + fixed_t p1x, fixed_t p1y, + fixed_t p2x, fixed_t p2y) { + constexpr int ARC_MAX_DEPTH = 4; // up to 16 chords per sub-arc + struct Seg { fixed_t ax, ay, bx, by; int depth; }; + Seg stk[16]; + int sp = 0; + stk[sp++] = { p1x, p1y, p2x, p2y, ARC_MAX_DEPTH }; + while (sp > 0) { + Seg s = stk[--sp]; + if (s.depth == 0) { + fixed_t sx0, sy0, sx1, sy1; + scale_pt(s.ax, s.ay, &sx0, &sy0); + scale_pt(s.bx, s.by, &sx1, &sy1); + el.add(sx0, sy0, sx1, sy1); + continue; + } + fixed_t mx = (s.ax + s.bx) / 2; + fixed_t my = (s.ay + s.by) / 2; + fixed_t vx = mx - cx; + fixed_t vy = my - cy; + fixed_t vlen = svg_fixed_hypot(vx, vy); + if (vlen == 0) { + // Degenerate: chord midpoint coincides with center. + fixed_t sx0, sy0, sx1, sy1; + scale_pt(s.ax, s.ay, &sx0, &sy0); + scale_pt(s.bx, s.by, &sx1, &sy1); + el.add(sx0, sy0, sx1, sy1); + continue; + } + fixed_t k = fixed_div(r, vlen); + fixed_t amx = cx + fixed_mul(vx, k); + fixed_t amy = cy + fixed_mul(vy, k); + stk[sp++] = { amx, amy, s.bx, s.by, s.depth - 1 }; + stk[sp++] = { s.ax, s.ay, amx, amy, s.depth - 1 }; + } + }; + while (pp.has_more()) { char cmd = '\0'; @@ -773,23 +842,90 @@ inline void svg_path_to_edges(SvgEdgeList& el, const char* d, int dLen, break; } case 'A': case 'a': { - // Arc command: consume parameters but approximate as a line - // (arcs are rare in these icons) - fixed_t rx = pp.read_number(); - fixed_t ry = pp.read_number(); - pp.read_number(); // x-rotation - pp.read_number(); // large-arc-flag - pp.read_number(); // sweep-flag + // Elliptical-arc command. We treat the arc as circular using + // r = min(|rx|, |ry|), which is exact for symbolic icons (all use + // equal axes) and a reasonable approximation otherwise. + fixed_t rx_in = pp.read_number(); + fixed_t ry_in = pp.read_number(); + pp.read_number(); // x-axis rotation (ignored) + fixed_t fa_f = pp.read_number(); // large-arc-flag + fixed_t fs_f = pp.read_number(); // sweep-flag fixed_t x = pp.read_number(); fixed_t y = pp.read_number(); if (cmd == 'a') { x += cur_x; y += cur_y; } - fixed_t sx0, sy0, sx1, sy1; - scale_pt(cur_x, cur_y, &sx0, &sy0); - scale_pt(x, y, &sx1, &sy1); - el.add(sx0, sy0, sx1, sy1); + + fixed_t r = (rx_in < 0) ? -rx_in : rx_in; + fixed_t ry_abs = (ry_in < 0) ? -ry_in : ry_in; + if (ry_abs < r) r = ry_abs; + + int fa = (fa_f != 0) ? 1 : 0; + int fs = (fs_f != 0) ? 1 : 0; + + fixed_t dx = x - cur_x; + fixed_t dy = y - cur_y; + if ((dx == 0 && dy == 0) || r == 0) { + // Per spec: degenerate arc becomes a line. + fixed_t sx0, sy0, sx1, sy1; + scale_pt(cur_x, cur_y, &sx0, &sy0); + scale_pt(x, y, &sx1, &sy1); + el.add(sx0, sy0, sx1, sy1); + cur_x = x; cur_y = y; + last_cmd = cmd; + break; + } + + // Endpoint-to-center: midpoint of chord, half-chord length, + // perpendicular height from chord to center. + fixed_t mx = cur_x + dx / 2; + fixed_t my = cur_y + dy / 2; + fixed_t half_chord = svg_fixed_hypot(dx / 2, dy / 2); + if (r < half_chord) r = half_chord; // SVG spec: snap radius up + int64_t r_sq = (int64_t)r * r; + int64_t hc_sq = (int64_t)half_chord * half_chord; + int64_t h_sq = r_sq - hc_sq; + if (h_sq < 0) h_sq = 0; + fixed_t h = (fixed_t)svg_int64_sqrt((uint64_t)h_sq); + + // Center = mid + sign * (h / chord_len) * (-dy, dx) + // sign: spec F.6.5 says -1 when fa == fs, else +1. + fixed_t chord_len = 2 * half_chord; + if (chord_len == 0) chord_len = 1; + fixed_t h_over_chord = fixed_div(h, chord_len); + int sign = (fa == fs) ? -1 : 1; + fixed_t off_x_perp = fixed_mul(-dy, h_over_chord); + fixed_t off_y_perp = fixed_mul( dx, h_over_chord); + if (sign < 0) { off_x_perp = -off_x_perp; off_y_perp = -off_y_perp; } + fixed_t cx_ctr = mx + off_x_perp; + fixed_t cy_ctr = my + off_y_perp; + + if (fa == 1) { + // Large arc: bisect at the far point (opposite side of center + // from chord midpoint), then walk each half as a small arc. + fixed_t vx = mx - cx_ctr; + fixed_t vy = my - cy_ctr; + fixed_t vlen = svg_fixed_hypot(vx, vy); + fixed_t am_x, am_y; + if (vlen == 0) { + // 180-degree arc: bisect using chord-perpendicular instead. + fixed_t k = fixed_div(r, chord_len); + fixed_t px = fixed_mul(-dy, k); + fixed_t py = fixed_mul( dx, k); + if (fs == 0) { px = -px; py = -py; } + am_x = cx_ctr + px; + am_y = cy_ctr + py; + } else { + fixed_t k = fixed_div(-r, vlen); + am_x = cx_ctr + fixed_mul(vx, k); + am_y = cy_ctr + fixed_mul(vy, k); + } + emit_small_arc(cx_ctr, cy_ctr, r, cur_x, cur_y, am_x, am_y); + emit_small_arc(cx_ctr, cy_ctr, r, am_x, am_y, x, y); + } else { + emit_small_arc(cx_ctr, cy_ctr, r, cur_x, cur_y, x, y); + } + cur_x = x; cur_y = y; last_cmd = cmd; - (void)rx; (void)ry; break; } case 'Z': case 'z': { @@ -1027,6 +1163,42 @@ inline bool svg_element_has_filter(const char* elem, int elemLen) { return svg_get_attr(elem, elemLen, " filter", buf, sizeof(buf)) > 0; } +// --------------------------------------------------------------------------- +// Parse transform="scale(x)" or transform="scale(x,y)" or translate(x,y) +// Returns true if a scale was found; sx/sy are fixed-point scale factors. +// --------------------------------------------------------------------------- +inline bool svg_get_element_scale(const char* elem, int elemLen, + fixed_t* sx, fixed_t* sy) { + char buf[64]; + if (svg_get_attr(elem, elemLen, " transform", buf, sizeof(buf)) <= 0) { + *sx = int_to_fixed(1); + *sy = int_to_fixed(1); + return false; + } + // Look for "scale(" + const char* sp = buf; + while (*sp) { + if (sp[0]=='s' && sp[1]=='c' && sp[2]=='a' && sp[3]=='l' && sp[4]=='e' && sp[5]=='(') { + sp += 6; + svg_parse_fixed(sp, sx); + // Skip to comma or closing paren + while (*sp && *sp != ',' && *sp != ')') ++sp; + if (*sp == ',') { + ++sp; + while (*sp == ' ') ++sp; + svg_parse_fixed(sp, sy); + } else { + *sy = *sx; // uniform scale + } + return true; + } + ++sp; + } + *sx = int_to_fixed(1); + *sy = int_to_fixed(1); + return false; +} + // --------------------------------------------------------------------------- // Scanline rasterizer with alpha blending (for multi-color SVGs) // --------------------------------------------------------------------------- @@ -1314,11 +1486,17 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t int alpha = svg_get_element_opacity(elem_start, elem_len); + // Per-element transform (scale) + fixed_t elem_sx, elem_sy; + svg_get_element_scale(elem_start, elem_len, &elem_sx, &elem_sy); + fixed_t eff_sx = fixed_mul(scale_x, elem_sx); + fixed_t eff_sy = fixed_mul(scale_y, elem_sy); + // Extract and rasterize path int d_len = svg_get_attr(elem_start, elem_len, " d", d_buf, SVG_MAX_PATH_LEN); if (d_len > 0) { el.clear(); - svg_path_to_edges(el, d_buf, d_len, scale_x, scale_y, vb_x, vb_y); + svg_path_to_edges(el, d_buf, d_len, eff_sx, eff_sy, vb_x, vb_y); if (el.count > 0) svg_rasterize_blend(el, icon.pixels, target_w, target_h, elem_color.to_pixel(), alpha); } @@ -1349,6 +1527,11 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t int alpha = svg_get_element_opacity(elem_start, elem_len); + fixed_t elem_sx, elem_sy; + svg_get_element_scale(elem_start, elem_len, &elem_sx, &elem_sy); + fixed_t eff_sx = fixed_mul(scale_x, elem_sx); + fixed_t eff_sy = fixed_mul(scale_y, elem_sy); + char attr_buf[32]; fixed_t cx = 0, cy = 0, r = 0; if (svg_get_attr(elem_start, elem_len, " cx", attr_buf, sizeof(attr_buf)) > 0) @@ -1358,10 +1541,10 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t if (svg_get_attr(elem_start, elem_len, " r", attr_buf, sizeof(attr_buf)) > 0) svg_parse_fixed(attr_buf, &r); - fixed_t scx = fixed_mul(cx - vb_x, scale_x); - fixed_t scy = fixed_mul(cy - vb_y, scale_y); - fixed_t srx = fixed_mul(r, scale_x); - fixed_t sry = fixed_mul(r, scale_y); + fixed_t scx = fixed_mul(cx - vb_x, eff_sx); + fixed_t scy = fixed_mul(cy - vb_y, eff_sy); + fixed_t srx = fixed_mul(r, eff_sx); + fixed_t sry = fixed_mul(r, eff_sy); fixed_t sr = (srx + sry) >> 1; el.clear(); @@ -1395,6 +1578,11 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t int alpha = svg_get_element_opacity(elem_start, elem_len); + fixed_t elem_sx, elem_sy; + svg_get_element_scale(elem_start, elem_len, &elem_sx, &elem_sy); + fixed_t eff_sx = fixed_mul(scale_x, elem_sx); + fixed_t eff_sy = fixed_mul(scale_y, elem_sy); + char attr_buf[32]; fixed_t rx_val = 0, ry_val = 0, rw = 0, rh = 0, rrx = 0, rry = 0; @@ -1411,12 +1599,12 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t if (svg_get_attr(elem_start, elem_len, " ry", attr_buf, sizeof(attr_buf)) > 0) svg_parse_fixed(attr_buf, &rry); - fixed_t sx = fixed_mul(rx_val - vb_x, scale_x); - fixed_t sy = fixed_mul(ry_val - vb_y, scale_y); - fixed_t sw = fixed_mul(rw, scale_x); - fixed_t sh = fixed_mul(rh, scale_y); - fixed_t srx = fixed_mul(rrx, scale_x); - fixed_t sry = fixed_mul(rry, scale_y); + fixed_t sx = fixed_mul(rx_val - vb_x, eff_sx); + fixed_t sy = fixed_mul(ry_val - vb_y, eff_sy); + fixed_t sw = fixed_mul(rw, eff_sx); + fixed_t sh = fixed_mul(rh, eff_sy); + fixed_t srx = fixed_mul(rrx, eff_sx); + fixed_t sry = fixed_mul(rry, eff_sy); el.clear(); svg_rect_edges(el, sx, sy, sw, sh, srx, sry); @@ -1438,6 +1626,46 @@ inline SvgIcon svg_render(const char* svg_data, int svg_len, int target_w, int t // --------------------------------------------------------------------------- // Load SVG from VFS and render // --------------------------------------------------------------------------- +// Extract intrinsic dimensions from an SVG document. Prefers width/height +// attributes, falls back to viewBox, then to a 256x256 default. Used by the +// image viewer to render SVGs at their natural size rather than a fixed icon +// size. +inline void svg_get_natural_size(const char* svg_data, int svg_len, + int* out_w, int* out_h) { + int w = 0, h = 0; + const char* svg_tag = svg_strstr(svg_data, svg_len, " 0) + w = svg_parse_int(attr_buf); + if (svg_get_attr(svg_tag, tag_len, " height", attr_buf, sizeof(attr_buf)) > 0) + h = svg_parse_int(attr_buf); + + if ((w <= 0 || h <= 0) && + svg_get_attr(svg_tag, tag_len, " viewBox", attr_buf, sizeof(attr_buf)) > 0) { + fixed_t vbx, vby, vbw, vbh; + const char* vp = attr_buf; + int c; + c = svg_parse_fixed(vp, &vbx); vp += c; while (*vp && svg_char_is_sep(*vp)) ++vp; + c = svg_parse_fixed(vp, &vby); vp += c; while (*vp && svg_char_is_sep(*vp)) ++vp; + c = svg_parse_fixed(vp, &vbw); vp += c; while (*vp && svg_char_is_sep(*vp)) ++vp; + svg_parse_fixed(vp, &vbh); + (void)vbx; (void)vby; + if (w <= 0) w = fixed_to_int(vbw); + if (h <= 0) h = fixed_to_int(vbh); + } + } + if (w <= 0) w = 256; + if (h <= 0) h = 256; + if (out_w) *out_w = w; + if (out_h) *out_h = h; +} + inline SvgIcon svg_load(const char* vfs_path, int target_w, int target_h, Color fill_color) { int fd = montauk::open(vfs_path); if (fd < 0) { diff --git a/template/sysroot/include/gui/truetype.hpp b/template/sysroot/include/gui/truetype.hpp index 7706763..90ac56c 100644 --- a/template/sysroot/include/gui/truetype.hpp +++ b/template/sysroot/include/gui/truetype.hpp @@ -41,6 +41,41 @@ namespace gui { +inline int decode_single_byte_codepoint(int codepoint) { + if (codepoint < 0 || codepoint > 255) return codepoint; + + switch (codepoint) { + case 0x80: return 0x20AC; // Euro Sign + case 0x82: return 0x201A; // Single Low-9 Quotation Mark + case 0x83: return 0x0192; // Latin Small Letter F With Hook + case 0x84: return 0x201E; // Double Low-9 Quotation Mark + case 0x85: return 0x2026; // Horizontal Ellipsis + case 0x86: return 0x2020; // Dagger + case 0x87: return 0x2021; // Double Dagger + case 0x88: return 0x02C6; // Modifier Letter Circumflex Accent + case 0x89: return 0x2030; // Per Mille Sign + case 0x8A: return 0x0160; // Latin Capital Letter S With Caron + case 0x8B: return 0x2039; // Single Left-Pointing Angle Quotation Mark + case 0x8C: return 0x0152; // Latin Capital Ligature OE + case 0x8E: return 0x017D; // Latin Capital Letter Z With Caron + case 0x91: return 0x2018; // Left Single Quotation Mark + case 0x92: return 0x2019; // Right Single Quotation Mark + case 0x93: return 0x201C; // Left Double Quotation Mark + case 0x94: return 0x201D; // Right Double Quotation Mark + case 0x95: return 0x2022; // Bullet + case 0x96: return 0x2013; // En Dash + case 0x97: return 0x2014; // Em Dash + case 0x98: return 0x02DC; // Small Tilde + case 0x99: return 0x2122; // Trade Mark Sign + case 0x9A: return 0x0161; // Latin Small Letter S With Caron + case 0x9B: return 0x203A; // Single Right-Pointing Angle Quotation Mark + case 0x9C: return 0x0153; // Latin Small Ligature OE + case 0x9E: return 0x017E; // Latin Small Letter Z With Caron + case 0x9F: return 0x0178; // Latin Capital Letter Y With Diaeresis + default: return codepoint; + } +} + struct CachedGlyph { uint8_t* bitmap; int width, height; @@ -50,7 +85,7 @@ struct CachedGlyph { }; struct GlyphCache { - CachedGlyph glyphs[256]; // Latin-1 Supplement (U+0080..U+00FF) included + CachedGlyph glyphs[256]; // Single-byte text with Windows-1252 punctuation mapping int pixel_size; float scale; int ascent, descent, line_gap; @@ -155,12 +190,13 @@ struct TrueTypeFont { if (g->loaded) return g; g->loaded = true; + int font_codepoint = decode_single_byte_codepoint(codepoint); int advance, lsb; - stbtt_GetCodepointHMetrics(&info, codepoint, &advance, &lsb); + stbtt_GetCodepointHMetrics(&info, font_codepoint, &advance, &lsb); g->advance = (int)(advance * gc->scale); int x0, y0, x1, y1; - stbtt_GetCodepointBitmapBox(&info, codepoint, gc->scale, gc->scale, + stbtt_GetCodepointBitmapBox(&info, font_codepoint, gc->scale, gc->scale, &x0, &y0, &x1, &y1); g->width = x1 - x0; g->height = y1 - y0; @@ -169,8 +205,10 @@ struct TrueTypeFont { if (g->width > 0 && g->height > 0) { g->bitmap = (uint8_t*)montauk::malloc(g->width * g->height); + if (!g->bitmap) + return g; stbtt_MakeCodepointBitmap(&info, g->bitmap, g->width, g->height, - g->width, gc->scale, gc->scale, codepoint); + g->width, gc->scale, gc->scale, font_codepoint); } return g; @@ -199,6 +237,13 @@ struct TrueTypeFont { GlyphCache* gc = get_cache(pixel_size); int cx = x; int baseline = y + gc->ascent; + int fb_w = fb.width(); + int fb_h = fb.height(); + int fb_pitch = fb.pitch(); + uint32_t* fb_pixels = fb.buffer(); + if (!fb_pixels) return; + uint32_t src_rgb = 0xFF000000 | ((uint32_t)color.r << 16) | + ((uint32_t)color.g << 8) | color.b; for (int i = 0; text[i]; i++) { CachedGlyph* g = get_glyph(gc, (unsigned char)text[i]); @@ -207,12 +252,41 @@ struct TrueTypeFont { if (g->bitmap) { int gx = cx + g->xoff; int gy = baseline + g->yoff; - for (int row = 0; row < g->height; row++) { - for (int col = 0; col < g->width; col++) { - uint8_t alpha = g->bitmap[row * g->width + col]; - if (alpha > 0) { - Color c = {color.r, color.g, color.b, alpha}; - fb.put_pixel_alpha(gx + col, gy + row, c); + + int row0 = gy < 0 ? -gy : 0; + int col0 = gx < 0 ? -gx : 0; + int row1 = gy + g->height > fb_h ? fb_h - gy : g->height; + int col1 = gx + g->width > fb_w ? fb_w - gx : g->width; + + if (row0 < row1 && col0 < col1) { + for (int row = row0; row < row1; row++) { + uint8_t* alpha_row = g->bitmap + row * g->width + col0; + uint32_t* dst = (uint32_t*)((uint8_t*)fb_pixels + (gy + row) * fb_pitch) + gx + col0; + + for (int col = col0; col < col1; col++) { + uint8_t alpha = *alpha_row++; + if (alpha == 0) { + dst++; + continue; + } + if (alpha == 255) { + *dst++ = src_rgb; + continue; + } + + uint32_t d = *dst; + uint32_t inv_a = 255 - alpha; + uint32_t dr = (d >> 16) & 0xFF; + uint32_t dg = (d >> 8) & 0xFF; + uint32_t db = d & 0xFF; + uint32_t rr = alpha * color.r + inv_a * dr; + uint32_t gg = alpha * color.g + inv_a * dg; + uint32_t bb = alpha * color.b + inv_a * db; + + rr = (rr + 1 + (rr >> 8)) >> 8; + gg = (gg + 1 + (gg >> 8)) >> 8; + bb = (bb + 1 + (bb >> 8)) >> 8; + *dst++ = 0xFF000000 | (rr << 16) | (gg << 8) | bb; } } } @@ -389,6 +463,7 @@ namespace fonts { inline bool init() { auto load = [](const char* path) -> TrueTypeFont* { TrueTypeFont* f = (TrueTypeFont*)montauk::malloc(sizeof(TrueTypeFont)); + if (!f) return nullptr; montauk::memset(f, 0, sizeof(TrueTypeFont)); if (!f->init(path)) { montauk::mfree(f); diff --git a/template/sysroot/include/http/http.hpp b/template/sysroot/include/http/http.hpp index 8a10eb5..e8f87ec 100644 --- a/template/sysroot/include/http/http.hpp +++ b/template/sysroot/include/http/http.hpp @@ -27,7 +27,64 @@ struct Response { int raw_len; }; +inline const char* find_header_block_end(const char* start, const char* end) { + if (!start || !end || start >= end) return nullptr; + + for (const char* s = start; s < end - 3; s++) { + if (s[0] == '\r' && s[1] == '\n' && s[2] == '\r' && s[3] == '\n') + return s + 4; + } + for (const char* s = start; s < end - 1; s++) { + if (s[0] == '\n' && s[1] == '\n') + return s + 2; + } + return nullptr; +} + +inline int parse_status_code(const char* start, const char* end) { + if (!start || !end || end - start < 12) return -1; + + const char* p = start; + while (p < end && *p && *p != ' ') p++; + if (p >= end || *p != ' ') return -1; + p++; + + int code = 0; + int digits = 0; + while (digits < 3 && p < end && *p >= '0' && *p <= '9') { + code = code * 10 + (*p - '0'); + p++; + digits++; + } + return digits == 3 ? code : -1; +} + +inline const char* find_final_response_start(const char* buf, int len) { + if (!buf || len <= 0) return nullptr; + + const char* start = buf; + const char* end = buf + len; + for (;;) { + int code = parse_status_code(start, end); + if (code < 0) return nullptr; + if (code < 100 || code >= 200) return start; + + const char* next = find_header_block_end(start, end); + if (!next || next >= end) return nullptr; + if (end - next < 5) return nullptr; + if (!(next[0] == 'H' && next[1] == 'T' && next[2] == 'T' && next[3] == 'P' && next[4] == '/')) + return nullptr; + start = next; + } +} + +inline const char* skip_informational_responses(const char* buf, int len) { + const char* start = find_final_response_start(buf, len); + return start ? start : buf; +} + // Parse raw HTTP response in-place. Sets pointers into buf (does not copy). +// Skips leading informational 1xx responses such as "100 Continue". // Returns status code, or -1 if unparseable. inline int parse_response(char* buf, int len, Response* out) { out->raw = buf; @@ -38,21 +95,18 @@ inline int parse_response(char* buf, int len, Response* out) { out->body = nullptr; out->body_len = 0; - if (len < 12) return -1; // "HTTP/1.x NNN" + const char* start = find_final_response_start(buf, len); + const char* end = buf + len; + if (!start || end - start < 12) return -1; // "HTTP/1.x NNN" // Parse status code from "HTTP/1.x NNN" - const char* p = buf; - while (*p && *p != ' ') p++; - if (*p != ' ') return -1; - p++; - int code = 0; - for (int i = 0; i < 3 && *p >= '0' && *p <= '9'; i++, p++) - code = code * 10 + (*p - '0'); + int code = parse_status_code(start, end); + if (code < 0) return -1; out->status = code; // Headers start after the status line - const char* hdr_start = buf; - while (hdr_start < buf + len - 1) { + const char* hdr_start = start; + while (hdr_start < end - 1) { if (*hdr_start == '\r' && *(hdr_start + 1) == '\n') { hdr_start += 2; break; } if (*hdr_start == '\n') { hdr_start++; break; } hdr_start++; @@ -60,14 +114,21 @@ inline int parse_response(char* buf, int len, Response* out) { out->headers = hdr_start; // Find \r\n\r\n boundary between headers and body - for (const char* s = hdr_start; s < buf + len - 3; s++) { - if (s[0] == '\r' && s[1] == '\n' && s[2] == '\r' && s[3] == '\n') { - out->headers_len = (int)(s - hdr_start); - out->body = s + 4; - out->body_len = len - (int)(out->body - buf); - return code; - } + const char* body = find_header_block_end(hdr_start, end); + if (body) { + if (body >= hdr_start + 4 && + body[-4] == '\r' && body[-3] == '\n' && body[-2] == '\r' && body[-1] == '\n') + out->headers_len = (int)((body - 4) - hdr_start); + else if (body >= hdr_start + 2 && + body[-2] == '\n' && body[-1] == '\n') + out->headers_len = (int)((body - 2) - hdr_start); + else + out->headers_len = (int)(body - hdr_start); + out->body = body; + out->body_len = len - (int)(out->body - buf); + return code; } + // No body separator found — entire remainder is headers out->headers_len = len - (int)(hdr_start - buf); return code; diff --git a/template/sysroot/include/libc/montauk.h b/template/sysroot/include/libc/montauk.h index 967c0d1..c51addd 100644 --- a/template/sysroot/include/libc/montauk.h +++ b/template/sysroot/include/libc/montauk.h @@ -79,6 +79,7 @@ extern "C" { #define MTK_SYS_WINPOLL 57 #define MTK_SYS_WINENUM 58 #define MTK_SYS_WINMAP 59 +#define MTK_SYS_WINUNMAP 97 #define MTK_SYS_WINSENDEVENT 60 #define MTK_SYS_PROCLIST 61 #define MTK_SYS_KILL 62 @@ -101,9 +102,30 @@ extern "C" { #define MTK_SYS_GETTZ 91 #define MTK_SYS_GETCWD 95 #define MTK_SYS_CHDIR 96 +#define MTK_SYS_DUPHANDLE 98 +#define MTK_SYS_WAIT_HANDLE 99 +#define MTK_SYS_STREAM_CREATE 100 +#define MTK_SYS_STREAM_READ 101 +#define MTK_SYS_STREAM_WRITE 102 +#define MTK_SYS_MAILBOX_CREATE 103 +#define MTK_SYS_MAILBOX_SEND 104 +#define MTK_SYS_MAILBOX_RECV 105 +#define MTK_SYS_WAITSET_CREATE 106 +#define MTK_SYS_WAITSET_ADD 107 +#define MTK_SYS_WAITSET_REMOVE 108 +#define MTK_SYS_WAITSET_WAIT 109 +#define MTK_SYS_PROC_OPEN 110 +#define MTK_SYS_SURFACE_CREATE 111 +#define MTK_SYS_SURFACE_MAP 112 +#define MTK_SYS_SURFACE_RESIZE 113 #define MTK_SOCK_TCP 1 #define MTK_SOCK_UDP 2 +#define MTK_IPC_SIGNAL_READABLE (1u << 0) +#define MTK_IPC_SIGNAL_WRITABLE (1u << 1) +#define MTK_IPC_SIGNAL_PEER_CLOSED (1u << 2) +#define MTK_IPC_SIGNAL_EXITED (1u << 3) +#define MTK_IPC_SIGNAL_READY (1u << 4) /* Window event types */ #define MTK_EVENT_KEY 0 @@ -140,6 +162,11 @@ typedef struct { uint8_t buttons; } mtk_mouse_state; +typedef struct { + int32_t index; + uint32_t signals; +} mtk_ipc_wait_result; + typedef struct { uint8_t type; uint8_t _pad[3]; @@ -402,6 +429,78 @@ static inline int mtk_readdir(const char *path, const char **names, int max) { return (int)_mtk_syscall3(MTK_SYS_READDIR, (long)path, (long)names, (long)max); } +/* ==================================================================== + Generic IPC + ==================================================================== */ + +static inline int mtk_dup_handle(int handle) { + return (int)_mtk_syscall1(MTK_SYS_DUPHANDLE, (long)handle); +} + +static inline uint32_t mtk_wait_handle(int handle, uint32_t wanted_signals, unsigned long timeout_ms) { + return (uint32_t)_mtk_syscall3(MTK_SYS_WAIT_HANDLE, (long)handle, (long)wanted_signals, (long)timeout_ms); +} + +static inline int mtk_stream_create(int *out_read_handle, int *out_write_handle, unsigned long capacity) { + return (int)_mtk_syscall3(MTK_SYS_STREAM_CREATE, (long)out_read_handle, (long)out_write_handle, (long)capacity); +} + +static inline int mtk_stream_read(int handle, void *buf, int max_len) { + return (int)_mtk_syscall3(MTK_SYS_STREAM_READ, (long)handle, (long)buf, (long)max_len); +} + +static inline int mtk_stream_write(int handle, const void *data, int len) { + return (int)_mtk_syscall3(MTK_SYS_STREAM_WRITE, (long)handle, (long)data, (long)len); +} + +static inline int mtk_mailbox_create(int *out_send_handle, int *out_recv_handle) { + return (int)_mtk_syscall2(MTK_SYS_MAILBOX_CREATE, (long)out_send_handle, (long)out_recv_handle); +} + +static inline int mtk_mailbox_send(int handle, uint32_t msg_type, const void *data, + uint16_t len, int attach_handle) { + return (int)_mtk_syscall5(MTK_SYS_MAILBOX_SEND, (long)handle, (long)msg_type, + (long)data, (long)len, (long)attach_handle); +} + +static inline int mtk_mailbox_recv(int handle, uint32_t *out_msg_type, void *data, + uint16_t *in_out_len, int *out_attach_handle) { + return (int)_mtk_syscall5(MTK_SYS_MAILBOX_RECV, (long)handle, (long)out_msg_type, + (long)data, (long)in_out_len, (long)out_attach_handle); +} + +static inline int mtk_waitset_create(void) { + return (int)_mtk_syscall0(MTK_SYS_WAITSET_CREATE); +} + +static inline int mtk_waitset_add(int waitset_handle, int target_handle, uint32_t signals) { + return (int)_mtk_syscall3(MTK_SYS_WAITSET_ADD, (long)waitset_handle, (long)target_handle, (long)signals); +} + +static inline int mtk_waitset_remove(int waitset_handle, int index) { + return (int)_mtk_syscall2(MTK_SYS_WAITSET_REMOVE, (long)waitset_handle, (long)index); +} + +static inline int mtk_waitset_wait(int waitset_handle, mtk_ipc_wait_result *out_ready, unsigned long timeout_ms) { + return (int)_mtk_syscall3(MTK_SYS_WAITSET_WAIT, (long)waitset_handle, (long)out_ready, (long)timeout_ms); +} + +static inline int mtk_proc_open(int pid) { + return (int)_mtk_syscall1(MTK_SYS_PROC_OPEN, (long)pid); +} + +static inline int mtk_surface_create(unsigned long byte_size) { + return (int)_mtk_syscall1(MTK_SYS_SURFACE_CREATE, (long)byte_size); +} + +static inline void *mtk_surface_map(int handle) { + return (void *)_mtk_syscall1(MTK_SYS_SURFACE_MAP, (long)handle); +} + +static inline int mtk_surface_resize(int handle, unsigned long new_size) { + return (int)_mtk_syscall2(MTK_SYS_SURFACE_RESIZE, (long)handle, (long)new_size); +} + /* ==================================================================== Memory ==================================================================== */ @@ -484,6 +583,10 @@ static inline int mtk_win_poll(int id, mtk_win_event *event) { return (int)_mtk_syscall2(MTK_SYS_WINPOLL, (long)id, (long)event); } +static inline int mtk_win_unmap(int id) { + return (int)_mtk_syscall1(MTK_SYS_WINUNMAP, (long)id); +} + static inline unsigned long mtk_win_resize(int id, int w, int h) { return (unsigned long)_mtk_syscall3(MTK_SYS_WINRESIZE, (long)id, (long)w, (long)h); } @@ -492,6 +595,10 @@ static inline int mtk_win_enumerate(mtk_win_info *info, int max) { return (int)_mtk_syscall2(MTK_SYS_WINENUM, (long)info, (long)max); } +static inline unsigned long mtk_win_map(int id) { + return (unsigned long)_mtk_syscall1(MTK_SYS_WINMAP, (long)id); +} + static inline int mtk_win_setcursor(int id, int cursor) { return (int)_mtk_syscall2(MTK_SYS_WINSETCURSOR, (long)id, (long)cursor); } diff --git a/template/sysroot/include/libloader/libloader.h b/template/sysroot/include/libloader/libloader.h new file mode 100644 index 0000000..ba19d52 --- /dev/null +++ b/template/sysroot/include/libloader/libloader.h @@ -0,0 +1,34 @@ +/* + * libloader.h + * Dynamic library loading interface for MontaukOS + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include + +// Library handle - opaque to users +struct LibHandle { + int handle; // syscall handle (slot + 1) + uint64_t base; // relocation base / load bias for symbol values + char path[256]; +}; + +namespace libloader { + +// Maximum libraries that can be loaded per process +static constexpr int MaxLoadedLibs = 8; + +// Load a shared library. +// Returns a LibHandle* on success, or nullptr on failure. +LibHandle* dlopen(const char* path); + +// Look up a symbol in a loaded library. +// Returns the function/data pointer, or nullptr if not found. +void* dlsym(LibHandle* lib, const char* symbolName); + +// Unload a library. +// Returns 0 on success, -1 on failure. +int dlclose(LibHandle* lib); + +} // namespace libloader diff --git a/template/sysroot/include/montauk/heap.h b/template/sysroot/include/montauk/heap.h index 283eeac..87ca143 100644 --- a/template/sysroot/include/montauk/heap.h +++ b/template/sysroot/include/montauk/heap.h @@ -37,6 +37,22 @@ namespace heap_detail { inline FreeNode g_overflow{0, nullptr}; inline bool g_initialized = false; + // Process-wide heap lock. Userspace threads share the heap, so the + // public malloc/mfree/realloc entry points must serialize access to + // g_buckets/g_overflow. Kept inline here (not in thread.h) because + // thread.h depends on heap.h, and the internal helpers below are not + // reentrant into the public API, so a plain spinlock suffices. + inline volatile uint32_t g_heap_lock = 0; + + static inline void heap_lock_acquire() { + while (__atomic_exchange_n(&g_heap_lock, 1, __ATOMIC_ACQUIRE) != 0) { + syscall0(Montauk::SYS_YIELD); + } + } + static inline void heap_lock_release() { + __atomic_store_n(&g_heap_lock, 0, __ATOMIC_RELEASE); + } + static inline Header* get_header(void* block) { return (Header*)((uint8_t*)block - sizeof(Header)); } @@ -146,15 +162,17 @@ namespace heap_detail { inline void* malloc(uint64_t size) { using namespace heap_detail; + // Guard against overflow: size + Header must not wrap + if (size > UINT64_MAX - sizeof(Header) - 15) + return nullptr; + + heap_lock_acquire(); + if (!g_initialized) { grow(16 * 0x1000); // seed with 64 KiB g_initialized = true; } - // Guard against overflow: size + Header must not wrap - if (size > UINT64_MAX - sizeof(Header) - 15) - return nullptr; - uint64_t needed = size + sizeof(Header); needed = (needed + 15) & ~15ULL; @@ -162,8 +180,10 @@ namespace heap_detail { if (idx >= 0) { // Small allocation — use segregated bucket (O(1)) - if (g_buckets[idx] == nullptr && !refill_bucket(idx)) + if (g_buckets[idx] == nullptr && !refill_bucket(idx)) { + heap_lock_release(); return nullptr; + } FreeNode* node = g_buckets[idx]; g_buckets[idx] = node->next; @@ -171,20 +191,22 @@ namespace heap_detail { Header* header = (Header*)node; header->magic = HEADER_MAGIC; header->size = size; + heap_lock_release(); return (void*)((uint8_t*)header + sizeof(Header)); } // Large allocation — search overflow list void* block = take_from_overflow(needed); if (block == nullptr) { - if (!grow(needed)) return nullptr; + if (!grow(needed)) { heap_lock_release(); return nullptr; } block = take_from_overflow(needed); - if (block == nullptr) return nullptr; + if (block == nullptr) { heap_lock_release(); return nullptr; } } Header* header = (Header*)block; header->magic = HEADER_MAGIC; header->size = size; + heap_lock_release(); return (void*)((uint8_t*)header + sizeof(Header)); } @@ -195,8 +217,10 @@ namespace heap_detail { Header* header = get_header(ptr); - if (header->magic == FREED_MAGIC) return; // double-free - if (header->magic != HEADER_MAGIC) return; // corrupt + heap_lock_acquire(); + + if (header->magic == FREED_MAGIC) { heap_lock_release(); return; } // double-free + if (header->magic != HEADER_MAGIC) { heap_lock_release(); return; } // corrupt header->magic = FREED_MAGIC; uint64_t blockSize = header->size + sizeof(Header); @@ -214,15 +238,18 @@ namespace heap_detail { // Large block — sorted insert with coalescing insert_overflow((void*)header, blockSize); } + heap_lock_release(); } inline void* realloc(void* ptr, uint64_t size) { if (ptr == nullptr) return malloc(size); + // Read old size under the lock to avoid racing with another + // thread that might be freeing/recycling this header. + heap_detail::heap_lock_acquire(); auto* header = heap_detail::get_header(ptr); uint64_t old = header->size; - // Compute actual block size (accounting for bucket rounding) uint64_t oldBlock = (old + sizeof(heap_detail::Header) + 15) & ~15ULL; int idx = heap_detail::bucket_index(oldBlock); if (idx >= 0) oldBlock = heap_detail::BUCKET_SIZES[idx]; @@ -230,8 +257,10 @@ namespace heap_detail { uint64_t newNeed = (size + sizeof(heap_detail::Header) + 15) & ~15ULL; if (newNeed <= oldBlock) { header->size = size; + heap_detail::heap_lock_release(); return ptr; } + heap_detail::heap_lock_release(); void* newBlock = malloc(size); if (newBlock == nullptr) return nullptr; diff --git a/template/sysroot/include/montauk/syscall.h b/template/sysroot/include/montauk/syscall.h index ae0eba1..96b2cb2 100644 --- a/template/sysroot/include/montauk/syscall.h +++ b/template/sysroot/include/montauk/syscall.h @@ -120,6 +120,12 @@ namespace montauk { inline int spawn(const char* path, const char* args = nullptr) { return (int)syscall2(Montauk::SYS_SPAWN, (uint64_t)path, (uint64_t)args); } + inline int chdir(const char* path) { + return (int)syscall1(Montauk::SYS_CHDIR, (uint64_t)path); + } + inline int getcwd(char* buf, uint64_t maxLen) { + return (int)syscall2(Montauk::SYS_GETCWD, (uint64_t)buf, maxLen); + } // Console inline void print(const char* text) { syscall1(Montauk::SYS_PRINT, (uint64_t)text); } @@ -135,6 +141,13 @@ namespace montauk { inline int readdir(const char* path, const char** names, int max) { return (int)syscall3(Montauk::SYS_READDIR, (uint64_t)path, (uint64_t)names, (uint64_t)max); } + // Paginated directory read: returns entries [startIndex, startIndex+max). + // Call repeatedly with increasing startIndex (advancing by the returned + // count) until it returns 0 to enumerate directories of any size. + inline int readdir_at(const char* path, const char** names, int max, int startIndex) { + return (int)syscall4(Montauk::SYS_READDIR_AT, (uint64_t)path, (uint64_t)names, + (uint64_t)max, (uint64_t)startIndex); + } // File write/create inline int fwrite(int handle, const uint8_t* buf, uint64_t off, uint64_t size) { @@ -149,12 +162,20 @@ namespace montauk { inline int fmkdir(const char* path) { return (int)syscall1(Montauk::SYS_FMKDIR, (uint64_t)path); } + inline int frename(const char* oldPath, const char* newPath) { + return (int)syscall2(Montauk::SYS_FRENAME, (uint64_t)oldPath, (uint64_t)newPath); + } inline int drivelist(int* outDrives, int max) { return (int)syscall2(Montauk::SYS_DRIVELIST, (uint64_t)outDrives, (uint64_t)max); } inline int drivelabel(int drive, char* outLabel, int maxLen) { return (int)syscall3(Montauk::SYS_DRIVELABEL, (uint64_t)drive, (uint64_t)outLabel, (uint64_t)maxLen); } + // Returns the kernel BlockDeviceKind backing the drive: 0=unknown/ramdisk, + // 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC. + inline int drivekind(int drive) { + return (int)syscall1(Montauk::SYS_DRIVEKIND, (uint64_t)drive); + } // Memory inline void* alloc(uint64_t size) { return (void*)syscall1(Montauk::SYS_ALLOC, size); } @@ -171,6 +192,9 @@ namespace montauk { inline bool is_key_available() { return (bool)syscall0(Montauk::SYS_ISKEYAVAILABLE); } inline void getkey(Montauk::KeyEvent* out) { syscall1(Montauk::SYS_GETKEY, (uint64_t)out); } inline char getchar() { return (char)syscall0(Montauk::SYS_GETCHAR); } + inline uint64_t input_wait(uint64_t observedSerial, uint64_t timeoutMs) { + return (uint64_t)syscall2(Montauk::SYS_INPUT_WAIT, observedSerial, timeoutMs); + } // Networking inline int32_t ping(uint32_t ip, uint32_t timeoutMs = 3000) { @@ -221,6 +245,81 @@ namespace montauk { (uint64_t)maxLen, (uint64_t)srcIp, (uint64_t)srcPort); } + // Generic IPC + inline int dup_handle(int handle) { + return (int)syscall1(Montauk::SYS_DUPHANDLE, (uint64_t)handle); + } + inline uint32_t wait_handle(int handle, uint32_t wantedSignals, uint64_t timeoutMs = ~0ULL) { + return (uint32_t)syscall3(Montauk::SYS_WAIT_HANDLE, (uint64_t)handle, + (uint64_t)wantedSignals, timeoutMs); + } + inline int stream_create(int* outReadHandle, int* outWriteHandle, uint32_t capacity = 0) { + return (int)syscall3(Montauk::SYS_STREAM_CREATE, (uint64_t)outReadHandle, + (uint64_t)outWriteHandle, (uint64_t)capacity); + } + inline int stream_read(int handle, void* buf, int maxLen) { + return (int)syscall3(Montauk::SYS_STREAM_READ, (uint64_t)handle, (uint64_t)buf, (uint64_t)maxLen); + } + inline int stream_write(int handle, const void* data, int len) { + return (int)syscall3(Montauk::SYS_STREAM_WRITE, (uint64_t)handle, (uint64_t)data, (uint64_t)len); + } + inline int mailbox_create(int* outSendHandle, int* outRecvHandle) { + return (int)syscall2(Montauk::SYS_MAILBOX_CREATE, (uint64_t)outSendHandle, (uint64_t)outRecvHandle); + } + inline int mailbox_send(int handle, uint32_t msgType, const void* data, uint16_t len, int attachHandle = -1) { + return (int)syscall5(Montauk::SYS_MAILBOX_SEND, (uint64_t)handle, (uint64_t)msgType, + (uint64_t)data, (uint64_t)len, (uint64_t)(int64_t)attachHandle); + } + inline int mailbox_recv(int handle, uint32_t* outMsgType, void* data, + uint16_t* inOutLen, int* outAttachHandle = nullptr) { + return (int)syscall5(Montauk::SYS_MAILBOX_RECV, (uint64_t)handle, (uint64_t)outMsgType, + (uint64_t)data, (uint64_t)inOutLen, (uint64_t)outAttachHandle); + } + inline int waitset_create() { + return (int)syscall0(Montauk::SYS_WAITSET_CREATE); + } + inline int waitset_add(int waitsetHandle, int targetHandle, uint32_t signals) { + return (int)syscall3(Montauk::SYS_WAITSET_ADD, (uint64_t)waitsetHandle, + (uint64_t)targetHandle, (uint64_t)signals); + } + inline int waitset_remove(int waitsetHandle, int index) { + return (int)syscall2(Montauk::SYS_WAITSET_REMOVE, (uint64_t)waitsetHandle, (uint64_t)index); + } + inline int waitset_wait(int waitsetHandle, Montauk::IpcWaitResult* outReady, uint64_t timeoutMs = ~0ULL) { + return (int)syscall3(Montauk::SYS_WAITSET_WAIT, (uint64_t)waitsetHandle, (uint64_t)outReady, timeoutMs); + } + inline int proc_open(int pid) { + return (int)syscall1(Montauk::SYS_PROC_OPEN, (uint64_t)pid); + } + inline int surface_create(uint64_t byteSize) { + return (int)syscall1(Montauk::SYS_SURFACE_CREATE, byteSize); + } + inline void* surface_map(int handle) { + return (void*)syscall1(Montauk::SYS_SURFACE_MAP, (uint64_t)handle); + } + inline int surface_resize(int handle, uint64_t newSize) { + return (int)syscall2(Montauk::SYS_SURFACE_RESIZE, (uint64_t)handle, newSize); + } + + // Shared library support + inline int load_lib(const char* path) { + return (int)syscall1(Montauk::SYS_LOAD_LIB, (uint64_t)path); + } + inline int unload_lib(int handle) { + return (int)syscall1(Montauk::SYS_UNLOAD_LIB, (uint64_t)handle); + } + inline void* dlsym(int handle, uint64_t symbolOffset) { + return (void*)syscall2(Montauk::SYS_DLSYM, (uint64_t)handle, symbolOffset); + } + inline uint64_t get_libbase(int handle) { + return (uint64_t)syscall1(Montauk::SYS_GETLIBBASE, (uint64_t)handle); + } + + // Crash report retrieval + inline int crash_report(Montauk::CrashReportInfo* out) { + return (int)syscall1(Montauk::SYS_CRASH_REPORT, (uint64_t)out); + } + // Process management inline void waitpid(int pid) { syscall1(Montauk::SYS_WAITPID, (uint64_t)pid); } @@ -273,6 +372,19 @@ namespace montauk { __builtin_unreachable(); } + inline int suspend() { + return (int)syscall0(Montauk::SYS_SUSPEND); + } + + // Graceful power-off request channel. The desktop posts a pending action + // (Montauk::POWER_REQ_SHUTDOWN / POWER_REQ_REBOOT) then exits; login.elf + // reads it with POWER_REQ_QUERY (read-and-clear), runs the shutdown stages, + // and finally calls shutdown()/reset(). Returns the pending action for a + // query, or 0 when posting one. + inline int power_request(int action) { + return (int)syscall1(Montauk::SYS_POWER_REQUEST, (uint64_t)(int64_t)action); + } + // Mouse inline void mouse_state(Montauk::MouseState* out) { syscall1(Montauk::SYS_MOUSESTATE, (uint64_t)out); } inline void set_mouse_bounds(int32_t maxX, int32_t maxY) { @@ -340,6 +452,11 @@ namespace montauk { inline int fs_mount(int partIndex, int driveNum) { return (int)syscall2(Montauk::SYS_FSMOUNT, (uint64_t)partIndex, (uint64_t)driveNum); } + // Flush all block-device write caches and cleanly unmount disk-backed + // volumes ahead of power-off. Returns the number of volumes unmounted. + inline int fs_sync() { + return (int)syscall0(Montauk::SYS_FS_SYNC); + } inline int fs_format(const Montauk::FsFormatParams* params) { return (int)syscall1(Montauk::SYS_FSFORMAT, (uint64_t)params); } @@ -381,6 +498,33 @@ namespace montauk { inline int audio_bt_status(int handle) { return audio_ctl(handle, Montauk::AUDIO_CTL_BT_STATUS, 0); } + inline int audio_set_master_volume(int percent) { + return audio_ctl(-1, Montauk::AUDIO_CTL_SET_MASTER_VOLUME, percent); + } + inline int audio_get_master_volume() { + return audio_ctl(-1, Montauk::AUDIO_CTL_GET_MASTER_VOLUME, 0); + } + inline int audio_set_master_mute(bool muted) { + return audio_ctl(-1, Montauk::AUDIO_CTL_SET_MASTER_MUTE, muted ? 1 : 0); + } + inline int audio_get_master_mute() { + return audio_ctl(-1, Montauk::AUDIO_CTL_GET_MASTER_MUTE, 0); + } + inline int audio_set_mute(int handle, bool muted) { + return audio_ctl(handle, Montauk::AUDIO_CTL_SET_MUTE, muted ? 1 : 0); + } + inline int audio_get_mute(int handle) { + return audio_ctl(handle, Montauk::AUDIO_CTL_GET_MUTE, 0); + } + inline int audio_list(Montauk::AudioStreamInfo* buf, int maxCount) { + return (int)syscall2(Montauk::SYS_AUDIOLIST, (uint64_t)buf, (uint64_t)maxCount); + } + // Returns the current mixer state serial. With timeoutMs > 0 the call + // blocks until the serial differs from `prevSerial` or the timeout + // elapses. With timeoutMs == 0 it returns immediately (cheap snapshot). + inline uint64_t audio_wait(uint64_t prevSerial, uint64_t timeoutMs) { + return syscall2(Montauk::SYS_AUDIOWAIT, prevSerial, timeoutMs); + } // Bluetooth inline int bt_scan(Montauk::BtScanResult* buf, int maxCount, uint32_t timeoutMs) { @@ -402,6 +546,30 @@ namespace montauk { // Kernel introspection inline void memstats(Montauk::MemStats* out) { syscall1(Montauk::SYS_MEMSTATS, (uint64_t)out); } + // User management + inline int setuser(int pid, const char* name) { + return (int)syscall2(Montauk::SYS_SETUSER, (uint64_t)pid, (uint64_t)name); + } + inline int getuser(char* buf, uint64_t maxLen) { + return (int)syscall2(Montauk::SYS_GETUSER, (uint64_t)buf, maxLen); + } + + // Clipboard + inline int clipboard_set_text(const char* data, uint32_t len) { + return (int)syscall2(Montauk::SYS_CLIPBOARD_SET_TEXT, (uint64_t)data, (uint64_t)len); + } + inline int clipboard_get_info(Montauk::ClipboardInfo* out) { + return (int)syscall1(Montauk::SYS_CLIPBOARD_GET_INFO, (uint64_t)out); + } + inline int clipboard_get_text(char* buf, uint32_t bufLen, uint32_t* outLen, + uint64_t* outSerial = nullptr) { + return (int)syscall4(Montauk::SYS_CLIPBOARD_GET_TEXT, (uint64_t)buf, (uint64_t)bufLen, + (uint64_t)outLen, (uint64_t)outSerial); + } + inline int clipboard_clear() { + return (int)syscall0(Montauk::SYS_CLIPBOARD_CLEAR); + } + // Window server inline int win_create(const char* title, int w, int h, Montauk::WinCreateResult* result) { return (int)syscall4(Montauk::SYS_WINCREATE, (uint64_t)title, (uint64_t)w, (uint64_t)h, (uint64_t)result); @@ -421,6 +589,9 @@ namespace montauk { inline uint64_t win_map(int id) { return (uint64_t)syscall1(Montauk::SYS_WINMAP, (uint64_t)id); } + inline int win_unmap(int id) { + return (int)syscall1(Montauk::SYS_WINUNMAP, (uint64_t)id); + } inline int win_sendevent(int id, const Montauk::WinEvent* event) { return (int)syscall2(Montauk::SYS_WINSENDEVENT, (uint64_t)id, (uint64_t)event); } diff --git a/template/sysroot/include/montauk/thread.h b/template/sysroot/include/montauk/thread.h new file mode 100644 index 0000000..e4eb5aa --- /dev/null +++ b/template/sysroot/include/montauk/thread.h @@ -0,0 +1,134 @@ +/* + * thread.h + * Userspace threading primitives for MontaukOS + * Copyright (c) 2026 Daniel Hammer + * + * Threads share their parent's address space, IPC handles, cwd, and + * heap allocator. The caller owns the thread stack: thread_spawn + * allocates one out of the user heap and the kernel uses it verbatim. + * + * Lifetimes: + * - thread_spawn returns a positive TID on success. + * - thread_join blocks until the target TID exits, frees its kernel + * stack, then returns its exit code via *out_code. + * - thread_exit terminates only the current thread. If the main thread + * calls exit() (SYS_EXIT) the whole process tears down, killing any + * surviving sibling threads. + * - thread_self returns the calling thread's TID. +*/ + +#pragma once +#include +#include +#include +#include + +namespace montauk { + + // Default per-thread stack size (64 KiB). Enough for typical app work; + // matches the main thread's 32 KiB lower bound with headroom for + // TrueType rendering call chains. + static constexpr uint64_t DEFAULT_THREAD_STACK_BYTES = 64 * 1024; + + using ThreadEntry = int (*)(void* arg); + + // Terminate the calling thread. Never returns. If called by the main + // thread this is equivalent to exit() (the whole process exits). + [[noreturn]] inline void thread_exit(int code = 0) { + syscall1(Montauk::SYS_THREAD_EXIT, (uint64_t)code); + __builtin_unreachable(); + } + + namespace detail { + struct ThreadCtx { + ThreadEntry user_entry; + void* user_arg; + void* stack_base; + }; + + // Userspace trampoline: bridges from the raw entry the kernel jumps + // to into the typed entry, then funnels into SYS_THREAD_EXIT. We + // route the exit through libc rather than relying on a kernel-side + // exit stub on the user stack -- the kernel never writes to user + // memory on this path. + // + // The thread's stack itself is intentionally not freed here: we are + // still running on it. It is reclaimed when the process exits, or + // the joiner may free it explicitly after thread_join. + [[noreturn]] inline void thread_trampoline(detail::ThreadCtx* ctx) { + int code = ctx->user_entry(ctx->user_arg); + montauk::mfree(ctx); + thread_exit(code); + } + } + + // Spawn a new thread that begins executing `entry(arg)`. Returns the + // new TID on success, or -1 on failure. The thread's stack is + // allocated from the user heap; it is leaked on thread exit (the + // thread itself cannot free the stack it is running on). The kernel + // reclaims it on process exit. Callers that need to spawn many short- + // lived threads should pool stacks themselves. + inline int thread_spawn(ThreadEntry entry, void* arg, + uint64_t stack_bytes = 0) { + if (entry == nullptr) return -1; + if (stack_bytes == 0) stack_bytes = DEFAULT_THREAD_STACK_BYTES; + stack_bytes = (stack_bytes + 15) & ~15ULL; + + void* stack = montauk::malloc(stack_bytes); + if (stack == nullptr) return -1; + auto* ctx = (detail::ThreadCtx*)montauk::malloc(sizeof(detail::ThreadCtx)); + if (ctx == nullptr) { + montauk::mfree(stack); + return -1; + } + ctx->user_entry = entry; + ctx->user_arg = arg; + ctx->stack_base = stack; + + uint64_t stack_top = ((uint64_t)stack + stack_bytes) & ~0xFULL; + int tid = (int)syscall3(Montauk::SYS_THREAD_SPAWN, + (uint64_t)&detail::thread_trampoline, + (uint64_t)ctx, stack_top); + if (tid < 0) { + montauk::mfree(ctx); + montauk::mfree(stack); + return -1; + } + return tid; + } + + // Block until the thread identified by `tid` terminates. Returns 0 on + // success (with the thread's exit code in *out_code if non-null) or + // -1 if `tid` is not a joinable sibling. + inline int thread_join(int tid, int* out_code = nullptr) { + return (int)syscall2(Montauk::SYS_THREAD_JOIN, + (uint64_t)tid, (uint64_t)out_code); + } + + // Return the calling thread's TID (== getpid() for the main thread). + inline int thread_self() { + return (int)syscall0(Montauk::SYS_THREAD_SELF); + } + + // Lightweight mutex backed by a single atomic word + the kernel + // yield syscall. Adequate for short critical sections; a heavier + // primitive can wrap mailbox_recv when blocking semantics are needed. + struct Mutex { + volatile uint32_t locked = 0; + + void lock() { + while (__atomic_exchange_n(&locked, 1, __ATOMIC_ACQUIRE) != 0) { + montauk::yield(); + } + } + + bool try_lock() { + return __atomic_exchange_n(&locked, 1, __ATOMIC_ACQUIRE) == 0; + } + + void unlock() { + __atomic_store_n(&locked, 0, __ATOMIC_RELEASE); + } + }; + +} diff --git a/template/sysroot/lib/libbearssl.a b/template/sysroot/lib/libbearssl.a index 40537c5..5318a8e 100644 Binary files a/template/sysroot/lib/libbearssl.a and b/template/sysroot/lib/libbearssl.a differ diff --git a/template/sysroot/lib/libjpeg.a b/template/sysroot/lib/libjpeg.a index 38bca66..f1b0586 100644 Binary files a/template/sysroot/lib/libjpeg.a and b/template/sysroot/lib/libjpeg.a differ diff --git a/template/sysroot/lib/liblibc.a b/template/sysroot/lib/liblibc.a index 6307ce4..39e9168 100644 Binary files a/template/sysroot/lib/liblibc.a and b/template/sysroot/lib/liblibc.a differ diff --git a/template/sysroot/lib/libtls.a b/template/sysroot/lib/libtls.a index 737b973..3923261 100644 Binary files a/template/sysroot/lib/libtls.a and b/template/sysroot/lib/libtls.a differ